PackageManagerService.java revision 84e347f01fa3a0675c3a8d6cc973228a4563b20d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.IActivityManager;
105import android.app.ResourcesManager;
106import android.app.admin.IDevicePolicyManager;
107import android.app.admin.SecurityLog;
108import android.app.backup.IBackupManager;
109import android.content.BroadcastReceiver;
110import android.content.ComponentName;
111import android.content.ContentResolver;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralRequest;
125import android.content.pm.EphemeralResolveInfo;
126import android.content.pm.EphemeralResponse;
127import android.content.pm.FeatureInfo;
128import android.content.pm.IOnPermissionsChangeListener;
129import android.content.pm.IPackageDataObserver;
130import android.content.pm.IPackageDeleteObserver;
131import android.content.pm.IPackageDeleteObserver2;
132import android.content.pm.IPackageInstallObserver2;
133import android.content.pm.IPackageInstaller;
134import android.content.pm.IPackageManager;
135import android.content.pm.IPackageMoveObserver;
136import android.content.pm.IPackageStatsObserver;
137import android.content.pm.InstrumentationInfo;
138import android.content.pm.IntentFilterVerificationInfo;
139import android.content.pm.KeySet;
140import android.content.pm.PackageCleanItem;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageInfoLite;
143import android.content.pm.PackageInstaller;
144import android.content.pm.PackageManager;
145import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
146import android.content.pm.PackageManagerInternal;
147import android.content.pm.PackageParser;
148import android.content.pm.PackageParser.ActivityIntentInfo;
149import android.content.pm.PackageParser.PackageLite;
150import android.content.pm.PackageParser.PackageParserException;
151import android.content.pm.PackageStats;
152import android.content.pm.PackageUserState;
153import android.content.pm.ParceledListSlice;
154import android.content.pm.PermissionGroupInfo;
155import android.content.pm.PermissionInfo;
156import android.content.pm.ProviderInfo;
157import android.content.pm.ResolveInfo;
158import android.content.pm.ServiceInfo;
159import android.content.pm.Signature;
160import android.content.pm.UserInfo;
161import android.content.pm.VerifierDeviceIdentity;
162import android.content.pm.VerifierInfo;
163import android.content.res.Resources;
164import android.graphics.Bitmap;
165import android.hardware.display.DisplayManager;
166import android.net.Uri;
167import android.os.Binder;
168import android.os.Build;
169import android.os.Bundle;
170import android.os.Debug;
171import android.os.Environment;
172import android.os.Environment.UserEnvironment;
173import android.os.FileUtils;
174import android.os.Handler;
175import android.os.IBinder;
176import android.os.Looper;
177import android.os.Message;
178import android.os.Parcel;
179import android.os.ParcelFileDescriptor;
180import android.os.PatternMatcher;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.ShellCallback;
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.IStorageManager;
195import android.os.storage.StorageManagerInternal;
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.Base64;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.Pair;
218import android.util.PrintStreamPrinter;
219import android.util.Slog;
220import android.util.SparseArray;
221import android.util.SparseBooleanArray;
222import android.util.SparseIntArray;
223import android.util.Xml;
224import android.util.jar.StrictJarFile;
225import android.view.Display;
226
227import com.android.internal.R;
228import com.android.internal.annotations.GuardedBy;
229import com.android.internal.app.IMediaContainerService;
230import com.android.internal.app.ResolverActivity;
231import com.android.internal.content.NativeLibraryHelper;
232import com.android.internal.content.PackageHelper;
233import com.android.internal.logging.MetricsLogger;
234import com.android.internal.os.IParcelFileDescriptorFactory;
235import com.android.internal.os.InstallerConnection.InstallerException;
236import com.android.internal.os.RoSystemProperties;
237import com.android.internal.os.SomeArgs;
238import com.android.internal.os.Zygote;
239import com.android.internal.telephony.CarrierAppUtils;
240import com.android.internal.util.ArrayUtils;
241import com.android.internal.util.FastPrintWriter;
242import com.android.internal.util.FastXmlSerializer;
243import com.android.internal.util.IndentingPrintWriter;
244import com.android.internal.util.Preconditions;
245import com.android.internal.util.XmlUtils;
246import com.android.server.AttributeCache;
247import com.android.server.EventLogTags;
248import com.android.server.FgThread;
249import com.android.server.IntentResolver;
250import com.android.server.LocalServices;
251import com.android.server.ServiceThread;
252import com.android.server.SystemConfig;
253import com.android.server.Watchdog;
254import com.android.server.net.NetworkPolicyManagerInternal;
255import com.android.server.pm.PermissionsState.PermissionState;
256import com.android.server.pm.Settings.DatabaseVersion;
257import com.android.server.pm.Settings.VersionInfo;
258import com.android.server.storage.DeviceStorageMonitorInternal;
259
260import dalvik.system.CloseGuard;
261import dalvik.system.DexFile;
262import dalvik.system.VMRuntime;
263
264import libcore.io.IoUtils;
265import libcore.util.EmptyArray;
266
267import org.xmlpull.v1.XmlPullParser;
268import org.xmlpull.v1.XmlPullParserException;
269import org.xmlpull.v1.XmlSerializer;
270
271import java.io.BufferedOutputStream;
272import java.io.BufferedReader;
273import java.io.ByteArrayInputStream;
274import java.io.ByteArrayOutputStream;
275import java.io.File;
276import java.io.FileDescriptor;
277import java.io.FileInputStream;
278import java.io.FileNotFoundException;
279import java.io.FileOutputStream;
280import java.io.FileReader;
281import java.io.FilenameFilter;
282import java.io.IOException;
283import java.io.PrintWriter;
284import java.nio.charset.StandardCharsets;
285import java.security.DigestInputStream;
286import java.security.MessageDigest;
287import java.security.NoSuchAlgorithmException;
288import java.security.PublicKey;
289import java.security.SecureRandom;
290import java.security.cert.Certificate;
291import java.security.cert.CertificateEncodingException;
292import java.security.cert.CertificateException;
293import java.text.SimpleDateFormat;
294import java.util.ArrayList;
295import java.util.Arrays;
296import java.util.Collection;
297import java.util.Collections;
298import java.util.Comparator;
299import java.util.Date;
300import java.util.HashSet;
301import java.util.Iterator;
302import java.util.List;
303import java.util.Map;
304import java.util.Objects;
305import java.util.Set;
306import java.util.concurrent.CountDownLatch;
307import java.util.concurrent.TimeUnit;
308import java.util.concurrent.atomic.AtomicBoolean;
309import java.util.concurrent.atomic.AtomicInteger;
310
311/**
312 * Keep track of all those APKs everywhere.
313 * <p>
314 * Internally there are two important locks:
315 * <ul>
316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
317 * and other related state. It is a fine-grained lock that should only be held
318 * momentarily, as it's one of the most contended locks in the system.
319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
320 * operations typically involve heavy lifting of application data on disk. Since
321 * {@code installd} is single-threaded, and it's operations can often be slow,
322 * this lock should never be acquired while already holding {@link #mPackages}.
323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
324 * holding {@link #mInstallLock}.
325 * </ul>
326 * Many internal methods rely on the caller to hold the appropriate locks, and
327 * this contract is expressed through method name suffixes:
328 * <ul>
329 * <li>fooLI(): the caller must hold {@link #mInstallLock}
330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
331 * being modified must be frozen
332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
334 * </ul>
335 * <p>
336 * Because this class is very central to the platform's security; please run all
337 * CTS and unit tests whenever making modifications:
338 *
339 * <pre>
340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
341 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
342 * </pre>
343 */
344public class PackageManagerService extends IPackageManager.Stub {
345    static final String TAG = "PackageManager";
346    static final boolean DEBUG_SETTINGS = false;
347    static final boolean DEBUG_PREFERRED = false;
348    static final boolean DEBUG_UPGRADE = false;
349    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
350    private static final boolean DEBUG_BACKUP = false;
351    private static final boolean DEBUG_INSTALL = false;
352    private static final boolean DEBUG_REMOVE = false;
353    private static final boolean DEBUG_BROADCASTS = false;
354    private static final boolean DEBUG_SHOW_INFO = false;
355    private static final boolean DEBUG_PACKAGE_INFO = false;
356    private static final boolean DEBUG_INTENT_MATCHING = false;
357    private static final boolean DEBUG_PACKAGE_SCANNING = false;
358    private static final boolean DEBUG_VERIFY = false;
359    private static final boolean DEBUG_FILTERS = false;
360
361    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
362    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
363    // user, but by default initialize to this.
364    static final boolean DEBUG_DEXOPT = false;
365
366    private static final boolean DEBUG_ABI_SELECTION = false;
367    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
368    private static final boolean DEBUG_TRIAGED_MISSING = false;
369    private static final boolean DEBUG_APP_DATA = false;
370
371    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
372    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
373
374    private static final boolean DISABLE_EPHEMERAL_APPS = false;
375    private static final boolean HIDE_EPHEMERAL_APIS = true;
376
377    private static final int RADIO_UID = Process.PHONE_UID;
378    private static final int LOG_UID = Process.LOG_UID;
379    private static final int NFC_UID = Process.NFC_UID;
380    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
381    private static final int SHELL_UID = Process.SHELL_UID;
382
383    // Cap the size of permission trees that 3rd party apps can define
384    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
385
386    // Suffix used during package installation when copying/moving
387    // package apks to install directory.
388    private static final String INSTALL_PACKAGE_SUFFIX = "-";
389
390    static final int SCAN_NO_DEX = 1<<1;
391    static final int SCAN_FORCE_DEX = 1<<2;
392    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
393    static final int SCAN_NEW_INSTALL = 1<<4;
394    static final int SCAN_UPDATE_TIME = 1<<5;
395    static final int SCAN_BOOTING = 1<<6;
396    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
397    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
398    static final int SCAN_REPLACING = 1<<9;
399    static final int SCAN_REQUIRE_KNOWN = 1<<10;
400    static final int SCAN_MOVE = 1<<11;
401    static final int SCAN_INITIAL = 1<<12;
402    static final int SCAN_CHECK_ONLY = 1<<13;
403    static final int SCAN_DONT_KILL_APP = 1<<14;
404    static final int SCAN_IGNORE_FROZEN = 1<<15;
405
406    static final int REMOVE_CHATTY = 1<<16;
407
408    private static final int[] EMPTY_INT_ARRAY = new int[0];
409
410    /**
411     * Timeout (in milliseconds) after which the watchdog should declare that
412     * our handler thread is wedged.  The usual default for such things is one
413     * minute but we sometimes do very lengthy I/O operations on this thread,
414     * such as installing multi-gigabyte applications, so ours needs to be longer.
415     */
416    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
417
418    /**
419     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
420     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
421     * settings entry if available, otherwise we use the hardcoded default.  If it's been
422     * more than this long since the last fstrim, we force one during the boot sequence.
423     *
424     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
425     * one gets run at the next available charging+idle time.  This final mandatory
426     * no-fstrim check kicks in only of the other scheduling criteria is never met.
427     */
428    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
429
430    /**
431     * Whether verification is enabled by default.
432     */
433    private static final boolean DEFAULT_VERIFY_ENABLE = true;
434
435    /**
436     * The default maximum time to wait for the verification agent to return in
437     * milliseconds.
438     */
439    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
440
441    /**
442     * The default response for package verification timeout.
443     *
444     * This can be either PackageManager.VERIFICATION_ALLOW or
445     * PackageManager.VERIFICATION_REJECT.
446     */
447    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
448
449    static final String PLATFORM_PACKAGE_NAME = "android";
450
451    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
452
453    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
454            DEFAULT_CONTAINER_PACKAGE,
455            "com.android.defcontainer.DefaultContainerService");
456
457    private static final String KILL_APP_REASON_GIDS_CHANGED =
458            "permission grant or revoke changed gids";
459
460    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
461            "permissions revoked";
462
463    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
464
465    private static final String PACKAGE_SCHEME = "package";
466
467    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
468    /**
469     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
470     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
471     * VENDOR_OVERLAY_DIR.
472     */
473    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
474    /**
475     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
476     * is in VENDOR_OVERLAY_THEME_PROPERTY.
477     */
478    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
479            = "persist.vendor.overlay.theme";
480
481    /** Permission grant: not grant the permission. */
482    private static final int GRANT_DENIED = 1;
483
484    /** Permission grant: grant the permission as an install permission. */
485    private static final int GRANT_INSTALL = 2;
486
487    /** Permission grant: grant the permission as a runtime one. */
488    private static final int GRANT_RUNTIME = 3;
489
490    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
491    private static final int GRANT_UPGRADE = 4;
492
493    /** Canonical intent used to identify what counts as a "web browser" app */
494    private static final Intent sBrowserIntent;
495    static {
496        sBrowserIntent = new Intent();
497        sBrowserIntent.setAction(Intent.ACTION_VIEW);
498        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
499        sBrowserIntent.setData(Uri.parse("http:"));
500    }
501
502    /**
503     * The set of all protected actions [i.e. those actions for which a high priority
504     * intent filter is disallowed].
505     */
506    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
507    static {
508        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
509        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
510        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
511        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
512    }
513
514    // Compilation reasons.
515    public static final int REASON_FIRST_BOOT = 0;
516    public static final int REASON_BOOT = 1;
517    public static final int REASON_INSTALL = 2;
518    public static final int REASON_BACKGROUND_DEXOPT = 3;
519    public static final int REASON_AB_OTA = 4;
520    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
521    public static final int REASON_SHARED_APK = 6;
522    public static final int REASON_FORCED_DEXOPT = 7;
523    public static final int REASON_CORE_APP = 8;
524
525    public static final int REASON_LAST = REASON_CORE_APP;
526
527    /** Special library name that skips shared libraries check during compilation. */
528    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
529
530    final ServiceThread mHandlerThread;
531
532    final PackageHandler mHandler;
533
534    private final ProcessLoggingHandler mProcessLoggingHandler;
535
536    /**
537     * Messages for {@link #mHandler} that need to wait for system ready before
538     * being dispatched.
539     */
540    private ArrayList<Message> mPostSystemReadyMessages;
541
542    final int mSdkVersion = Build.VERSION.SDK_INT;
543
544    final Context mContext;
545    final boolean mFactoryTest;
546    final boolean mOnlyCore;
547    final DisplayMetrics mMetrics;
548    final int mDefParseFlags;
549    final String[] mSeparateProcesses;
550    final boolean mIsUpgrade;
551    final boolean mIsPreNUpgrade;
552    final boolean mIsPreNMR1Upgrade;
553
554    @GuardedBy("mPackages")
555    private boolean mDexOptDialogShown;
556
557    /** The location for ASEC container files on internal storage. */
558    final String mAsecInternalPath;
559
560    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
561    // LOCK HELD.  Can be called with mInstallLock held.
562    @GuardedBy("mInstallLock")
563    final Installer mInstaller;
564
565    /** Directory where installed third-party apps stored */
566    final File mAppInstallDir;
567    final File mEphemeralInstallDir;
568
569    /**
570     * Directory to which applications installed internally have their
571     * 32 bit native libraries copied.
572     */
573    private File mAppLib32InstallDir;
574
575    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
576    // apps.
577    final File mDrmAppPrivateInstallDir;
578
579    // ----------------------------------------------------------------
580
581    // Lock for state used when installing and doing other long running
582    // operations.  Methods that must be called with this lock held have
583    // the suffix "LI".
584    final Object mInstallLock = new Object();
585
586    // ----------------------------------------------------------------
587
588    // Keys are String (package name), values are Package.  This also serves
589    // as the lock for the global state.  Methods that must be called with
590    // this lock held have the prefix "LP".
591    @GuardedBy("mPackages")
592    final ArrayMap<String, PackageParser.Package> mPackages =
593            new ArrayMap<String, PackageParser.Package>();
594
595    final ArrayMap<String, Set<String>> mKnownCodebase =
596            new ArrayMap<String, Set<String>>();
597
598    // Tracks available target package names -> overlay package paths.
599    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
600        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
601
602    /**
603     * Tracks new system packages [received in an OTA] that we expect to
604     * find updated user-installed versions. Keys are package name, values
605     * are package location.
606     */
607    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
608    /**
609     * Tracks high priority intent filters for protected actions. During boot, certain
610     * filter actions are protected and should never be allowed to have a high priority
611     * intent filter for them. However, there is one, and only one exception -- the
612     * setup wizard. It must be able to define a high priority intent filter for these
613     * actions to ensure there are no escapes from the wizard. We need to delay processing
614     * of these during boot as we need to look at all of the system packages in order
615     * to know which component is the setup wizard.
616     */
617    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
618    /**
619     * Whether or not processing protected filters should be deferred.
620     */
621    private boolean mDeferProtectedFilters = true;
622
623    /**
624     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
625     */
626    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
627    /**
628     * Whether or not system app permissions should be promoted from install to runtime.
629     */
630    boolean mPromoteSystemApps;
631
632    @GuardedBy("mPackages")
633    final Settings mSettings;
634
635    /**
636     * Set of package names that are currently "frozen", which means active
637     * surgery is being done on the code/data for that package. The platform
638     * will refuse to launch frozen packages to avoid race conditions.
639     *
640     * @see PackageFreezer
641     */
642    @GuardedBy("mPackages")
643    final ArraySet<String> mFrozenPackages = new ArraySet<>();
644
645    final ProtectedPackages mProtectedPackages;
646
647    boolean mFirstBoot;
648
649    // System configuration read by SystemConfig.
650    final int[] mGlobalGids;
651    final SparseArray<ArraySet<String>> mSystemPermissions;
652    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
653
654    // If mac_permissions.xml was found for seinfo labeling.
655    boolean mFoundPolicyFile;
656
657    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
658
659    public static final class SharedLibraryEntry {
660        public final String path;
661        public final String apk;
662
663        SharedLibraryEntry(String _path, String _apk) {
664            path = _path;
665            apk = _apk;
666        }
667    }
668
669    // Currently known shared libraries.
670    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
671            new ArrayMap<String, SharedLibraryEntry>();
672
673    // All available activities, for your resolving pleasure.
674    final ActivityIntentResolver mActivities =
675            new ActivityIntentResolver();
676
677    // All available receivers, for your resolving pleasure.
678    final ActivityIntentResolver mReceivers =
679            new ActivityIntentResolver();
680
681    // All available services, for your resolving pleasure.
682    final ServiceIntentResolver mServices = new ServiceIntentResolver();
683
684    // All available providers, for your resolving pleasure.
685    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
686
687    // Mapping from provider base names (first directory in content URI codePath)
688    // to the provider information.
689    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
690            new ArrayMap<String, PackageParser.Provider>();
691
692    // Mapping from instrumentation class names to info about them.
693    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
694            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
695
696    // Mapping from permission names to info about them.
697    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
698            new ArrayMap<String, PackageParser.PermissionGroup>();
699
700    // Packages whose data we have transfered into another package, thus
701    // should no longer exist.
702    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
703
704    // Broadcast actions that are only available to the system.
705    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
706
707    /** List of packages waiting for verification. */
708    final SparseArray<PackageVerificationState> mPendingVerification
709            = new SparseArray<PackageVerificationState>();
710
711    /** Set of packages associated with each app op permission. */
712    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
713
714    final PackageInstallerService mInstallerService;
715
716    private final PackageDexOptimizer mPackageDexOptimizer;
717
718    private AtomicInteger mNextMoveId = new AtomicInteger();
719    private final MoveCallbacks mMoveCallbacks;
720
721    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
722
723    // Cache of users who need badging.
724    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
725
726    /** Token for keys in mPendingVerification. */
727    private int mPendingVerificationToken = 0;
728
729    volatile boolean mSystemReady;
730    volatile boolean mSafeMode;
731    volatile boolean mHasSystemUidErrors;
732
733    ApplicationInfo mAndroidApplication;
734    final ActivityInfo mResolveActivity = new ActivityInfo();
735    final ResolveInfo mResolveInfo = new ResolveInfo();
736    ComponentName mResolveComponentName;
737    PackageParser.Package mPlatformPackage;
738    ComponentName mCustomResolverComponentName;
739
740    boolean mResolverReplaced = false;
741
742    private final @Nullable ComponentName mIntentFilterVerifierComponent;
743    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
744
745    private int mIntentFilterVerificationToken = 0;
746
747    /** Component that knows whether or not an ephemeral application exists */
748    final ComponentName mEphemeralResolverComponent;
749    /** The service connection to the ephemeral resolver */
750    final EphemeralResolverConnection mEphemeralResolverConnection;
751
752    /** Component used to install ephemeral applications */
753    final ComponentName mEphemeralInstallerComponent;
754    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
755    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
756
757    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
758            = new SparseArray<IntentFilterVerificationState>();
759
760    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
761
762    // List of packages names to keep cached, even if they are uninstalled for all users
763    private List<String> mKeepUninstalledPackages;
764
765    private UserManagerInternal mUserManagerInternal;
766
767    private static class IFVerificationParams {
768        PackageParser.Package pkg;
769        boolean replacing;
770        int userId;
771        int verifierUid;
772
773        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
774                int _userId, int _verifierUid) {
775            pkg = _pkg;
776            replacing = _replacing;
777            userId = _userId;
778            replacing = _replacing;
779            verifierUid = _verifierUid;
780        }
781    }
782
783    private interface IntentFilterVerifier<T extends IntentFilter> {
784        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
785                                               T filter, String packageName);
786        void startVerifications(int userId);
787        void receiveVerificationResponse(int verificationId);
788    }
789
790    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
791        private Context mContext;
792        private ComponentName mIntentFilterVerifierComponent;
793        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
794
795        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
796            mContext = context;
797            mIntentFilterVerifierComponent = verifierComponent;
798        }
799
800        private String getDefaultScheme() {
801            return IntentFilter.SCHEME_HTTPS;
802        }
803
804        @Override
805        public void startVerifications(int userId) {
806            // Launch verifications requests
807            int count = mCurrentIntentFilterVerifications.size();
808            for (int n=0; n<count; n++) {
809                int verificationId = mCurrentIntentFilterVerifications.get(n);
810                final IntentFilterVerificationState ivs =
811                        mIntentFilterVerificationStates.get(verificationId);
812
813                String packageName = ivs.getPackageName();
814
815                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
816                final int filterCount = filters.size();
817                ArraySet<String> domainsSet = new ArraySet<>();
818                for (int m=0; m<filterCount; m++) {
819                    PackageParser.ActivityIntentInfo filter = filters.get(m);
820                    domainsSet.addAll(filter.getHostsList());
821                }
822                synchronized (mPackages) {
823                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
824                            packageName, domainsSet) != null) {
825                        scheduleWriteSettingsLocked();
826                    }
827                }
828                sendVerificationRequest(userId, verificationId, ivs);
829            }
830            mCurrentIntentFilterVerifications.clear();
831        }
832
833        private void sendVerificationRequest(int userId, int verificationId,
834                IntentFilterVerificationState ivs) {
835
836            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
837            verificationIntent.putExtra(
838                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
839                    verificationId);
840            verificationIntent.putExtra(
841                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
842                    getDefaultScheme());
843            verificationIntent.putExtra(
844                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
845                    ivs.getHostsString());
846            verificationIntent.putExtra(
847                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
848                    ivs.getPackageName());
849            verificationIntent.setComponent(mIntentFilterVerifierComponent);
850            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
851
852            UserHandle user = new UserHandle(userId);
853            mContext.sendBroadcastAsUser(verificationIntent, user);
854            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
855                    "Sending IntentFilter verification broadcast");
856        }
857
858        public void receiveVerificationResponse(int verificationId) {
859            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
860
861            final boolean verified = ivs.isVerified();
862
863            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
864            final int count = filters.size();
865            if (DEBUG_DOMAIN_VERIFICATION) {
866                Slog.i(TAG, "Received verification response " + verificationId
867                        + " for " + count + " filters, verified=" + verified);
868            }
869            for (int n=0; n<count; n++) {
870                PackageParser.ActivityIntentInfo filter = filters.get(n);
871                filter.setVerified(verified);
872
873                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
874                        + " verified with result:" + verified + " and hosts:"
875                        + ivs.getHostsString());
876            }
877
878            mIntentFilterVerificationStates.remove(verificationId);
879
880            final String packageName = ivs.getPackageName();
881            IntentFilterVerificationInfo ivi = null;
882
883            synchronized (mPackages) {
884                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
885            }
886            if (ivi == null) {
887                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
888                        + verificationId + " packageName:" + packageName);
889                return;
890            }
891            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
892                    "Updating IntentFilterVerificationInfo for package " + packageName
893                            +" verificationId:" + verificationId);
894
895            synchronized (mPackages) {
896                if (verified) {
897                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
898                } else {
899                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
900                }
901                scheduleWriteSettingsLocked();
902
903                final int userId = ivs.getUserId();
904                if (userId != UserHandle.USER_ALL) {
905                    final int userStatus =
906                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
907
908                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
909                    boolean needUpdate = false;
910
911                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
912                    // already been set by the User thru the Disambiguation dialog
913                    switch (userStatus) {
914                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
915                            if (verified) {
916                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
917                            } else {
918                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
919                            }
920                            needUpdate = true;
921                            break;
922
923                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
924                            if (verified) {
925                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
926                                needUpdate = true;
927                            }
928                            break;
929
930                        default:
931                            // Nothing to do
932                    }
933
934                    if (needUpdate) {
935                        mSettings.updateIntentFilterVerificationStatusLPw(
936                                packageName, updatedStatus, userId);
937                        scheduleWritePackageRestrictionsLocked(userId);
938                    }
939                }
940            }
941        }
942
943        @Override
944        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
945                    ActivityIntentInfo filter, String packageName) {
946            if (!hasValidDomains(filter)) {
947                return false;
948            }
949            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
950            if (ivs == null) {
951                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
952                        packageName);
953            }
954            if (DEBUG_DOMAIN_VERIFICATION) {
955                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
956            }
957            ivs.addFilter(filter);
958            return true;
959        }
960
961        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
962                int userId, int verificationId, String packageName) {
963            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
964                    verifierUid, userId, packageName);
965            ivs.setPendingState();
966            synchronized (mPackages) {
967                mIntentFilterVerificationStates.append(verificationId, ivs);
968                mCurrentIntentFilterVerifications.add(verificationId);
969            }
970            return ivs;
971        }
972    }
973
974    private static boolean hasValidDomains(ActivityIntentInfo filter) {
975        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
976                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
977                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
978    }
979
980    // Set of pending broadcasts for aggregating enable/disable of components.
981    static class PendingPackageBroadcasts {
982        // for each user id, a map of <package name -> components within that package>
983        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
984
985        public PendingPackageBroadcasts() {
986            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
987        }
988
989        public ArrayList<String> get(int userId, String packageName) {
990            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
991            return packages.get(packageName);
992        }
993
994        public void put(int userId, String packageName, ArrayList<String> components) {
995            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
996            packages.put(packageName, components);
997        }
998
999        public void remove(int userId, String packageName) {
1000            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1001            if (packages != null) {
1002                packages.remove(packageName);
1003            }
1004        }
1005
1006        public void remove(int userId) {
1007            mUidMap.remove(userId);
1008        }
1009
1010        public int userIdCount() {
1011            return mUidMap.size();
1012        }
1013
1014        public int userIdAt(int n) {
1015            return mUidMap.keyAt(n);
1016        }
1017
1018        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1019            return mUidMap.get(userId);
1020        }
1021
1022        public int size() {
1023            // total number of pending broadcast entries across all userIds
1024            int num = 0;
1025            for (int i = 0; i< mUidMap.size(); i++) {
1026                num += mUidMap.valueAt(i).size();
1027            }
1028            return num;
1029        }
1030
1031        public void clear() {
1032            mUidMap.clear();
1033        }
1034
1035        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1036            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1037            if (map == null) {
1038                map = new ArrayMap<String, ArrayList<String>>();
1039                mUidMap.put(userId, map);
1040            }
1041            return map;
1042        }
1043    }
1044    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1045
1046    // Service Connection to remote media container service to copy
1047    // package uri's from external media onto secure containers
1048    // or internal storage.
1049    private IMediaContainerService mContainerService = null;
1050
1051    static final int SEND_PENDING_BROADCAST = 1;
1052    static final int MCS_BOUND = 3;
1053    static final int END_COPY = 4;
1054    static final int INIT_COPY = 5;
1055    static final int MCS_UNBIND = 6;
1056    static final int START_CLEANING_PACKAGE = 7;
1057    static final int FIND_INSTALL_LOC = 8;
1058    static final int POST_INSTALL = 9;
1059    static final int MCS_RECONNECT = 10;
1060    static final int MCS_GIVE_UP = 11;
1061    static final int UPDATED_MEDIA_STATUS = 12;
1062    static final int WRITE_SETTINGS = 13;
1063    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1064    static final int PACKAGE_VERIFIED = 15;
1065    static final int CHECK_PENDING_VERIFICATION = 16;
1066    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1067    static final int INTENT_FILTER_VERIFIED = 18;
1068    static final int WRITE_PACKAGE_LIST = 19;
1069    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1070
1071    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1072
1073    // Delay time in millisecs
1074    static final int BROADCAST_DELAY = 10 * 1000;
1075
1076    static UserManagerService sUserManager;
1077
1078    // Stores a list of users whose package restrictions file needs to be updated
1079    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1080
1081    final private DefaultContainerConnection mDefContainerConn =
1082            new DefaultContainerConnection();
1083    class DefaultContainerConnection implements ServiceConnection {
1084        public void onServiceConnected(ComponentName name, IBinder service) {
1085            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1086            final IMediaContainerService imcs = IMediaContainerService.Stub
1087                    .asInterface(Binder.allowBlocking(service));
1088            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1089        }
1090
1091        public void onServiceDisconnected(ComponentName name) {
1092            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1093        }
1094    }
1095
1096    // Recordkeeping of restore-after-install operations that are currently in flight
1097    // between the Package Manager and the Backup Manager
1098    static class PostInstallData {
1099        public InstallArgs args;
1100        public PackageInstalledInfo res;
1101
1102        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1103            args = _a;
1104            res = _r;
1105        }
1106    }
1107
1108    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1109    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1110
1111    // XML tags for backup/restore of various bits of state
1112    private static final String TAG_PREFERRED_BACKUP = "pa";
1113    private static final String TAG_DEFAULT_APPS = "da";
1114    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1115
1116    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1117    private static final String TAG_ALL_GRANTS = "rt-grants";
1118    private static final String TAG_GRANT = "grant";
1119    private static final String ATTR_PACKAGE_NAME = "pkg";
1120
1121    private static final String TAG_PERMISSION = "perm";
1122    private static final String ATTR_PERMISSION_NAME = "name";
1123    private static final String ATTR_IS_GRANTED = "g";
1124    private static final String ATTR_USER_SET = "set";
1125    private static final String ATTR_USER_FIXED = "fixed";
1126    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1127
1128    // System/policy permission grants are not backed up
1129    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1130            FLAG_PERMISSION_POLICY_FIXED
1131            | FLAG_PERMISSION_SYSTEM_FIXED
1132            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1133
1134    // And we back up these user-adjusted states
1135    private static final int USER_RUNTIME_GRANT_MASK =
1136            FLAG_PERMISSION_USER_SET
1137            | FLAG_PERMISSION_USER_FIXED
1138            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1139
1140    final @Nullable String mRequiredVerifierPackage;
1141    final @NonNull String mRequiredInstallerPackage;
1142    final @NonNull String mRequiredUninstallerPackage;
1143    final @Nullable String mSetupWizardPackage;
1144    final @Nullable String mStorageManagerPackage;
1145    final @NonNull String mServicesSystemSharedLibraryPackageName;
1146    final @NonNull String mSharedSystemSharedLibraryPackageName;
1147
1148    final boolean mPermissionReviewRequired;
1149
1150    private final PackageUsage mPackageUsage = new PackageUsage();
1151    private final CompilerStats mCompilerStats = new CompilerStats();
1152
1153    class PackageHandler extends Handler {
1154        private boolean mBound = false;
1155        final ArrayList<HandlerParams> mPendingInstalls =
1156            new ArrayList<HandlerParams>();
1157
1158        private boolean connectToService() {
1159            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1160                    " DefaultContainerService");
1161            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1162            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1163            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1164                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1165                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166                mBound = true;
1167                return true;
1168            }
1169            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1170            return false;
1171        }
1172
1173        private void disconnectService() {
1174            mContainerService = null;
1175            mBound = false;
1176            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1177            mContext.unbindService(mDefContainerConn);
1178            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1179        }
1180
1181        PackageHandler(Looper looper) {
1182            super(looper);
1183        }
1184
1185        public void handleMessage(Message msg) {
1186            try {
1187                doHandleMessage(msg);
1188            } finally {
1189                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1190            }
1191        }
1192
1193        void doHandleMessage(Message msg) {
1194            switch (msg.what) {
1195                case INIT_COPY: {
1196                    HandlerParams params = (HandlerParams) msg.obj;
1197                    int idx = mPendingInstalls.size();
1198                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1199                    // If a bind was already initiated we dont really
1200                    // need to do anything. The pending install
1201                    // will be processed later on.
1202                    if (!mBound) {
1203                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1204                                System.identityHashCode(mHandler));
1205                        // If this is the only one pending we might
1206                        // have to bind to the service again.
1207                        if (!connectToService()) {
1208                            Slog.e(TAG, "Failed to bind to media container service");
1209                            params.serviceError();
1210                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1211                                    System.identityHashCode(mHandler));
1212                            if (params.traceMethod != null) {
1213                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1214                                        params.traceCookie);
1215                            }
1216                            return;
1217                        } else {
1218                            // Once we bind to the service, the first
1219                            // pending request will be processed.
1220                            mPendingInstalls.add(idx, params);
1221                        }
1222                    } else {
1223                        mPendingInstalls.add(idx, params);
1224                        // Already bound to the service. Just make
1225                        // sure we trigger off processing the first request.
1226                        if (idx == 0) {
1227                            mHandler.sendEmptyMessage(MCS_BOUND);
1228                        }
1229                    }
1230                    break;
1231                }
1232                case MCS_BOUND: {
1233                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1234                    if (msg.obj != null) {
1235                        mContainerService = (IMediaContainerService) msg.obj;
1236                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1237                                System.identityHashCode(mHandler));
1238                    }
1239                    if (mContainerService == null) {
1240                        if (!mBound) {
1241                            // Something seriously wrong since we are not bound and we are not
1242                            // waiting for connection. Bail out.
1243                            Slog.e(TAG, "Cannot bind to media container service");
1244                            for (HandlerParams params : mPendingInstalls) {
1245                                // Indicate service bind error
1246                                params.serviceError();
1247                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1248                                        System.identityHashCode(params));
1249                                if (params.traceMethod != null) {
1250                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1251                                            params.traceMethod, params.traceCookie);
1252                                }
1253                                return;
1254                            }
1255                            mPendingInstalls.clear();
1256                        } else {
1257                            Slog.w(TAG, "Waiting to connect to media container service");
1258                        }
1259                    } else if (mPendingInstalls.size() > 0) {
1260                        HandlerParams params = mPendingInstalls.get(0);
1261                        if (params != null) {
1262                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1263                                    System.identityHashCode(params));
1264                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1265                            if (params.startCopy()) {
1266                                // We are done...  look for more work or to
1267                                // go idle.
1268                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1269                                        "Checking for more work or unbind...");
1270                                // Delete pending install
1271                                if (mPendingInstalls.size() > 0) {
1272                                    mPendingInstalls.remove(0);
1273                                }
1274                                if (mPendingInstalls.size() == 0) {
1275                                    if (mBound) {
1276                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1277                                                "Posting delayed MCS_UNBIND");
1278                                        removeMessages(MCS_UNBIND);
1279                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1280                                        // Unbind after a little delay, to avoid
1281                                        // continual thrashing.
1282                                        sendMessageDelayed(ubmsg, 10000);
1283                                    }
1284                                } else {
1285                                    // There are more pending requests in queue.
1286                                    // Just post MCS_BOUND message to trigger processing
1287                                    // of next pending install.
1288                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1289                                            "Posting MCS_BOUND for next work");
1290                                    mHandler.sendEmptyMessage(MCS_BOUND);
1291                                }
1292                            }
1293                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1294                        }
1295                    } else {
1296                        // Should never happen ideally.
1297                        Slog.w(TAG, "Empty queue");
1298                    }
1299                    break;
1300                }
1301                case MCS_RECONNECT: {
1302                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1303                    if (mPendingInstalls.size() > 0) {
1304                        if (mBound) {
1305                            disconnectService();
1306                        }
1307                        if (!connectToService()) {
1308                            Slog.e(TAG, "Failed to bind to media container service");
1309                            for (HandlerParams params : mPendingInstalls) {
1310                                // Indicate service bind error
1311                                params.serviceError();
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1313                                        System.identityHashCode(params));
1314                            }
1315                            mPendingInstalls.clear();
1316                        }
1317                    }
1318                    break;
1319                }
1320                case MCS_UNBIND: {
1321                    // If there is no actual work left, then time to unbind.
1322                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1323
1324                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1325                        if (mBound) {
1326                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1327
1328                            disconnectService();
1329                        }
1330                    } else if (mPendingInstalls.size() > 0) {
1331                        // There are more pending requests in queue.
1332                        // Just post MCS_BOUND message to trigger processing
1333                        // of next pending install.
1334                        mHandler.sendEmptyMessage(MCS_BOUND);
1335                    }
1336
1337                    break;
1338                }
1339                case MCS_GIVE_UP: {
1340                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1341                    HandlerParams params = mPendingInstalls.remove(0);
1342                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1343                            System.identityHashCode(params));
1344                    break;
1345                }
1346                case SEND_PENDING_BROADCAST: {
1347                    String packages[];
1348                    ArrayList<String> components[];
1349                    int size = 0;
1350                    int uids[];
1351                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1352                    synchronized (mPackages) {
1353                        if (mPendingBroadcasts == null) {
1354                            return;
1355                        }
1356                        size = mPendingBroadcasts.size();
1357                        if (size <= 0) {
1358                            // Nothing to be done. Just return
1359                            return;
1360                        }
1361                        packages = new String[size];
1362                        components = new ArrayList[size];
1363                        uids = new int[size];
1364                        int i = 0;  // filling out the above arrays
1365
1366                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1367                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1368                            Iterator<Map.Entry<String, ArrayList<String>>> it
1369                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1370                                            .entrySet().iterator();
1371                            while (it.hasNext() && i < size) {
1372                                Map.Entry<String, ArrayList<String>> ent = it.next();
1373                                packages[i] = ent.getKey();
1374                                components[i] = ent.getValue();
1375                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1376                                uids[i] = (ps != null)
1377                                        ? UserHandle.getUid(packageUserId, ps.appId)
1378                                        : -1;
1379                                i++;
1380                            }
1381                        }
1382                        size = i;
1383                        mPendingBroadcasts.clear();
1384                    }
1385                    // Send broadcasts
1386                    for (int i = 0; i < size; i++) {
1387                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1388                    }
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1390                    break;
1391                }
1392                case START_CLEANING_PACKAGE: {
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1394                    final String packageName = (String)msg.obj;
1395                    final int userId = msg.arg1;
1396                    final boolean andCode = msg.arg2 != 0;
1397                    synchronized (mPackages) {
1398                        if (userId == UserHandle.USER_ALL) {
1399                            int[] users = sUserManager.getUserIds();
1400                            for (int user : users) {
1401                                mSettings.addPackageToCleanLPw(
1402                                        new PackageCleanItem(user, packageName, andCode));
1403                            }
1404                        } else {
1405                            mSettings.addPackageToCleanLPw(
1406                                    new PackageCleanItem(userId, packageName, andCode));
1407                        }
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                    startCleaningPackages();
1411                } break;
1412                case POST_INSTALL: {
1413                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1414
1415                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1416                    final boolean didRestore = (msg.arg2 != 0);
1417                    mRunningInstalls.delete(msg.arg1);
1418
1419                    if (data != null) {
1420                        InstallArgs args = data.args;
1421                        PackageInstalledInfo parentRes = data.res;
1422
1423                        final boolean grantPermissions = (args.installFlags
1424                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1425                        final boolean killApp = (args.installFlags
1426                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1427                        final String[] grantedPermissions = args.installGrantPermissions;
1428
1429                        // Handle the parent package
1430                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1431                                grantedPermissions, didRestore, args.installerPackageName,
1432                                args.observer);
1433
1434                        // Handle the child packages
1435                        final int childCount = (parentRes.addedChildPackages != null)
1436                                ? parentRes.addedChildPackages.size() : 0;
1437                        for (int i = 0; i < childCount; i++) {
1438                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1439                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1440                                    grantedPermissions, false, args.installerPackageName,
1441                                    args.observer);
1442                        }
1443
1444                        // Log tracing if needed
1445                        if (args.traceMethod != null) {
1446                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1447                                    args.traceCookie);
1448                        }
1449                    } else {
1450                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1451                    }
1452
1453                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1454                } break;
1455                case UPDATED_MEDIA_STATUS: {
1456                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1457                    boolean reportStatus = msg.arg1 == 1;
1458                    boolean doGc = msg.arg2 == 1;
1459                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1460                    if (doGc) {
1461                        // Force a gc to clear up stale containers.
1462                        Runtime.getRuntime().gc();
1463                    }
1464                    if (msg.obj != null) {
1465                        @SuppressWarnings("unchecked")
1466                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1467                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1468                        // Unload containers
1469                        unloadAllContainers(args);
1470                    }
1471                    if (reportStatus) {
1472                        try {
1473                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1474                                    "Invoking StorageManagerService call back");
1475                            PackageHelper.getStorageManager().finishMediaUpdate();
1476                        } catch (RemoteException e) {
1477                            Log.e(TAG, "StorageManagerService not running?");
1478                        }
1479                    }
1480                } break;
1481                case WRITE_SETTINGS: {
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1483                    synchronized (mPackages) {
1484                        removeMessages(WRITE_SETTINGS);
1485                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1486                        mSettings.writeLPr();
1487                        mDirtyUsers.clear();
1488                    }
1489                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1490                } break;
1491                case WRITE_PACKAGE_RESTRICTIONS: {
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1493                    synchronized (mPackages) {
1494                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1495                        for (int userId : mDirtyUsers) {
1496                            mSettings.writePackageRestrictionsLPr(userId);
1497                        }
1498                        mDirtyUsers.clear();
1499                    }
1500                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1501                } break;
1502                case WRITE_PACKAGE_LIST: {
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1504                    synchronized (mPackages) {
1505                        removeMessages(WRITE_PACKAGE_LIST);
1506                        mSettings.writePackageListLPr(msg.arg1);
1507                    }
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1509                } break;
1510                case CHECK_PENDING_VERIFICATION: {
1511                    final int verificationId = msg.arg1;
1512                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1513
1514                    if ((state != null) && !state.timeoutExtended()) {
1515                        final InstallArgs args = state.getInstallArgs();
1516                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1517
1518                        Slog.i(TAG, "Verification timed out for " + originUri);
1519                        mPendingVerification.remove(verificationId);
1520
1521                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1522
1523                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1524                            Slog.i(TAG, "Continuing with installation of " + originUri);
1525                            state.setVerifierResponse(Binder.getCallingUid(),
1526                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1527                            broadcastPackageVerified(verificationId, originUri,
1528                                    PackageManager.VERIFICATION_ALLOW,
1529                                    state.getInstallArgs().getUser());
1530                            try {
1531                                ret = args.copyApk(mContainerService, true);
1532                            } catch (RemoteException e) {
1533                                Slog.e(TAG, "Could not contact the ContainerService");
1534                            }
1535                        } else {
1536                            broadcastPackageVerified(verificationId, originUri,
1537                                    PackageManager.VERIFICATION_REJECT,
1538                                    state.getInstallArgs().getUser());
1539                        }
1540
1541                        Trace.asyncTraceEnd(
1542                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1543
1544                        processPendingInstall(args, ret);
1545                        mHandler.sendEmptyMessage(MCS_UNBIND);
1546                    }
1547                    break;
1548                }
1549                case PACKAGE_VERIFIED: {
1550                    final int verificationId = msg.arg1;
1551
1552                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1553                    if (state == null) {
1554                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1555                        break;
1556                    }
1557
1558                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1559
1560                    state.setVerifierResponse(response.callerUid, response.code);
1561
1562                    if (state.isVerificationComplete()) {
1563                        mPendingVerification.remove(verificationId);
1564
1565                        final InstallArgs args = state.getInstallArgs();
1566                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1567
1568                        int ret;
1569                        if (state.isInstallAllowed()) {
1570                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1571                            broadcastPackageVerified(verificationId, originUri,
1572                                    response.code, state.getInstallArgs().getUser());
1573                            try {
1574                                ret = args.copyApk(mContainerService, true);
1575                            } catch (RemoteException e) {
1576                                Slog.e(TAG, "Could not contact the ContainerService");
1577                            }
1578                        } else {
1579                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1580                        }
1581
1582                        Trace.asyncTraceEnd(
1583                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1584
1585                        processPendingInstall(args, ret);
1586                        mHandler.sendEmptyMessage(MCS_UNBIND);
1587                    }
1588
1589                    break;
1590                }
1591                case START_INTENT_FILTER_VERIFICATIONS: {
1592                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1593                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1594                            params.replacing, params.pkg);
1595                    break;
1596                }
1597                case INTENT_FILTER_VERIFIED: {
1598                    final int verificationId = msg.arg1;
1599
1600                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1601                            verificationId);
1602                    if (state == null) {
1603                        Slog.w(TAG, "Invalid IntentFilter verification token "
1604                                + verificationId + " received");
1605                        break;
1606                    }
1607
1608                    final int userId = state.getUserId();
1609
1610                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                            "Processing IntentFilter verification with token:"
1612                            + verificationId + " and userId:" + userId);
1613
1614                    final IntentFilterVerificationResponse response =
1615                            (IntentFilterVerificationResponse) msg.obj;
1616
1617                    state.setVerifierResponse(response.callerUid, response.code);
1618
1619                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1620                            "IntentFilter verification with token:" + verificationId
1621                            + " and userId:" + userId
1622                            + " is settings verifier response with response code:"
1623                            + response.code);
1624
1625                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1626                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1627                                + response.getFailedDomainsString());
1628                    }
1629
1630                    if (state.isVerificationComplete()) {
1631                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1632                    } else {
1633                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1634                                "IntentFilter verification with token:" + verificationId
1635                                + " was not said to be complete");
1636                    }
1637
1638                    break;
1639                }
1640                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1641                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1642                            mEphemeralResolverConnection,
1643                            (EphemeralRequest) msg.obj,
1644                            mEphemeralInstallerActivity,
1645                            mHandler);
1646                }
1647            }
1648        }
1649    }
1650
1651    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1652            boolean killApp, String[] grantedPermissions,
1653            boolean launchedForRestore, String installerPackage,
1654            IPackageInstallObserver2 installObserver) {
1655        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1656            // Send the removed broadcasts
1657            if (res.removedInfo != null) {
1658                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1659            }
1660
1661            // Now that we successfully installed the package, grant runtime
1662            // permissions if requested before broadcasting the install.
1663            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1664                    >= Build.VERSION_CODES.M) {
1665                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1666            }
1667
1668            final boolean update = res.removedInfo != null
1669                    && res.removedInfo.removedPackage != null;
1670
1671            // If this is the first time we have child packages for a disabled privileged
1672            // app that had no children, we grant requested runtime permissions to the new
1673            // children if the parent on the system image had them already granted.
1674            if (res.pkg.parentPackage != null) {
1675                synchronized (mPackages) {
1676                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1677                }
1678            }
1679
1680            synchronized (mPackages) {
1681                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1682            }
1683
1684            final String packageName = res.pkg.applicationInfo.packageName;
1685
1686            // Determine the set of users who are adding this package for
1687            // the first time vs. those who are seeing an update.
1688            int[] firstUsers = EMPTY_INT_ARRAY;
1689            int[] updateUsers = EMPTY_INT_ARRAY;
1690            if (res.origUsers == null || res.origUsers.length == 0) {
1691                firstUsers = res.newUsers;
1692            } else {
1693                for (int newUser : res.newUsers) {
1694                    boolean isNew = true;
1695                    for (int origUser : res.origUsers) {
1696                        if (origUser == newUser) {
1697                            isNew = false;
1698                            break;
1699                        }
1700                    }
1701                    if (isNew) {
1702                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1703                    } else {
1704                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1705                    }
1706                }
1707            }
1708
1709            // Send installed broadcasts if the install/update is not ephemeral
1710            if (!isEphemeral(res.pkg)) {
1711                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1712
1713                // Send added for users that see the package for the first time
1714                // sendPackageAddedForNewUsers also deals with system apps
1715                int appId = UserHandle.getAppId(res.uid);
1716                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1717                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1718
1719                // Send added for users that don't see the package for the first time
1720                Bundle extras = new Bundle(1);
1721                extras.putInt(Intent.EXTRA_UID, res.uid);
1722                if (update) {
1723                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1724                }
1725                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1726                        extras, 0 /*flags*/, null /*targetPackage*/,
1727                        null /*finishedReceiver*/, updateUsers);
1728
1729                // Send replaced for users that don't see the package for the first time
1730                if (update) {
1731                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1732                            packageName, extras, 0 /*flags*/,
1733                            null /*targetPackage*/, null /*finishedReceiver*/,
1734                            updateUsers);
1735                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1736                            null /*package*/, null /*extras*/, 0 /*flags*/,
1737                            packageName /*targetPackage*/,
1738                            null /*finishedReceiver*/, updateUsers);
1739                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1740                    // First-install and we did a restore, so we're responsible for the
1741                    // first-launch broadcast.
1742                    if (DEBUG_BACKUP) {
1743                        Slog.i(TAG, "Post-restore of " + packageName
1744                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1745                    }
1746                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1747                }
1748
1749                // Send broadcast package appeared if forward locked/external for all users
1750                // treat asec-hosted packages like removable media on upgrade
1751                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1752                    if (DEBUG_INSTALL) {
1753                        Slog.i(TAG, "upgrading pkg " + res.pkg
1754                                + " is ASEC-hosted -> AVAILABLE");
1755                    }
1756                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1757                    ArrayList<String> pkgList = new ArrayList<>(1);
1758                    pkgList.add(packageName);
1759                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1760                }
1761            }
1762
1763            // Work that needs to happen on first install within each user
1764            if (firstUsers != null && firstUsers.length > 0) {
1765                synchronized (mPackages) {
1766                    for (int userId : firstUsers) {
1767                        // If this app is a browser and it's newly-installed for some
1768                        // users, clear any default-browser state in those users. The
1769                        // app's nature doesn't depend on the user, so we can just check
1770                        // its browser nature in any user and generalize.
1771                        if (packageIsBrowser(packageName, userId)) {
1772                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1773                        }
1774
1775                        // We may also need to apply pending (restored) runtime
1776                        // permission grants within these users.
1777                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1778                    }
1779                }
1780            }
1781
1782            // Log current value of "unknown sources" setting
1783            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1784                    getUnknownSourcesSettings());
1785
1786            // Force a gc to clear up things
1787            Runtime.getRuntime().gc();
1788
1789            // Remove the replaced package's older resources safely now
1790            // We delete after a gc for applications  on sdcard.
1791            if (res.removedInfo != null && res.removedInfo.args != null) {
1792                synchronized (mInstallLock) {
1793                    res.removedInfo.args.doPostDeleteLI(true);
1794                }
1795            }
1796        }
1797
1798        // If someone is watching installs - notify them
1799        if (installObserver != null) {
1800            try {
1801                Bundle extras = extrasForInstallResult(res);
1802                installObserver.onPackageInstalled(res.name, res.returnCode,
1803                        res.returnMsg, extras);
1804            } catch (RemoteException e) {
1805                Slog.i(TAG, "Observer no longer exists.");
1806            }
1807        }
1808    }
1809
1810    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1811            PackageParser.Package pkg) {
1812        if (pkg.parentPackage == null) {
1813            return;
1814        }
1815        if (pkg.requestedPermissions == null) {
1816            return;
1817        }
1818        final PackageSetting disabledSysParentPs = mSettings
1819                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1820        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1821                || !disabledSysParentPs.isPrivileged()
1822                || (disabledSysParentPs.childPackageNames != null
1823                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1824            return;
1825        }
1826        final int[] allUserIds = sUserManager.getUserIds();
1827        final int permCount = pkg.requestedPermissions.size();
1828        for (int i = 0; i < permCount; i++) {
1829            String permission = pkg.requestedPermissions.get(i);
1830            BasePermission bp = mSettings.mPermissions.get(permission);
1831            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1832                continue;
1833            }
1834            for (int userId : allUserIds) {
1835                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1836                        permission, userId)) {
1837                    grantRuntimePermission(pkg.packageName, permission, userId);
1838                }
1839            }
1840        }
1841    }
1842
1843    private StorageEventListener mStorageListener = new StorageEventListener() {
1844        @Override
1845        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1846            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1847                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1848                    final String volumeUuid = vol.getFsUuid();
1849
1850                    // Clean up any users or apps that were removed or recreated
1851                    // while this volume was missing
1852                    reconcileUsers(volumeUuid);
1853                    reconcileApps(volumeUuid);
1854
1855                    // Clean up any install sessions that expired or were
1856                    // cancelled while this volume was missing
1857                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1858
1859                    loadPrivatePackages(vol);
1860
1861                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1862                    unloadPrivatePackages(vol);
1863                }
1864            }
1865
1866            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1867                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1868                    updateExternalMediaStatus(true, false);
1869                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1870                    updateExternalMediaStatus(false, false);
1871                }
1872            }
1873        }
1874
1875        @Override
1876        public void onVolumeForgotten(String fsUuid) {
1877            if (TextUtils.isEmpty(fsUuid)) {
1878                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1879                return;
1880            }
1881
1882            // Remove any apps installed on the forgotten volume
1883            synchronized (mPackages) {
1884                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1885                for (PackageSetting ps : packages) {
1886                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1887                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1888                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1889
1890                    // Try very hard to release any references to this package
1891                    // so we don't risk the system server being killed due to
1892                    // open FDs
1893                    AttributeCache.instance().removePackage(ps.name);
1894                }
1895
1896                mSettings.onVolumeForgotten(fsUuid);
1897                mSettings.writeLPr();
1898            }
1899        }
1900    };
1901
1902    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1903            String[] grantedPermissions) {
1904        for (int userId : userIds) {
1905            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1906        }
1907
1908        // We could have touched GID membership, so flush out packages.list
1909        synchronized (mPackages) {
1910            mSettings.writePackageListLPr();
1911        }
1912    }
1913
1914    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1915            String[] grantedPermissions) {
1916        SettingBase sb = (SettingBase) pkg.mExtras;
1917        if (sb == null) {
1918            return;
1919        }
1920
1921        PermissionsState permissionsState = sb.getPermissionsState();
1922
1923        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1924                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1925
1926        for (String permission : pkg.requestedPermissions) {
1927            final BasePermission bp;
1928            synchronized (mPackages) {
1929                bp = mSettings.mPermissions.get(permission);
1930            }
1931            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1932                    && (grantedPermissions == null
1933                           || ArrayUtils.contains(grantedPermissions, permission))) {
1934                final int flags = permissionsState.getPermissionFlags(permission, userId);
1935                // Installer cannot change immutable permissions.
1936                if ((flags & immutableFlags) == 0) {
1937                    grantRuntimePermission(pkg.packageName, permission, userId);
1938                }
1939            }
1940        }
1941    }
1942
1943    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1944        Bundle extras = null;
1945        switch (res.returnCode) {
1946            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1947                extras = new Bundle();
1948                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1949                        res.origPermission);
1950                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1951                        res.origPackage);
1952                break;
1953            }
1954            case PackageManager.INSTALL_SUCCEEDED: {
1955                extras = new Bundle();
1956                extras.putBoolean(Intent.EXTRA_REPLACING,
1957                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1958                break;
1959            }
1960        }
1961        return extras;
1962    }
1963
1964    void scheduleWriteSettingsLocked() {
1965        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1966            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1967        }
1968    }
1969
1970    void scheduleWritePackageListLocked(int userId) {
1971        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1972            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1973            msg.arg1 = userId;
1974            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1975        }
1976    }
1977
1978    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1979        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1980        scheduleWritePackageRestrictionsLocked(userId);
1981    }
1982
1983    void scheduleWritePackageRestrictionsLocked(int userId) {
1984        final int[] userIds = (userId == UserHandle.USER_ALL)
1985                ? sUserManager.getUserIds() : new int[]{userId};
1986        for (int nextUserId : userIds) {
1987            if (!sUserManager.exists(nextUserId)) return;
1988            mDirtyUsers.add(nextUserId);
1989            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1990                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1991            }
1992        }
1993    }
1994
1995    public static PackageManagerService main(Context context, Installer installer,
1996            boolean factoryTest, boolean onlyCore) {
1997        // Self-check for initial settings.
1998        PackageManagerServiceCompilerMapping.checkProperties();
1999
2000        PackageManagerService m = new PackageManagerService(context, installer,
2001                factoryTest, onlyCore);
2002        m.enableSystemUserPackages();
2003        ServiceManager.addService("package", m);
2004        return m;
2005    }
2006
2007    private void enableSystemUserPackages() {
2008        if (!UserManager.isSplitSystemUser()) {
2009            return;
2010        }
2011        // For system user, enable apps based on the following conditions:
2012        // - app is whitelisted or belong to one of these groups:
2013        //   -- system app which has no launcher icons
2014        //   -- system app which has INTERACT_ACROSS_USERS permission
2015        //   -- system IME app
2016        // - app is not in the blacklist
2017        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2018        Set<String> enableApps = new ArraySet<>();
2019        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2020                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2021                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2022        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2023        enableApps.addAll(wlApps);
2024        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2025                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2026        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2027        enableApps.removeAll(blApps);
2028        Log.i(TAG, "Applications installed for system user: " + enableApps);
2029        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2030                UserHandle.SYSTEM);
2031        final int allAppsSize = allAps.size();
2032        synchronized (mPackages) {
2033            for (int i = 0; i < allAppsSize; i++) {
2034                String pName = allAps.get(i);
2035                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2036                // Should not happen, but we shouldn't be failing if it does
2037                if (pkgSetting == null) {
2038                    continue;
2039                }
2040                boolean install = enableApps.contains(pName);
2041                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2042                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2043                            + " for system user");
2044                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2045                }
2046            }
2047        }
2048    }
2049
2050    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2051        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2052                Context.DISPLAY_SERVICE);
2053        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2054    }
2055
2056    /**
2057     * Requests that files preopted on a secondary system partition be copied to the data partition
2058     * if possible.  Note that the actual copying of the files is accomplished by init for security
2059     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2060     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2061     */
2062    private static void requestCopyPreoptedFiles() {
2063        final int WAIT_TIME_MS = 100;
2064        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2065        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2066            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2067            // We will wait for up to 100 seconds.
2068            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2069            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2070                try {
2071                    Thread.sleep(WAIT_TIME_MS);
2072                } catch (InterruptedException e) {
2073                    // Do nothing
2074                }
2075                if (SystemClock.uptimeMillis() > timeEnd) {
2076                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2077                    Slog.wtf(TAG, "cppreopt did not finish!");
2078                    break;
2079                }
2080            }
2081        }
2082    }
2083
2084    public PackageManagerService(Context context, Installer installer,
2085            boolean factoryTest, boolean onlyCore) {
2086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
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        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2137
2138        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2139                FgThread.get().getLooper());
2140
2141        getDefaultDisplayMetrics(context, mMetrics);
2142
2143        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2144        SystemConfig systemConfig = SystemConfig.getInstance();
2145        mGlobalGids = systemConfig.getGlobalGids();
2146        mSystemPermissions = systemConfig.getSystemPermissions();
2147        mAvailableFeatures = systemConfig.getAvailableFeatures();
2148        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2149
2150        mProtectedPackages = new ProtectedPackages(mContext);
2151
2152        synchronized (mInstallLock) {
2153        // writer
2154        synchronized (mPackages) {
2155            mHandlerThread = new ServiceThread(TAG,
2156                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2157            mHandlerThread.start();
2158            mHandler = new PackageHandler(mHandlerThread.getLooper());
2159            mProcessLoggingHandler = new ProcessLoggingHandler();
2160            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2161
2162            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2163
2164            File dataDir = Environment.getDataDirectory();
2165            mAppInstallDir = new File(dataDir, "app");
2166            mAppLib32InstallDir = new File(dataDir, "app-lib");
2167            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2168            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2169            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2170
2171            sUserManager = new UserManagerService(context, this, mPackages);
2172
2173            // Propagate permission configuration in to package manager.
2174            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2175                    = systemConfig.getPermissions();
2176            for (int i=0; i<permConfig.size(); i++) {
2177                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2178                BasePermission bp = mSettings.mPermissions.get(perm.name);
2179                if (bp == null) {
2180                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2181                    mSettings.mPermissions.put(perm.name, bp);
2182                }
2183                if (perm.gids != null) {
2184                    bp.setGids(perm.gids, perm.perUser);
2185                }
2186            }
2187
2188            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2189            for (int i=0; i<libConfig.size(); i++) {
2190                mSharedLibraries.put(libConfig.keyAt(i),
2191                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2192            }
2193
2194            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2195
2196            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2197            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2198            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2199
2200            if (mFirstBoot) {
2201                requestCopyPreoptedFiles();
2202            }
2203
2204            String customResolverActivity = Resources.getSystem().getString(
2205                    R.string.config_customResolverActivity);
2206            if (TextUtils.isEmpty(customResolverActivity)) {
2207                customResolverActivity = null;
2208            } else {
2209                mCustomResolverComponentName = ComponentName.unflattenFromString(
2210                        customResolverActivity);
2211            }
2212
2213            long startTime = SystemClock.uptimeMillis();
2214
2215            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2216                    startTime);
2217
2218            // Set flag to monitor and not change apk file paths when
2219            // scanning install directories.
2220            final int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2221
2222            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2223            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2224
2225            if (bootClassPath == null) {
2226                Slog.w(TAG, "No BOOTCLASSPATH found!");
2227            }
2228
2229            if (systemServerClassPath == null) {
2230                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2231            }
2232
2233            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2234            final String[] dexCodeInstructionSets =
2235                    getDexCodeInstructionSets(
2236                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2237
2238            /**
2239             * Ensure all external libraries have had dexopt run on them.
2240             */
2241            if (mSharedLibraries.size() > 0) {
2242                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2243                // NOTE: For now, we're compiling these system "shared libraries"
2244                // (and framework jars) into all available architectures. It's possible
2245                // to compile them only when we come across an app that uses them (there's
2246                // already logic for that in scanPackageLI) but that adds some complexity.
2247                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2248                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2249                        final String lib = libEntry.path;
2250                        if (lib == null) {
2251                            continue;
2252                        }
2253
2254                        try {
2255                            // Shared libraries do not have profiles so we perform a full
2256                            // AOT compilation (if needed).
2257                            int dexoptNeeded = DexFile.getDexOptNeeded(
2258                                    lib, dexCodeInstructionSet,
2259                                    getCompilerFilterForReason(REASON_SHARED_APK),
2260                                    false /* newProfile */);
2261                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2262                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2263                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2264                                        getCompilerFilterForReason(REASON_SHARED_APK),
2265                                        StorageManager.UUID_PRIVATE_INTERNAL,
2266                                        SKIP_SHARED_LIBRARY_CHECK);
2267                            }
2268                        } catch (FileNotFoundException e) {
2269                            Slog.w(TAG, "Library not found: " + lib);
2270                        } catch (IOException | InstallerException e) {
2271                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2272                                    + e.getMessage());
2273                        }
2274                    }
2275                }
2276                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2277            }
2278
2279            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2280
2281            final VersionInfo ver = mSettings.getInternalVersion();
2282            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2283
2284            // when upgrading from pre-M, promote system app permissions from install to runtime
2285            mPromoteSystemApps =
2286                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2287
2288            // When upgrading from pre-N, we need to handle package extraction like first boot,
2289            // as there is no profiling data available.
2290            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2291
2292            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2293
2294            // save off the names of pre-existing system packages prior to scanning; we don't
2295            // want to automatically grant runtime permissions for new system apps
2296            if (mPromoteSystemApps) {
2297                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2298                while (pkgSettingIter.hasNext()) {
2299                    PackageSetting ps = pkgSettingIter.next();
2300                    if (isSystemApp(ps)) {
2301                        mExistingSystemPackages.add(ps.name);
2302                    }
2303                }
2304            }
2305
2306            // Collect vendor overlay packages. (Do this before scanning any apps.)
2307            // For security and version matching reason, only consider
2308            // overlay packages if they reside in the right directory.
2309            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2310            if (overlayThemeDir.isEmpty()) {
2311                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2312            }
2313            if (!overlayThemeDir.isEmpty()) {
2314                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2315                        | PackageParser.PARSE_IS_SYSTEM
2316                        | PackageParser.PARSE_IS_SYSTEM_DIR
2317                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2318            }
2319            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2320                    | PackageParser.PARSE_IS_SYSTEM
2321                    | PackageParser.PARSE_IS_SYSTEM_DIR
2322                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2323
2324            // Find base frameworks (resource packages without code).
2325            scanDirTracedLI(frameworkDir, mDefParseFlags
2326                    | PackageParser.PARSE_IS_SYSTEM
2327                    | PackageParser.PARSE_IS_SYSTEM_DIR
2328                    | PackageParser.PARSE_IS_PRIVILEGED,
2329                    scanFlags | SCAN_NO_DEX, 0);
2330
2331            // Collected privileged system packages.
2332            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2333            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2334                    | PackageParser.PARSE_IS_SYSTEM
2335                    | PackageParser.PARSE_IS_SYSTEM_DIR
2336                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2337
2338            // Collect ordinary system packages.
2339            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2340            scanDirTracedLI(systemAppDir, mDefParseFlags
2341                    | PackageParser.PARSE_IS_SYSTEM
2342                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2343
2344            // Collect all vendor packages.
2345            File vendorAppDir = new File("/vendor/app");
2346            try {
2347                vendorAppDir = vendorAppDir.getCanonicalFile();
2348            } catch (IOException e) {
2349                // failed to look up canonical path, continue with original one
2350            }
2351            scanDirTracedLI(vendorAppDir, mDefParseFlags
2352                    | PackageParser.PARSE_IS_SYSTEM
2353                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2354
2355            // Collect all OEM packages.
2356            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2357            scanDirTracedLI(oemAppDir, mDefParseFlags
2358                    | PackageParser.PARSE_IS_SYSTEM
2359                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2360
2361            // Prune any system packages that no longer exist.
2362            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2363            if (!mOnlyCore) {
2364                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2365                while (psit.hasNext()) {
2366                    PackageSetting ps = psit.next();
2367
2368                    /*
2369                     * If this is not a system app, it can't be a
2370                     * disable system app.
2371                     */
2372                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2373                        continue;
2374                    }
2375
2376                    /*
2377                     * If the package is scanned, it's not erased.
2378                     */
2379                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2380                    if (scannedPkg != null) {
2381                        /*
2382                         * If the system app is both scanned and in the
2383                         * disabled packages list, then it must have been
2384                         * added via OTA. Remove it from the currently
2385                         * scanned package so the previously user-installed
2386                         * application can be scanned.
2387                         */
2388                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2389                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2390                                    + ps.name + "; removing system app.  Last known codePath="
2391                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2392                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2393                                    + scannedPkg.mVersionCode);
2394                            removePackageLI(scannedPkg, true);
2395                            mExpectingBetter.put(ps.name, ps.codePath);
2396                        }
2397
2398                        continue;
2399                    }
2400
2401                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2402                        psit.remove();
2403                        logCriticalInfo(Log.WARN, "System package " + ps.name
2404                                + " no longer exists; it's data will be wiped");
2405                        // Actual deletion of code and data will be handled by later
2406                        // reconciliation step
2407                    } else {
2408                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2409                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2410                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2411                        }
2412                    }
2413                }
2414            }
2415
2416            //look for any incomplete package installations
2417            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2418            for (int i = 0; i < deletePkgsList.size(); i++) {
2419                // Actual deletion of code and data will be handled by later
2420                // reconciliation step
2421                final String packageName = deletePkgsList.get(i).name;
2422                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2423                synchronized (mPackages) {
2424                    mSettings.removePackageLPw(packageName);
2425                }
2426            }
2427
2428            //delete tmp files
2429            deleteTempPackageFiles();
2430
2431            // Remove any shared userIDs that have no associated packages
2432            mSettings.pruneSharedUsersLPw();
2433
2434            if (!mOnlyCore) {
2435                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2436                        SystemClock.uptimeMillis());
2437                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2438
2439                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2440                        | PackageParser.PARSE_FORWARD_LOCK,
2441                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2442
2443                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2444                        | PackageParser.PARSE_IS_EPHEMERAL,
2445                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2446
2447                /**
2448                 * Remove disable package settings for any updated system
2449                 * apps that were removed via an OTA. If they're not a
2450                 * previously-updated app, remove them completely.
2451                 * Otherwise, just revoke their system-level permissions.
2452                 */
2453                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2454                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2455                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2456
2457                    String msg;
2458                    if (deletedPkg == null) {
2459                        msg = "Updated system package " + deletedAppName
2460                                + " no longer exists; it's data will be wiped";
2461                        // Actual deletion of code and data will be handled by later
2462                        // reconciliation step
2463                    } else {
2464                        msg = "Updated system app + " + deletedAppName
2465                                + " no longer present; removing system privileges for "
2466                                + deletedAppName;
2467
2468                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2469
2470                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2471                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2472                    }
2473                    logCriticalInfo(Log.WARN, msg);
2474                }
2475
2476                /**
2477                 * Make sure all system apps that we expected to appear on
2478                 * the userdata partition actually showed up. If they never
2479                 * appeared, crawl back and revive the system version.
2480                 */
2481                for (int i = 0; i < mExpectingBetter.size(); i++) {
2482                    final String packageName = mExpectingBetter.keyAt(i);
2483                    if (!mPackages.containsKey(packageName)) {
2484                        final File scanFile = mExpectingBetter.valueAt(i);
2485
2486                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2487                                + " but never showed up; reverting to system");
2488
2489                        int reparseFlags = mDefParseFlags;
2490                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2491                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2492                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2493                                    | PackageParser.PARSE_IS_PRIVILEGED;
2494                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2495                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2496                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2497                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2498                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2499                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2500                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2501                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2502                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2503                        } else {
2504                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2505                            continue;
2506                        }
2507
2508                        mSettings.enableSystemPackageLPw(packageName);
2509
2510                        try {
2511                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2512                        } catch (PackageManagerException e) {
2513                            Slog.e(TAG, "Failed to parse original system package: "
2514                                    + e.getMessage());
2515                        }
2516                    }
2517                }
2518            }
2519            mExpectingBetter.clear();
2520
2521            // Resolve the storage manager.
2522            mStorageManagerPackage = getStorageManagerPackageName();
2523
2524            // Resolve protected action filters. Only the setup wizard is allowed to
2525            // have a high priority filter for these actions.
2526            mSetupWizardPackage = getSetupWizardPackageName();
2527            if (mProtectedFilters.size() > 0) {
2528                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2529                    Slog.i(TAG, "No setup wizard;"
2530                        + " All protected intents capped to priority 0");
2531                }
2532                for (ActivityIntentInfo filter : mProtectedFilters) {
2533                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2534                        if (DEBUG_FILTERS) {
2535                            Slog.i(TAG, "Found setup wizard;"
2536                                + " allow priority " + filter.getPriority() + ";"
2537                                + " package: " + filter.activity.info.packageName
2538                                + " activity: " + filter.activity.className
2539                                + " priority: " + filter.getPriority());
2540                        }
2541                        // skip setup wizard; allow it to keep the high priority filter
2542                        continue;
2543                    }
2544                    Slog.w(TAG, "Protected action; cap priority to 0;"
2545                            + " package: " + filter.activity.info.packageName
2546                            + " activity: " + filter.activity.className
2547                            + " origPrio: " + filter.getPriority());
2548                    filter.setPriority(0);
2549                }
2550            }
2551            mDeferProtectedFilters = false;
2552            mProtectedFilters.clear();
2553
2554            // Now that we know all of the shared libraries, update all clients to have
2555            // the correct library paths.
2556            updateAllSharedLibrariesLPw();
2557
2558            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2559                // NOTE: We ignore potential failures here during a system scan (like
2560                // the rest of the commands above) because there's precious little we
2561                // can do about it. A settings error is reported, though.
2562                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2563            }
2564
2565            // Now that we know all the packages we are keeping,
2566            // read and update their last usage times.
2567            mPackageUsage.read(mPackages);
2568            mCompilerStats.read();
2569
2570            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2571                    SystemClock.uptimeMillis());
2572            Slog.i(TAG, "Time to scan packages: "
2573                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2574                    + " seconds");
2575
2576            // If the platform SDK has changed since the last time we booted,
2577            // we need to re-grant app permission to catch any new ones that
2578            // appear.  This is really a hack, and means that apps can in some
2579            // cases get permissions that the user didn't initially explicitly
2580            // allow...  it would be nice to have some better way to handle
2581            // this situation.
2582            int updateFlags = UPDATE_PERMISSIONS_ALL;
2583            if (ver.sdkVersion != mSdkVersion) {
2584                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2585                        + mSdkVersion + "; regranting permissions for internal storage");
2586                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2587            }
2588            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2589            ver.sdkVersion = mSdkVersion;
2590
2591            // If this is the first boot or an update from pre-M, and it is a normal
2592            // boot, then we need to initialize the default preferred apps across
2593            // all defined users.
2594            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2595                for (UserInfo user : sUserManager.getUsers(true)) {
2596                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2597                    applyFactoryDefaultBrowserLPw(user.id);
2598                    primeDomainVerificationsLPw(user.id);
2599                }
2600            }
2601
2602            // Prepare storage for system user really early during boot,
2603            // since core system apps like SettingsProvider and SystemUI
2604            // can't wait for user to start
2605            final int storageFlags;
2606            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2607                storageFlags = StorageManager.FLAG_STORAGE_DE;
2608            } else {
2609                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2610            }
2611            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2612                    storageFlags, true /* migrateAppData */);
2613
2614            // If this is first boot after an OTA, and a normal boot, then
2615            // we need to clear code cache directories.
2616            // Note that we do *not* clear the application profiles. These remain valid
2617            // across OTAs and are used to drive profile verification (post OTA) and
2618            // profile compilation (without waiting to collect a fresh set of profiles).
2619            if (mIsUpgrade && !onlyCore) {
2620                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2621                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2622                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2623                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2624                        // No apps are running this early, so no need to freeze
2625                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2626                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2627                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2628                    }
2629                }
2630                ver.fingerprint = Build.FINGERPRINT;
2631            }
2632
2633            checkDefaultBrowser();
2634
2635            // clear only after permissions and other defaults have been updated
2636            mExistingSystemPackages.clear();
2637            mPromoteSystemApps = false;
2638
2639            // All the changes are done during package scanning.
2640            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2641
2642            // can downgrade to reader
2643            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2644            mSettings.writeLPr();
2645            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2646
2647            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2648            // early on (before the package manager declares itself as early) because other
2649            // components in the system server might ask for package contexts for these apps.
2650            //
2651            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2652            // (i.e, that the data partition is unavailable).
2653            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2654                long start = System.nanoTime();
2655                List<PackageParser.Package> coreApps = new ArrayList<>();
2656                for (PackageParser.Package pkg : mPackages.values()) {
2657                    if (pkg.coreApp) {
2658                        coreApps.add(pkg);
2659                    }
2660                }
2661
2662                int[] stats = performDexOptUpgrade(coreApps, false,
2663                        getCompilerFilterForReason(REASON_CORE_APP));
2664
2665                final int elapsedTimeSeconds =
2666                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2667                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2668
2669                if (DEBUG_DEXOPT) {
2670                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2671                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2672                }
2673
2674
2675                // TODO: Should we log these stats to tron too ?
2676                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2677                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2678                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2679                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2680            }
2681
2682            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2683                    SystemClock.uptimeMillis());
2684
2685            if (!mOnlyCore) {
2686                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2687                mRequiredInstallerPackage = getRequiredInstallerLPr();
2688                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2689                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2690                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2691                        mIntentFilterVerifierComponent);
2692                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2693                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2694                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2695                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2696            } else {
2697                mRequiredVerifierPackage = null;
2698                mRequiredInstallerPackage = null;
2699                mRequiredUninstallerPackage = null;
2700                mIntentFilterVerifierComponent = null;
2701                mIntentFilterVerifier = null;
2702                mServicesSystemSharedLibraryPackageName = null;
2703                mSharedSystemSharedLibraryPackageName = null;
2704            }
2705
2706            mInstallerService = new PackageInstallerService(context, this);
2707
2708            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2709            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2710            // both the installer and resolver must be present to enable ephemeral
2711            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2712                if (DEBUG_EPHEMERAL) {
2713                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2714                            + " installer:" + ephemeralInstallerComponent);
2715                }
2716                mEphemeralResolverComponent = ephemeralResolverComponent;
2717                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2718                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2719                mEphemeralResolverConnection =
2720                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2721            } else {
2722                if (DEBUG_EPHEMERAL) {
2723                    final String missingComponent =
2724                            (ephemeralResolverComponent == null)
2725                            ? (ephemeralInstallerComponent == null)
2726                                    ? "resolver and installer"
2727                                    : "resolver"
2728                            : "installer";
2729                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2730                }
2731                mEphemeralResolverComponent = null;
2732                mEphemeralInstallerComponent = null;
2733                mEphemeralResolverConnection = null;
2734            }
2735
2736            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2737        } // synchronized (mPackages)
2738        } // synchronized (mInstallLock)
2739
2740        // Now after opening every single application zip, make sure they
2741        // are all flushed.  Not really needed, but keeps things nice and
2742        // tidy.
2743        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2744        Runtime.getRuntime().gc();
2745        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2746
2747        // The initial scanning above does many calls into installd while
2748        // holding the mPackages lock, but we're mostly interested in yelling
2749        // once we have a booted system.
2750        mInstaller.setWarnIfHeld(mPackages);
2751
2752        // Expose private service for system components to use.
2753        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2754        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2755    }
2756
2757    @Override
2758    public boolean isFirstBoot() {
2759        return mFirstBoot;
2760    }
2761
2762    @Override
2763    public boolean isOnlyCoreApps() {
2764        return mOnlyCore;
2765    }
2766
2767    @Override
2768    public boolean isUpgrade() {
2769        return mIsUpgrade;
2770    }
2771
2772    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2773        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2774
2775        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2776                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2777                UserHandle.USER_SYSTEM);
2778        if (matches.size() == 1) {
2779            return matches.get(0).getComponentInfo().packageName;
2780        } else if (matches.size() == 0) {
2781            Log.e(TAG, "There should probably be a verifier, but, none were found");
2782            return null;
2783        }
2784        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2785    }
2786
2787    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2788        synchronized (mPackages) {
2789            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2790            if (libraryEntry == null) {
2791                throw new IllegalStateException("Missing required shared library:" + libraryName);
2792            }
2793            return libraryEntry.apk;
2794        }
2795    }
2796
2797    private @NonNull String getRequiredInstallerLPr() {
2798        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2799        intent.addCategory(Intent.CATEGORY_DEFAULT);
2800        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2801
2802        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2803                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2804                UserHandle.USER_SYSTEM);
2805        if (matches.size() == 1) {
2806            ResolveInfo resolveInfo = matches.get(0);
2807            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2808                throw new RuntimeException("The installer must be a privileged app");
2809            }
2810            return matches.get(0).getComponentInfo().packageName;
2811        } else {
2812            throw new RuntimeException("There must be exactly one installer; found " + matches);
2813        }
2814    }
2815
2816    private @NonNull String getRequiredUninstallerLPr() {
2817        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2818        intent.addCategory(Intent.CATEGORY_DEFAULT);
2819        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2820
2821        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2822                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2823                UserHandle.USER_SYSTEM);
2824        if (resolveInfo == null ||
2825                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2826            throw new RuntimeException("There must be exactly one uninstaller; found "
2827                    + resolveInfo);
2828        }
2829        return resolveInfo.getComponentInfo().packageName;
2830    }
2831
2832    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2833        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2834
2835        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2836                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2837                UserHandle.USER_SYSTEM);
2838        ResolveInfo best = null;
2839        final int N = matches.size();
2840        for (int i = 0; i < N; i++) {
2841            final ResolveInfo cur = matches.get(i);
2842            final String packageName = cur.getComponentInfo().packageName;
2843            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2844                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2845                continue;
2846            }
2847
2848            if (best == null || cur.priority > best.priority) {
2849                best = cur;
2850            }
2851        }
2852
2853        if (best != null) {
2854            return best.getComponentInfo().getComponentName();
2855        } else {
2856            throw new RuntimeException("There must be at least one intent filter verifier");
2857        }
2858    }
2859
2860    private @Nullable ComponentName getEphemeralResolverLPr() {
2861        final String[] packageArray =
2862                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2863        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2864            if (DEBUG_EPHEMERAL) {
2865                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2866            }
2867            return null;
2868        }
2869
2870        final int resolveFlags =
2871                MATCH_DIRECT_BOOT_AWARE
2872                | MATCH_DIRECT_BOOT_UNAWARE
2873                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2874        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2875        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2876                resolveFlags, UserHandle.USER_SYSTEM);
2877
2878        final int N = resolvers.size();
2879        if (N == 0) {
2880            if (DEBUG_EPHEMERAL) {
2881                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2882            }
2883            return null;
2884        }
2885
2886        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2887        for (int i = 0; i < N; i++) {
2888            final ResolveInfo info = resolvers.get(i);
2889
2890            if (info.serviceInfo == null) {
2891                continue;
2892            }
2893
2894            final String packageName = info.serviceInfo.packageName;
2895            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2896                if (DEBUG_EPHEMERAL) {
2897                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2898                            + " pkg: " + packageName + ", info:" + info);
2899                }
2900                continue;
2901            }
2902
2903            if (DEBUG_EPHEMERAL) {
2904                Slog.v(TAG, "Ephemeral resolver found;"
2905                        + " pkg: " + packageName + ", info:" + info);
2906            }
2907            return new ComponentName(packageName, info.serviceInfo.name);
2908        }
2909        if (DEBUG_EPHEMERAL) {
2910            Slog.v(TAG, "Ephemeral resolver NOT found");
2911        }
2912        return null;
2913    }
2914
2915    private @Nullable ComponentName getEphemeralInstallerLPr() {
2916        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2917        intent.addCategory(Intent.CATEGORY_DEFAULT);
2918        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2919
2920        final int resolveFlags =
2921                MATCH_DIRECT_BOOT_AWARE
2922                | MATCH_DIRECT_BOOT_UNAWARE
2923                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2924        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2925                resolveFlags, UserHandle.USER_SYSTEM);
2926        if (matches.size() == 0) {
2927            return null;
2928        } else if (matches.size() == 1) {
2929            return matches.get(0).getComponentInfo().getComponentName();
2930        } else {
2931            throw new RuntimeException(
2932                    "There must be at most one ephemeral installer; found " + matches);
2933        }
2934    }
2935
2936    private void primeDomainVerificationsLPw(int userId) {
2937        if (DEBUG_DOMAIN_VERIFICATION) {
2938            Slog.d(TAG, "Priming domain verifications in user " + userId);
2939        }
2940
2941        SystemConfig systemConfig = SystemConfig.getInstance();
2942        ArraySet<String> packages = systemConfig.getLinkedApps();
2943
2944        for (String packageName : packages) {
2945            PackageParser.Package pkg = mPackages.get(packageName);
2946            if (pkg != null) {
2947                if (!pkg.isSystemApp()) {
2948                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2949                    continue;
2950                }
2951
2952                ArraySet<String> domains = null;
2953                for (PackageParser.Activity a : pkg.activities) {
2954                    for (ActivityIntentInfo filter : a.intents) {
2955                        if (hasValidDomains(filter)) {
2956                            if (domains == null) {
2957                                domains = new ArraySet<String>();
2958                            }
2959                            domains.addAll(filter.getHostsList());
2960                        }
2961                    }
2962                }
2963
2964                if (domains != null && domains.size() > 0) {
2965                    if (DEBUG_DOMAIN_VERIFICATION) {
2966                        Slog.v(TAG, "      + " + packageName);
2967                    }
2968                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2969                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2970                    // and then 'always' in the per-user state actually used for intent resolution.
2971                    final IntentFilterVerificationInfo ivi;
2972                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2973                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2974                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2975                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2976                } else {
2977                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2978                            + "' does not handle web links");
2979                }
2980            } else {
2981                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2982            }
2983        }
2984
2985        scheduleWritePackageRestrictionsLocked(userId);
2986        scheduleWriteSettingsLocked();
2987    }
2988
2989    private void applyFactoryDefaultBrowserLPw(int userId) {
2990        // The default browser app's package name is stored in a string resource,
2991        // with a product-specific overlay used for vendor customization.
2992        String browserPkg = mContext.getResources().getString(
2993                com.android.internal.R.string.default_browser);
2994        if (!TextUtils.isEmpty(browserPkg)) {
2995            // non-empty string => required to be a known package
2996            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2997            if (ps == null) {
2998                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2999                browserPkg = null;
3000            } else {
3001                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3002            }
3003        }
3004
3005        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3006        // default.  If there's more than one, just leave everything alone.
3007        if (browserPkg == null) {
3008            calculateDefaultBrowserLPw(userId);
3009        }
3010    }
3011
3012    private void calculateDefaultBrowserLPw(int userId) {
3013        List<String> allBrowsers = resolveAllBrowserApps(userId);
3014        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3015        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3016    }
3017
3018    private List<String> resolveAllBrowserApps(int userId) {
3019        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3020        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3021                PackageManager.MATCH_ALL, userId);
3022
3023        final int count = list.size();
3024        List<String> result = new ArrayList<String>(count);
3025        for (int i=0; i<count; i++) {
3026            ResolveInfo info = list.get(i);
3027            if (info.activityInfo == null
3028                    || !info.handleAllWebDataURI
3029                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3030                    || result.contains(info.activityInfo.packageName)) {
3031                continue;
3032            }
3033            result.add(info.activityInfo.packageName);
3034        }
3035
3036        return result;
3037    }
3038
3039    private boolean packageIsBrowser(String packageName, int userId) {
3040        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3041                PackageManager.MATCH_ALL, userId);
3042        final int N = list.size();
3043        for (int i = 0; i < N; i++) {
3044            ResolveInfo info = list.get(i);
3045            if (packageName.equals(info.activityInfo.packageName)) {
3046                return true;
3047            }
3048        }
3049        return false;
3050    }
3051
3052    private void checkDefaultBrowser() {
3053        final int myUserId = UserHandle.myUserId();
3054        final String packageName = getDefaultBrowserPackageName(myUserId);
3055        if (packageName != null) {
3056            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3057            if (info == null) {
3058                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3059                synchronized (mPackages) {
3060                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3061                }
3062            }
3063        }
3064    }
3065
3066    @Override
3067    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3068            throws RemoteException {
3069        try {
3070            return super.onTransact(code, data, reply, flags);
3071        } catch (RuntimeException e) {
3072            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3073                Slog.wtf(TAG, "Package Manager Crash", e);
3074            }
3075            throw e;
3076        }
3077    }
3078
3079    static int[] appendInts(int[] cur, int[] add) {
3080        if (add == null) return cur;
3081        if (cur == null) return add;
3082        final int N = add.length;
3083        for (int i=0; i<N; i++) {
3084            cur = appendInt(cur, add[i]);
3085        }
3086        return cur;
3087    }
3088
3089    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3090        if (!sUserManager.exists(userId)) return null;
3091        if (ps == null) {
3092            return null;
3093        }
3094        final PackageParser.Package p = ps.pkg;
3095        if (p == null) {
3096            return null;
3097        }
3098
3099        final PermissionsState permissionsState = ps.getPermissionsState();
3100
3101        // Compute GIDs only if requested
3102        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3103                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3104        // Compute granted permissions only if package has requested permissions
3105        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3106                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3107        final PackageUserState state = ps.readUserState(userId);
3108
3109        return PackageParser.generatePackageInfo(p, gids, flags,
3110                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3111    }
3112
3113    @Override
3114    public void checkPackageStartable(String packageName, int userId) {
3115        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3116
3117        synchronized (mPackages) {
3118            final PackageSetting ps = mSettings.mPackages.get(packageName);
3119            if (ps == null) {
3120                throw new SecurityException("Package " + packageName + " was not found!");
3121            }
3122
3123            if (!ps.getInstalled(userId)) {
3124                throw new SecurityException(
3125                        "Package " + packageName + " was not installed for user " + userId + "!");
3126            }
3127
3128            if (mSafeMode && !ps.isSystem()) {
3129                throw new SecurityException("Package " + packageName + " not a system app!");
3130            }
3131
3132            if (mFrozenPackages.contains(packageName)) {
3133                throw new SecurityException("Package " + packageName + " is currently frozen!");
3134            }
3135
3136            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3137                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3138                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3139            }
3140        }
3141    }
3142
3143    @Override
3144    public boolean isPackageAvailable(String packageName, int userId) {
3145        if (!sUserManager.exists(userId)) return false;
3146        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3147                false /* requireFullPermission */, false /* checkShell */, "is package available");
3148        synchronized (mPackages) {
3149            PackageParser.Package p = mPackages.get(packageName);
3150            if (p != null) {
3151                final PackageSetting ps = (PackageSetting) p.mExtras;
3152                if (ps != null) {
3153                    final PackageUserState state = ps.readUserState(userId);
3154                    if (state != null) {
3155                        return PackageParser.isAvailable(state);
3156                    }
3157                }
3158            }
3159        }
3160        return false;
3161    }
3162
3163    @Override
3164    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3165        if (!sUserManager.exists(userId)) return null;
3166        flags = updateFlagsForPackage(flags, userId, packageName);
3167        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3168                false /* requireFullPermission */, false /* checkShell */, "get package info");
3169        // reader
3170        synchronized (mPackages) {
3171            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3172            PackageParser.Package p = null;
3173            if (matchFactoryOnly) {
3174                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3175                if (ps != null) {
3176                    return generatePackageInfo(ps, flags, userId);
3177                }
3178            }
3179            if (p == null) {
3180                p = mPackages.get(packageName);
3181                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3182                    return null;
3183                }
3184            }
3185            if (DEBUG_PACKAGE_INFO)
3186                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3187            if (p != null) {
3188                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3189            }
3190            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3191                final PackageSetting ps = mSettings.mPackages.get(packageName);
3192                return generatePackageInfo(ps, flags, userId);
3193            }
3194        }
3195        return null;
3196    }
3197
3198    @Override
3199    public String[] currentToCanonicalPackageNames(String[] names) {
3200        String[] out = new String[names.length];
3201        // reader
3202        synchronized (mPackages) {
3203            for (int i=names.length-1; i>=0; i--) {
3204                PackageSetting ps = mSettings.mPackages.get(names[i]);
3205                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3206            }
3207        }
3208        return out;
3209    }
3210
3211    @Override
3212    public String[] canonicalToCurrentPackageNames(String[] names) {
3213        String[] out = new String[names.length];
3214        // reader
3215        synchronized (mPackages) {
3216            for (int i=names.length-1; i>=0; i--) {
3217                String cur = mSettings.getRenamedPackageLPr(names[i]);
3218                out[i] = cur != null ? cur : names[i];
3219            }
3220        }
3221        return out;
3222    }
3223
3224    @Override
3225    public int getPackageUid(String packageName, int flags, int userId) {
3226        if (!sUserManager.exists(userId)) return -1;
3227        flags = updateFlagsForPackage(flags, userId, packageName);
3228        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3229                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3230
3231        // reader
3232        synchronized (mPackages) {
3233            final PackageParser.Package p = mPackages.get(packageName);
3234            if (p != null && p.isMatch(flags)) {
3235                return UserHandle.getUid(userId, p.applicationInfo.uid);
3236            }
3237            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3238                final PackageSetting ps = mSettings.mPackages.get(packageName);
3239                if (ps != null && ps.isMatch(flags)) {
3240                    return UserHandle.getUid(userId, ps.appId);
3241                }
3242            }
3243        }
3244
3245        return -1;
3246    }
3247
3248    @Override
3249    public int[] getPackageGids(String packageName, int flags, int userId) {
3250        if (!sUserManager.exists(userId)) return null;
3251        flags = updateFlagsForPackage(flags, userId, packageName);
3252        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3253                false /* requireFullPermission */, false /* checkShell */,
3254                "getPackageGids");
3255
3256        // reader
3257        synchronized (mPackages) {
3258            final PackageParser.Package p = mPackages.get(packageName);
3259            if (p != null && p.isMatch(flags)) {
3260                PackageSetting ps = (PackageSetting) p.mExtras;
3261                return ps.getPermissionsState().computeGids(userId);
3262            }
3263            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3264                final PackageSetting ps = mSettings.mPackages.get(packageName);
3265                if (ps != null && ps.isMatch(flags)) {
3266                    return ps.getPermissionsState().computeGids(userId);
3267                }
3268            }
3269        }
3270
3271        return null;
3272    }
3273
3274    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3275        if (bp.perm != null) {
3276            return PackageParser.generatePermissionInfo(bp.perm, flags);
3277        }
3278        PermissionInfo pi = new PermissionInfo();
3279        pi.name = bp.name;
3280        pi.packageName = bp.sourcePackage;
3281        pi.nonLocalizedLabel = bp.name;
3282        pi.protectionLevel = bp.protectionLevel;
3283        return pi;
3284    }
3285
3286    @Override
3287    public PermissionInfo getPermissionInfo(String name, int flags) {
3288        // reader
3289        synchronized (mPackages) {
3290            final BasePermission p = mSettings.mPermissions.get(name);
3291            if (p != null) {
3292                return generatePermissionInfo(p, flags);
3293            }
3294            return null;
3295        }
3296    }
3297
3298    @Override
3299    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3300            int flags) {
3301        // reader
3302        synchronized (mPackages) {
3303            if (group != null && !mPermissionGroups.containsKey(group)) {
3304                // This is thrown as NameNotFoundException
3305                return null;
3306            }
3307
3308            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3309            for (BasePermission p : mSettings.mPermissions.values()) {
3310                if (group == null) {
3311                    if (p.perm == null || p.perm.info.group == null) {
3312                        out.add(generatePermissionInfo(p, flags));
3313                    }
3314                } else {
3315                    if (p.perm != null && group.equals(p.perm.info.group)) {
3316                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3317                    }
3318                }
3319            }
3320            return new ParceledListSlice<>(out);
3321        }
3322    }
3323
3324    @Override
3325    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3326        // reader
3327        synchronized (mPackages) {
3328            return PackageParser.generatePermissionGroupInfo(
3329                    mPermissionGroups.get(name), flags);
3330        }
3331    }
3332
3333    @Override
3334    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3335        // reader
3336        synchronized (mPackages) {
3337            final int N = mPermissionGroups.size();
3338            ArrayList<PermissionGroupInfo> out
3339                    = new ArrayList<PermissionGroupInfo>(N);
3340            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3341                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3342            }
3343            return new ParceledListSlice<>(out);
3344        }
3345    }
3346
3347    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3348            int userId) {
3349        if (!sUserManager.exists(userId)) return null;
3350        PackageSetting ps = mSettings.mPackages.get(packageName);
3351        if (ps != null) {
3352            if (ps.pkg == null) {
3353                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3354                if (pInfo != null) {
3355                    return pInfo.applicationInfo;
3356                }
3357                return null;
3358            }
3359            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3360                    ps.readUserState(userId), userId);
3361        }
3362        return null;
3363    }
3364
3365    @Override
3366    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3367        if (!sUserManager.exists(userId)) return null;
3368        flags = updateFlagsForApplication(flags, userId, packageName);
3369        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3370                false /* requireFullPermission */, false /* checkShell */, "get application info");
3371        // writer
3372        synchronized (mPackages) {
3373            PackageParser.Package p = mPackages.get(packageName);
3374            if (DEBUG_PACKAGE_INFO) Log.v(
3375                    TAG, "getApplicationInfo " + packageName
3376                    + ": " + p);
3377            if (p != null) {
3378                PackageSetting ps = mSettings.mPackages.get(packageName);
3379                if (ps == null) return null;
3380                // Note: isEnabledLP() does not apply here - always return info
3381                return PackageParser.generateApplicationInfo(
3382                        p, flags, ps.readUserState(userId), userId);
3383            }
3384            if ("android".equals(packageName)||"system".equals(packageName)) {
3385                return mAndroidApplication;
3386            }
3387            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3388                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3389            }
3390        }
3391        return null;
3392    }
3393
3394    @Override
3395    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3396            final IPackageDataObserver observer) {
3397        mContext.enforceCallingOrSelfPermission(
3398                android.Manifest.permission.CLEAR_APP_CACHE, null);
3399        // Queue up an async operation since clearing cache may take a little while.
3400        mHandler.post(new Runnable() {
3401            public void run() {
3402                mHandler.removeCallbacks(this);
3403                boolean success = true;
3404                synchronized (mInstallLock) {
3405                    try {
3406                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3407                    } catch (InstallerException e) {
3408                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3409                        success = false;
3410                    }
3411                }
3412                if (observer != null) {
3413                    try {
3414                        observer.onRemoveCompleted(null, success);
3415                    } catch (RemoteException e) {
3416                        Slog.w(TAG, "RemoveException when invoking call back");
3417                    }
3418                }
3419            }
3420        });
3421    }
3422
3423    @Override
3424    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3425            final IntentSender pi) {
3426        mContext.enforceCallingOrSelfPermission(
3427                android.Manifest.permission.CLEAR_APP_CACHE, null);
3428        // Queue up an async operation since clearing cache may take a little while.
3429        mHandler.post(new Runnable() {
3430            public void run() {
3431                mHandler.removeCallbacks(this);
3432                boolean success = true;
3433                synchronized (mInstallLock) {
3434                    try {
3435                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3436                    } catch (InstallerException e) {
3437                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3438                        success = false;
3439                    }
3440                }
3441                if(pi != null) {
3442                    try {
3443                        // Callback via pending intent
3444                        int code = success ? 1 : 0;
3445                        pi.sendIntent(null, code, null,
3446                                null, null);
3447                    } catch (SendIntentException e1) {
3448                        Slog.i(TAG, "Failed to send pending intent");
3449                    }
3450                }
3451            }
3452        });
3453    }
3454
3455    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3456        synchronized (mInstallLock) {
3457            try {
3458                mInstaller.freeCache(volumeUuid, freeStorageSize);
3459            } catch (InstallerException e) {
3460                throw new IOException("Failed to free enough space", e);
3461            }
3462        }
3463    }
3464
3465    /**
3466     * Update given flags based on encryption status of current user.
3467     */
3468    private int updateFlags(int flags, int userId) {
3469        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3470                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3471            // Caller expressed an explicit opinion about what encryption
3472            // aware/unaware components they want to see, so fall through and
3473            // give them what they want
3474        } else {
3475            // Caller expressed no opinion, so match based on user state
3476            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3477                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3478            } else {
3479                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3480            }
3481        }
3482        return flags;
3483    }
3484
3485    private UserManagerInternal getUserManagerInternal() {
3486        if (mUserManagerInternal == null) {
3487            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3488        }
3489        return mUserManagerInternal;
3490    }
3491
3492    /**
3493     * Update given flags when being used to request {@link PackageInfo}.
3494     */
3495    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3496        boolean triaged = true;
3497        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3498                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3499            // Caller is asking for component details, so they'd better be
3500            // asking for specific encryption matching behavior, or be triaged
3501            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3502                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3503                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3504                triaged = false;
3505            }
3506        }
3507        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3508                | PackageManager.MATCH_SYSTEM_ONLY
3509                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3510            triaged = false;
3511        }
3512        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3513            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3514                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3515        }
3516        return updateFlags(flags, userId);
3517    }
3518
3519    /**
3520     * Update given flags when being used to request {@link ApplicationInfo}.
3521     */
3522    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3523        return updateFlagsForPackage(flags, userId, cookie);
3524    }
3525
3526    /**
3527     * Update given flags when being used to request {@link ComponentInfo}.
3528     */
3529    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3530        if (cookie instanceof Intent) {
3531            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3532                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3533            }
3534        }
3535
3536        boolean triaged = true;
3537        // Caller is asking for component details, so they'd better be
3538        // asking for specific encryption matching behavior, or be triaged
3539        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3540                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3541                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3542            triaged = false;
3543        }
3544        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3545            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3546                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3547        }
3548
3549        return updateFlags(flags, userId);
3550    }
3551
3552    /**
3553     * Update given flags when being used to request {@link ResolveInfo}.
3554     */
3555    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3556        // Safe mode means we shouldn't match any third-party components
3557        if (mSafeMode) {
3558            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3559        }
3560
3561        return updateFlagsForComponent(flags, userId, cookie);
3562    }
3563
3564    @Override
3565    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3566        if (!sUserManager.exists(userId)) return null;
3567        flags = updateFlagsForComponent(flags, userId, component);
3568        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3569                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3570        synchronized (mPackages) {
3571            PackageParser.Activity a = mActivities.mActivities.get(component);
3572
3573            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3574            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3575                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3576                if (ps == null) return null;
3577                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3578                        userId);
3579            }
3580            if (mResolveComponentName.equals(component)) {
3581                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3582                        new PackageUserState(), userId);
3583            }
3584        }
3585        return null;
3586    }
3587
3588    @Override
3589    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3590            String resolvedType) {
3591        synchronized (mPackages) {
3592            if (component.equals(mResolveComponentName)) {
3593                // The resolver supports EVERYTHING!
3594                return true;
3595            }
3596            PackageParser.Activity a = mActivities.mActivities.get(component);
3597            if (a == null) {
3598                return false;
3599            }
3600            for (int i=0; i<a.intents.size(); i++) {
3601                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3602                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3603                    return true;
3604                }
3605            }
3606            return false;
3607        }
3608    }
3609
3610    @Override
3611    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3612        if (!sUserManager.exists(userId)) return null;
3613        flags = updateFlagsForComponent(flags, userId, component);
3614        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3615                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3616        synchronized (mPackages) {
3617            PackageParser.Activity a = mReceivers.mActivities.get(component);
3618            if (DEBUG_PACKAGE_INFO) Log.v(
3619                TAG, "getReceiverInfo " + component + ": " + a);
3620            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3621                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3622                if (ps == null) return null;
3623                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3624                        userId);
3625            }
3626        }
3627        return null;
3628    }
3629
3630    @Override
3631    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3632        if (!sUserManager.exists(userId)) return null;
3633        flags = updateFlagsForComponent(flags, userId, component);
3634        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3635                false /* requireFullPermission */, false /* checkShell */, "get service info");
3636        synchronized (mPackages) {
3637            PackageParser.Service s = mServices.mServices.get(component);
3638            if (DEBUG_PACKAGE_INFO) Log.v(
3639                TAG, "getServiceInfo " + component + ": " + s);
3640            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3641                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3642                if (ps == null) return null;
3643                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3644                        userId);
3645            }
3646        }
3647        return null;
3648    }
3649
3650    @Override
3651    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3652        if (!sUserManager.exists(userId)) return null;
3653        flags = updateFlagsForComponent(flags, userId, component);
3654        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3655                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3656        synchronized (mPackages) {
3657            PackageParser.Provider p = mProviders.mProviders.get(component);
3658            if (DEBUG_PACKAGE_INFO) Log.v(
3659                TAG, "getProviderInfo " + component + ": " + p);
3660            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3661                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3662                if (ps == null) return null;
3663                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3664                        userId);
3665            }
3666        }
3667        return null;
3668    }
3669
3670    @Override
3671    public String[] getSystemSharedLibraryNames() {
3672        Set<String> libSet;
3673        synchronized (mPackages) {
3674            libSet = mSharedLibraries.keySet();
3675            int size = libSet.size();
3676            if (size > 0) {
3677                String[] libs = new String[size];
3678                libSet.toArray(libs);
3679                return libs;
3680            }
3681        }
3682        return null;
3683    }
3684
3685    @Override
3686    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3687        synchronized (mPackages) {
3688            return mServicesSystemSharedLibraryPackageName;
3689        }
3690    }
3691
3692    @Override
3693    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3694        synchronized (mPackages) {
3695            return mSharedSystemSharedLibraryPackageName;
3696        }
3697    }
3698
3699    @Override
3700    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3701        synchronized (mPackages) {
3702            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3703
3704            final FeatureInfo fi = new FeatureInfo();
3705            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3706                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3707            res.add(fi);
3708
3709            return new ParceledListSlice<>(res);
3710        }
3711    }
3712
3713    @Override
3714    public boolean hasSystemFeature(String name, int version) {
3715        synchronized (mPackages) {
3716            final FeatureInfo feat = mAvailableFeatures.get(name);
3717            if (feat == null) {
3718                return false;
3719            } else {
3720                return feat.version >= version;
3721            }
3722        }
3723    }
3724
3725    @Override
3726    public int checkPermission(String permName, String pkgName, int userId) {
3727        if (!sUserManager.exists(userId)) {
3728            return PackageManager.PERMISSION_DENIED;
3729        }
3730
3731        synchronized (mPackages) {
3732            final PackageParser.Package p = mPackages.get(pkgName);
3733            if (p != null && p.mExtras != null) {
3734                final PackageSetting ps = (PackageSetting) p.mExtras;
3735                final PermissionsState permissionsState = ps.getPermissionsState();
3736                if (permissionsState.hasPermission(permName, userId)) {
3737                    return PackageManager.PERMISSION_GRANTED;
3738                }
3739                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3740                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3741                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3742                    return PackageManager.PERMISSION_GRANTED;
3743                }
3744            }
3745        }
3746
3747        return PackageManager.PERMISSION_DENIED;
3748    }
3749
3750    @Override
3751    public int checkUidPermission(String permName, int uid) {
3752        final int userId = UserHandle.getUserId(uid);
3753
3754        if (!sUserManager.exists(userId)) {
3755            return PackageManager.PERMISSION_DENIED;
3756        }
3757
3758        synchronized (mPackages) {
3759            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3760            if (obj != null) {
3761                final SettingBase ps = (SettingBase) obj;
3762                final PermissionsState permissionsState = ps.getPermissionsState();
3763                if (permissionsState.hasPermission(permName, userId)) {
3764                    return PackageManager.PERMISSION_GRANTED;
3765                }
3766                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3767                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3768                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3769                    return PackageManager.PERMISSION_GRANTED;
3770                }
3771            } else {
3772                ArraySet<String> perms = mSystemPermissions.get(uid);
3773                if (perms != null) {
3774                    if (perms.contains(permName)) {
3775                        return PackageManager.PERMISSION_GRANTED;
3776                    }
3777                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3778                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3779                        return PackageManager.PERMISSION_GRANTED;
3780                    }
3781                }
3782            }
3783        }
3784
3785        return PackageManager.PERMISSION_DENIED;
3786    }
3787
3788    @Override
3789    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3790        if (UserHandle.getCallingUserId() != userId) {
3791            mContext.enforceCallingPermission(
3792                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3793                    "isPermissionRevokedByPolicy for user " + userId);
3794        }
3795
3796        if (checkPermission(permission, packageName, userId)
3797                == PackageManager.PERMISSION_GRANTED) {
3798            return false;
3799        }
3800
3801        final long identity = Binder.clearCallingIdentity();
3802        try {
3803            final int flags = getPermissionFlags(permission, packageName, userId);
3804            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3805        } finally {
3806            Binder.restoreCallingIdentity(identity);
3807        }
3808    }
3809
3810    @Override
3811    public String getPermissionControllerPackageName() {
3812        synchronized (mPackages) {
3813            return mRequiredInstallerPackage;
3814        }
3815    }
3816
3817    /**
3818     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3819     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3820     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3821     * @param message the message to log on security exception
3822     */
3823    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3824            boolean checkShell, String message) {
3825        if (userId < 0) {
3826            throw new IllegalArgumentException("Invalid userId " + userId);
3827        }
3828        if (checkShell) {
3829            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3830        }
3831        if (userId == UserHandle.getUserId(callingUid)) return;
3832        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3833            if (requireFullPermission) {
3834                mContext.enforceCallingOrSelfPermission(
3835                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3836            } else {
3837                try {
3838                    mContext.enforceCallingOrSelfPermission(
3839                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3840                } catch (SecurityException se) {
3841                    mContext.enforceCallingOrSelfPermission(
3842                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3843                }
3844            }
3845        }
3846    }
3847
3848    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3849        if (callingUid == Process.SHELL_UID) {
3850            if (userHandle >= 0
3851                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3852                throw new SecurityException("Shell does not have permission to access user "
3853                        + userHandle);
3854            } else if (userHandle < 0) {
3855                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3856                        + Debug.getCallers(3));
3857            }
3858        }
3859    }
3860
3861    private BasePermission findPermissionTreeLP(String permName) {
3862        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3863            if (permName.startsWith(bp.name) &&
3864                    permName.length() > bp.name.length() &&
3865                    permName.charAt(bp.name.length()) == '.') {
3866                return bp;
3867            }
3868        }
3869        return null;
3870    }
3871
3872    private BasePermission checkPermissionTreeLP(String permName) {
3873        if (permName != null) {
3874            BasePermission bp = findPermissionTreeLP(permName);
3875            if (bp != null) {
3876                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3877                    return bp;
3878                }
3879                throw new SecurityException("Calling uid "
3880                        + Binder.getCallingUid()
3881                        + " is not allowed to add to permission tree "
3882                        + bp.name + " owned by uid " + bp.uid);
3883            }
3884        }
3885        throw new SecurityException("No permission tree found for " + permName);
3886    }
3887
3888    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3889        if (s1 == null) {
3890            return s2 == null;
3891        }
3892        if (s2 == null) {
3893            return false;
3894        }
3895        if (s1.getClass() != s2.getClass()) {
3896            return false;
3897        }
3898        return s1.equals(s2);
3899    }
3900
3901    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3902        if (pi1.icon != pi2.icon) return false;
3903        if (pi1.logo != pi2.logo) return false;
3904        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3905        if (!compareStrings(pi1.name, pi2.name)) return false;
3906        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3907        // We'll take care of setting this one.
3908        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3909        // These are not currently stored in settings.
3910        //if (!compareStrings(pi1.group, pi2.group)) return false;
3911        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3912        //if (pi1.labelRes != pi2.labelRes) return false;
3913        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3914        return true;
3915    }
3916
3917    int permissionInfoFootprint(PermissionInfo info) {
3918        int size = info.name.length();
3919        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3920        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3921        return size;
3922    }
3923
3924    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3925        int size = 0;
3926        for (BasePermission perm : mSettings.mPermissions.values()) {
3927            if (perm.uid == tree.uid) {
3928                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3929            }
3930        }
3931        return size;
3932    }
3933
3934    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3935        // We calculate the max size of permissions defined by this uid and throw
3936        // if that plus the size of 'info' would exceed our stated maximum.
3937        if (tree.uid != Process.SYSTEM_UID) {
3938            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3939            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3940                throw new SecurityException("Permission tree size cap exceeded");
3941            }
3942        }
3943    }
3944
3945    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3946        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3947            throw new SecurityException("Label must be specified in permission");
3948        }
3949        BasePermission tree = checkPermissionTreeLP(info.name);
3950        BasePermission bp = mSettings.mPermissions.get(info.name);
3951        boolean added = bp == null;
3952        boolean changed = true;
3953        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3954        if (added) {
3955            enforcePermissionCapLocked(info, tree);
3956            bp = new BasePermission(info.name, tree.sourcePackage,
3957                    BasePermission.TYPE_DYNAMIC);
3958        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3959            throw new SecurityException(
3960                    "Not allowed to modify non-dynamic permission "
3961                    + info.name);
3962        } else {
3963            if (bp.protectionLevel == fixedLevel
3964                    && bp.perm.owner.equals(tree.perm.owner)
3965                    && bp.uid == tree.uid
3966                    && comparePermissionInfos(bp.perm.info, info)) {
3967                changed = false;
3968            }
3969        }
3970        bp.protectionLevel = fixedLevel;
3971        info = new PermissionInfo(info);
3972        info.protectionLevel = fixedLevel;
3973        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3974        bp.perm.info.packageName = tree.perm.info.packageName;
3975        bp.uid = tree.uid;
3976        if (added) {
3977            mSettings.mPermissions.put(info.name, bp);
3978        }
3979        if (changed) {
3980            if (!async) {
3981                mSettings.writeLPr();
3982            } else {
3983                scheduleWriteSettingsLocked();
3984            }
3985        }
3986        return added;
3987    }
3988
3989    @Override
3990    public boolean addPermission(PermissionInfo info) {
3991        synchronized (mPackages) {
3992            return addPermissionLocked(info, false);
3993        }
3994    }
3995
3996    @Override
3997    public boolean addPermissionAsync(PermissionInfo info) {
3998        synchronized (mPackages) {
3999            return addPermissionLocked(info, true);
4000        }
4001    }
4002
4003    @Override
4004    public void removePermission(String name) {
4005        synchronized (mPackages) {
4006            checkPermissionTreeLP(name);
4007            BasePermission bp = mSettings.mPermissions.get(name);
4008            if (bp != null) {
4009                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4010                    throw new SecurityException(
4011                            "Not allowed to modify non-dynamic permission "
4012                            + name);
4013                }
4014                mSettings.mPermissions.remove(name);
4015                mSettings.writeLPr();
4016            }
4017        }
4018    }
4019
4020    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4021            BasePermission bp) {
4022        int index = pkg.requestedPermissions.indexOf(bp.name);
4023        if (index == -1) {
4024            throw new SecurityException("Package " + pkg.packageName
4025                    + " has not requested permission " + bp.name);
4026        }
4027        if (!bp.isRuntime() && !bp.isDevelopment()) {
4028            throw new SecurityException("Permission " + bp.name
4029                    + " is not a changeable permission type");
4030        }
4031    }
4032
4033    @Override
4034    public void grantRuntimePermission(String packageName, String name, final int userId) {
4035        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4036    }
4037
4038    private void grantRuntimePermission(String packageName, String name, final int userId,
4039            boolean overridePolicy) {
4040        if (!sUserManager.exists(userId)) {
4041            Log.e(TAG, "No such user:" + userId);
4042            return;
4043        }
4044
4045        mContext.enforceCallingOrSelfPermission(
4046                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4047                "grantRuntimePermission");
4048
4049        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4050                true /* requireFullPermission */, true /* checkShell */,
4051                "grantRuntimePermission");
4052
4053        final int uid;
4054        final SettingBase sb;
4055
4056        synchronized (mPackages) {
4057            final PackageParser.Package pkg = mPackages.get(packageName);
4058            if (pkg == null) {
4059                throw new IllegalArgumentException("Unknown package: " + packageName);
4060            }
4061
4062            final BasePermission bp = mSettings.mPermissions.get(name);
4063            if (bp == null) {
4064                throw new IllegalArgumentException("Unknown permission: " + name);
4065            }
4066
4067            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4068
4069            // If a permission review is required for legacy apps we represent
4070            // their permissions as always granted runtime ones since we need
4071            // to keep the review required permission flag per user while an
4072            // install permission's state is shared across all users.
4073            if (mPermissionReviewRequired
4074                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4075                    && bp.isRuntime()) {
4076                return;
4077            }
4078
4079            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4080            sb = (SettingBase) pkg.mExtras;
4081            if (sb == null) {
4082                throw new IllegalArgumentException("Unknown package: " + packageName);
4083            }
4084
4085            final PermissionsState permissionsState = sb.getPermissionsState();
4086
4087            final int flags = permissionsState.getPermissionFlags(name, userId);
4088            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4089                throw new SecurityException("Cannot grant system fixed permission "
4090                        + name + " for package " + packageName);
4091            }
4092            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4093                throw new SecurityException("Cannot grant policy fixed permission "
4094                        + name + " for package " + packageName);
4095            }
4096
4097            if (bp.isDevelopment()) {
4098                // Development permissions must be handled specially, since they are not
4099                // normal runtime permissions.  For now they apply to all users.
4100                if (permissionsState.grantInstallPermission(bp) !=
4101                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4102                    scheduleWriteSettingsLocked();
4103                }
4104                return;
4105            }
4106
4107            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4108                throw new SecurityException("Cannot grant non-ephemeral permission"
4109                        + name + " for package " + packageName);
4110            }
4111
4112            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4113                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4114                return;
4115            }
4116
4117            final int result = permissionsState.grantRuntimePermission(bp, userId);
4118            switch (result) {
4119                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4120                    return;
4121                }
4122
4123                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4124                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4125                    mHandler.post(new Runnable() {
4126                        @Override
4127                        public void run() {
4128                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4129                        }
4130                    });
4131                }
4132                break;
4133            }
4134
4135            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4136
4137            // Not critical if that is lost - app has to request again.
4138            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4139        }
4140
4141        // Only need to do this if user is initialized. Otherwise it's a new user
4142        // and there are no processes running as the user yet and there's no need
4143        // to make an expensive call to remount processes for the changed permissions.
4144        if (READ_EXTERNAL_STORAGE.equals(name)
4145                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4146            final long token = Binder.clearCallingIdentity();
4147            try {
4148                if (sUserManager.isInitialized(userId)) {
4149                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4150                            StorageManagerInternal.class);
4151                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4152                }
4153            } finally {
4154                Binder.restoreCallingIdentity(token);
4155            }
4156        }
4157    }
4158
4159    @Override
4160    public void revokeRuntimePermission(String packageName, String name, int userId) {
4161        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4162    }
4163
4164    private void revokeRuntimePermission(String packageName, String name, int userId,
4165            boolean overridePolicy) {
4166        if (!sUserManager.exists(userId)) {
4167            Log.e(TAG, "No such user:" + userId);
4168            return;
4169        }
4170
4171        mContext.enforceCallingOrSelfPermission(
4172                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4173                "revokeRuntimePermission");
4174
4175        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4176                true /* requireFullPermission */, true /* checkShell */,
4177                "revokeRuntimePermission");
4178
4179        final int appId;
4180
4181        synchronized (mPackages) {
4182            final PackageParser.Package pkg = mPackages.get(packageName);
4183            if (pkg == null) {
4184                throw new IllegalArgumentException("Unknown package: " + packageName);
4185            }
4186
4187            final BasePermission bp = mSettings.mPermissions.get(name);
4188            if (bp == null) {
4189                throw new IllegalArgumentException("Unknown permission: " + name);
4190            }
4191
4192            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4193
4194            // If a permission review is required for legacy apps we represent
4195            // their permissions as always granted runtime ones since we need
4196            // to keep the review required permission flag per user while an
4197            // install permission's state is shared across all users.
4198            if (mPermissionReviewRequired
4199                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4200                    && bp.isRuntime()) {
4201                return;
4202            }
4203
4204            SettingBase sb = (SettingBase) pkg.mExtras;
4205            if (sb == null) {
4206                throw new IllegalArgumentException("Unknown package: " + packageName);
4207            }
4208
4209            final PermissionsState permissionsState = sb.getPermissionsState();
4210
4211            final int flags = permissionsState.getPermissionFlags(name, userId);
4212            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4213                throw new SecurityException("Cannot revoke system fixed permission "
4214                        + name + " for package " + packageName);
4215            }
4216            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4217                throw new SecurityException("Cannot revoke policy fixed permission "
4218                        + name + " for package " + packageName);
4219            }
4220
4221            if (bp.isDevelopment()) {
4222                // Development permissions must be handled specially, since they are not
4223                // normal runtime permissions.  For now they apply to all users.
4224                if (permissionsState.revokeInstallPermission(bp) !=
4225                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4226                    scheduleWriteSettingsLocked();
4227                }
4228                return;
4229            }
4230
4231            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4232                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4233                return;
4234            }
4235
4236            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4237
4238            // Critical, after this call app should never have the permission.
4239            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4240
4241            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4242        }
4243
4244        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4245    }
4246
4247    @Override
4248    public void resetRuntimePermissions() {
4249        mContext.enforceCallingOrSelfPermission(
4250                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4251                "revokeRuntimePermission");
4252
4253        int callingUid = Binder.getCallingUid();
4254        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4255            mContext.enforceCallingOrSelfPermission(
4256                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4257                    "resetRuntimePermissions");
4258        }
4259
4260        synchronized (mPackages) {
4261            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4262            for (int userId : UserManagerService.getInstance().getUserIds()) {
4263                final int packageCount = mPackages.size();
4264                for (int i = 0; i < packageCount; i++) {
4265                    PackageParser.Package pkg = mPackages.valueAt(i);
4266                    if (!(pkg.mExtras instanceof PackageSetting)) {
4267                        continue;
4268                    }
4269                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4270                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4271                }
4272            }
4273        }
4274    }
4275
4276    @Override
4277    public int getPermissionFlags(String name, String packageName, int userId) {
4278        if (!sUserManager.exists(userId)) {
4279            return 0;
4280        }
4281
4282        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4283
4284        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4285                true /* requireFullPermission */, false /* checkShell */,
4286                "getPermissionFlags");
4287
4288        synchronized (mPackages) {
4289            final PackageParser.Package pkg = mPackages.get(packageName);
4290            if (pkg == null) {
4291                return 0;
4292            }
4293
4294            final BasePermission bp = mSettings.mPermissions.get(name);
4295            if (bp == null) {
4296                return 0;
4297            }
4298
4299            SettingBase sb = (SettingBase) pkg.mExtras;
4300            if (sb == null) {
4301                return 0;
4302            }
4303
4304            PermissionsState permissionsState = sb.getPermissionsState();
4305            return permissionsState.getPermissionFlags(name, userId);
4306        }
4307    }
4308
4309    @Override
4310    public void updatePermissionFlags(String name, String packageName, int flagMask,
4311            int flagValues, int userId) {
4312        if (!sUserManager.exists(userId)) {
4313            return;
4314        }
4315
4316        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4317
4318        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4319                true /* requireFullPermission */, true /* checkShell */,
4320                "updatePermissionFlags");
4321
4322        // Only the system can change these flags and nothing else.
4323        if (getCallingUid() != Process.SYSTEM_UID) {
4324            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4325            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4326            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4327            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4328            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4329        }
4330
4331        synchronized (mPackages) {
4332            final PackageParser.Package pkg = mPackages.get(packageName);
4333            if (pkg == null) {
4334                throw new IllegalArgumentException("Unknown package: " + packageName);
4335            }
4336
4337            final BasePermission bp = mSettings.mPermissions.get(name);
4338            if (bp == null) {
4339                throw new IllegalArgumentException("Unknown permission: " + name);
4340            }
4341
4342            SettingBase sb = (SettingBase) pkg.mExtras;
4343            if (sb == null) {
4344                throw new IllegalArgumentException("Unknown package: " + packageName);
4345            }
4346
4347            PermissionsState permissionsState = sb.getPermissionsState();
4348
4349            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4350
4351            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4352                // Install and runtime permissions are stored in different places,
4353                // so figure out what permission changed and persist the change.
4354                if (permissionsState.getInstallPermissionState(name) != null) {
4355                    scheduleWriteSettingsLocked();
4356                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4357                        || hadState) {
4358                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4359                }
4360            }
4361        }
4362    }
4363
4364    /**
4365     * Update the permission flags for all packages and runtime permissions of a user in order
4366     * to allow device or profile owner to remove POLICY_FIXED.
4367     */
4368    @Override
4369    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4370        if (!sUserManager.exists(userId)) {
4371            return;
4372        }
4373
4374        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4375
4376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4377                true /* requireFullPermission */, true /* checkShell */,
4378                "updatePermissionFlagsForAllApps");
4379
4380        // Only the system can change system fixed flags.
4381        if (getCallingUid() != Process.SYSTEM_UID) {
4382            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4383            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4384        }
4385
4386        synchronized (mPackages) {
4387            boolean changed = false;
4388            final int packageCount = mPackages.size();
4389            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4390                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4391                SettingBase sb = (SettingBase) pkg.mExtras;
4392                if (sb == null) {
4393                    continue;
4394                }
4395                PermissionsState permissionsState = sb.getPermissionsState();
4396                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4397                        userId, flagMask, flagValues);
4398            }
4399            if (changed) {
4400                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4401            }
4402        }
4403    }
4404
4405    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4406        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4407                != PackageManager.PERMISSION_GRANTED
4408            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4409                != PackageManager.PERMISSION_GRANTED) {
4410            throw new SecurityException(message + " requires "
4411                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4412                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4413        }
4414    }
4415
4416    @Override
4417    public boolean shouldShowRequestPermissionRationale(String permissionName,
4418            String packageName, int userId) {
4419        if (UserHandle.getCallingUserId() != userId) {
4420            mContext.enforceCallingPermission(
4421                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4422                    "canShowRequestPermissionRationale for user " + userId);
4423        }
4424
4425        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4426        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4427            return false;
4428        }
4429
4430        if (checkPermission(permissionName, packageName, userId)
4431                == PackageManager.PERMISSION_GRANTED) {
4432            return false;
4433        }
4434
4435        final int flags;
4436
4437        final long identity = Binder.clearCallingIdentity();
4438        try {
4439            flags = getPermissionFlags(permissionName,
4440                    packageName, userId);
4441        } finally {
4442            Binder.restoreCallingIdentity(identity);
4443        }
4444
4445        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4446                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4447                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4448
4449        if ((flags & fixedFlags) != 0) {
4450            return false;
4451        }
4452
4453        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4454    }
4455
4456    @Override
4457    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4458        mContext.enforceCallingOrSelfPermission(
4459                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4460                "addOnPermissionsChangeListener");
4461
4462        synchronized (mPackages) {
4463            mOnPermissionChangeListeners.addListenerLocked(listener);
4464        }
4465    }
4466
4467    @Override
4468    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4469        synchronized (mPackages) {
4470            mOnPermissionChangeListeners.removeListenerLocked(listener);
4471        }
4472    }
4473
4474    @Override
4475    public boolean isProtectedBroadcast(String actionName) {
4476        synchronized (mPackages) {
4477            if (mProtectedBroadcasts.contains(actionName)) {
4478                return true;
4479            } else if (actionName != null) {
4480                // TODO: remove these terrible hacks
4481                if (actionName.startsWith("android.net.netmon.lingerExpired")
4482                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4483                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4484                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4485                    return true;
4486                }
4487            }
4488        }
4489        return false;
4490    }
4491
4492    @Override
4493    public int checkSignatures(String pkg1, String pkg2) {
4494        synchronized (mPackages) {
4495            final PackageParser.Package p1 = mPackages.get(pkg1);
4496            final PackageParser.Package p2 = mPackages.get(pkg2);
4497            if (p1 == null || p1.mExtras == null
4498                    || p2 == null || p2.mExtras == null) {
4499                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4500            }
4501            return compareSignatures(p1.mSignatures, p2.mSignatures);
4502        }
4503    }
4504
4505    @Override
4506    public int checkUidSignatures(int uid1, int uid2) {
4507        // Map to base uids.
4508        uid1 = UserHandle.getAppId(uid1);
4509        uid2 = UserHandle.getAppId(uid2);
4510        // reader
4511        synchronized (mPackages) {
4512            Signature[] s1;
4513            Signature[] s2;
4514            Object obj = mSettings.getUserIdLPr(uid1);
4515            if (obj != null) {
4516                if (obj instanceof SharedUserSetting) {
4517                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4518                } else if (obj instanceof PackageSetting) {
4519                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4520                } else {
4521                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4522                }
4523            } else {
4524                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4525            }
4526            obj = mSettings.getUserIdLPr(uid2);
4527            if (obj != null) {
4528                if (obj instanceof SharedUserSetting) {
4529                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4530                } else if (obj instanceof PackageSetting) {
4531                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4532                } else {
4533                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4534                }
4535            } else {
4536                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4537            }
4538            return compareSignatures(s1, s2);
4539        }
4540    }
4541
4542    /**
4543     * This method should typically only be used when granting or revoking
4544     * permissions, since the app may immediately restart after this call.
4545     * <p>
4546     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4547     * guard your work against the app being relaunched.
4548     */
4549    private void killUid(int appId, int userId, String reason) {
4550        final long identity = Binder.clearCallingIdentity();
4551        try {
4552            IActivityManager am = ActivityManager.getService();
4553            if (am != null) {
4554                try {
4555                    am.killUid(appId, userId, reason);
4556                } catch (RemoteException e) {
4557                    /* ignore - same process */
4558                }
4559            }
4560        } finally {
4561            Binder.restoreCallingIdentity(identity);
4562        }
4563    }
4564
4565    /**
4566     * Compares two sets of signatures. Returns:
4567     * <br />
4568     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4569     * <br />
4570     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4571     * <br />
4572     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4573     * <br />
4574     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4575     * <br />
4576     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4577     */
4578    static int compareSignatures(Signature[] s1, Signature[] s2) {
4579        if (s1 == null) {
4580            return s2 == null
4581                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4582                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4583        }
4584
4585        if (s2 == null) {
4586            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4587        }
4588
4589        if (s1.length != s2.length) {
4590            return PackageManager.SIGNATURE_NO_MATCH;
4591        }
4592
4593        // Since both signature sets are of size 1, we can compare without HashSets.
4594        if (s1.length == 1) {
4595            return s1[0].equals(s2[0]) ?
4596                    PackageManager.SIGNATURE_MATCH :
4597                    PackageManager.SIGNATURE_NO_MATCH;
4598        }
4599
4600        ArraySet<Signature> set1 = new ArraySet<Signature>();
4601        for (Signature sig : s1) {
4602            set1.add(sig);
4603        }
4604        ArraySet<Signature> set2 = new ArraySet<Signature>();
4605        for (Signature sig : s2) {
4606            set2.add(sig);
4607        }
4608        // Make sure s2 contains all signatures in s1.
4609        if (set1.equals(set2)) {
4610            return PackageManager.SIGNATURE_MATCH;
4611        }
4612        return PackageManager.SIGNATURE_NO_MATCH;
4613    }
4614
4615    /**
4616     * If the database version for this type of package (internal storage or
4617     * external storage) is less than the version where package signatures
4618     * were updated, return true.
4619     */
4620    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4621        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4622        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4623    }
4624
4625    /**
4626     * Used for backward compatibility to make sure any packages with
4627     * certificate chains get upgraded to the new style. {@code existingSigs}
4628     * will be in the old format (since they were stored on disk from before the
4629     * system upgrade) and {@code scannedSigs} will be in the newer format.
4630     */
4631    private int compareSignaturesCompat(PackageSignatures existingSigs,
4632            PackageParser.Package scannedPkg) {
4633        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4634            return PackageManager.SIGNATURE_NO_MATCH;
4635        }
4636
4637        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4638        for (Signature sig : existingSigs.mSignatures) {
4639            existingSet.add(sig);
4640        }
4641        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4642        for (Signature sig : scannedPkg.mSignatures) {
4643            try {
4644                Signature[] chainSignatures = sig.getChainSignatures();
4645                for (Signature chainSig : chainSignatures) {
4646                    scannedCompatSet.add(chainSig);
4647                }
4648            } catch (CertificateEncodingException e) {
4649                scannedCompatSet.add(sig);
4650            }
4651        }
4652        /*
4653         * Make sure the expanded scanned set contains all signatures in the
4654         * existing one.
4655         */
4656        if (scannedCompatSet.equals(existingSet)) {
4657            // Migrate the old signatures to the new scheme.
4658            existingSigs.assignSignatures(scannedPkg.mSignatures);
4659            // The new KeySets will be re-added later in the scanning process.
4660            synchronized (mPackages) {
4661                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4662            }
4663            return PackageManager.SIGNATURE_MATCH;
4664        }
4665        return PackageManager.SIGNATURE_NO_MATCH;
4666    }
4667
4668    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4669        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4670        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4671    }
4672
4673    private int compareSignaturesRecover(PackageSignatures existingSigs,
4674            PackageParser.Package scannedPkg) {
4675        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4676            return PackageManager.SIGNATURE_NO_MATCH;
4677        }
4678
4679        String msg = null;
4680        try {
4681            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4682                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4683                        + scannedPkg.packageName);
4684                return PackageManager.SIGNATURE_MATCH;
4685            }
4686        } catch (CertificateException e) {
4687            msg = e.getMessage();
4688        }
4689
4690        logCriticalInfo(Log.INFO,
4691                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4692        return PackageManager.SIGNATURE_NO_MATCH;
4693    }
4694
4695    @Override
4696    public List<String> getAllPackages() {
4697        synchronized (mPackages) {
4698            return new ArrayList<String>(mPackages.keySet());
4699        }
4700    }
4701
4702    @Override
4703    public String[] getPackagesForUid(int uid) {
4704        final int userId = UserHandle.getUserId(uid);
4705        uid = UserHandle.getAppId(uid);
4706        // reader
4707        synchronized (mPackages) {
4708            Object obj = mSettings.getUserIdLPr(uid);
4709            if (obj instanceof SharedUserSetting) {
4710                final SharedUserSetting sus = (SharedUserSetting) obj;
4711                final int N = sus.packages.size();
4712                String[] res = new String[N];
4713                final Iterator<PackageSetting> it = sus.packages.iterator();
4714                int i = 0;
4715                while (it.hasNext()) {
4716                    PackageSetting ps = it.next();
4717                    if (ps.getInstalled(userId)) {
4718                        res[i++] = ps.name;
4719                    } else {
4720                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4721                    }
4722                }
4723                return res;
4724            } else if (obj instanceof PackageSetting) {
4725                final PackageSetting ps = (PackageSetting) obj;
4726                return new String[] { ps.name };
4727            }
4728        }
4729        return null;
4730    }
4731
4732    @Override
4733    public String getNameForUid(int uid) {
4734        // reader
4735        synchronized (mPackages) {
4736            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4737            if (obj instanceof SharedUserSetting) {
4738                final SharedUserSetting sus = (SharedUserSetting) obj;
4739                return sus.name + ":" + sus.userId;
4740            } else if (obj instanceof PackageSetting) {
4741                final PackageSetting ps = (PackageSetting) obj;
4742                return ps.name;
4743            }
4744        }
4745        return null;
4746    }
4747
4748    @Override
4749    public int getUidForSharedUser(String sharedUserName) {
4750        if(sharedUserName == null) {
4751            return -1;
4752        }
4753        // reader
4754        synchronized (mPackages) {
4755            SharedUserSetting suid;
4756            try {
4757                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4758                if (suid != null) {
4759                    return suid.userId;
4760                }
4761            } catch (PackageManagerException ignore) {
4762                // can't happen, but, still need to catch it
4763            }
4764            return -1;
4765        }
4766    }
4767
4768    @Override
4769    public int getFlagsForUid(int uid) {
4770        synchronized (mPackages) {
4771            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4772            if (obj instanceof SharedUserSetting) {
4773                final SharedUserSetting sus = (SharedUserSetting) obj;
4774                return sus.pkgFlags;
4775            } else if (obj instanceof PackageSetting) {
4776                final PackageSetting ps = (PackageSetting) obj;
4777                return ps.pkgFlags;
4778            }
4779        }
4780        return 0;
4781    }
4782
4783    @Override
4784    public int getPrivateFlagsForUid(int uid) {
4785        synchronized (mPackages) {
4786            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4787            if (obj instanceof SharedUserSetting) {
4788                final SharedUserSetting sus = (SharedUserSetting) obj;
4789                return sus.pkgPrivateFlags;
4790            } else if (obj instanceof PackageSetting) {
4791                final PackageSetting ps = (PackageSetting) obj;
4792                return ps.pkgPrivateFlags;
4793            }
4794        }
4795        return 0;
4796    }
4797
4798    @Override
4799    public boolean isUidPrivileged(int uid) {
4800        uid = UserHandle.getAppId(uid);
4801        // reader
4802        synchronized (mPackages) {
4803            Object obj = mSettings.getUserIdLPr(uid);
4804            if (obj instanceof SharedUserSetting) {
4805                final SharedUserSetting sus = (SharedUserSetting) obj;
4806                final Iterator<PackageSetting> it = sus.packages.iterator();
4807                while (it.hasNext()) {
4808                    if (it.next().isPrivileged()) {
4809                        return true;
4810                    }
4811                }
4812            } else if (obj instanceof PackageSetting) {
4813                final PackageSetting ps = (PackageSetting) obj;
4814                return ps.isPrivileged();
4815            }
4816        }
4817        return false;
4818    }
4819
4820    @Override
4821    public String[] getAppOpPermissionPackages(String permissionName) {
4822        synchronized (mPackages) {
4823            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4824            if (pkgs == null) {
4825                return null;
4826            }
4827            return pkgs.toArray(new String[pkgs.size()]);
4828        }
4829    }
4830
4831    @Override
4832    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4833            int flags, int userId) {
4834        try {
4835            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4836
4837            if (!sUserManager.exists(userId)) return null;
4838            flags = updateFlagsForResolve(flags, userId, intent);
4839            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4840                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4841
4842            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4843            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4844                    flags, userId);
4845            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4846
4847            final ResolveInfo bestChoice =
4848                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4849            return bestChoice;
4850        } finally {
4851            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4852        }
4853    }
4854
4855    @Override
4856    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4857            IntentFilter filter, int match, ComponentName activity) {
4858        final int userId = UserHandle.getCallingUserId();
4859        if (DEBUG_PREFERRED) {
4860            Log.v(TAG, "setLastChosenActivity intent=" + intent
4861                + " resolvedType=" + resolvedType
4862                + " flags=" + flags
4863                + " filter=" + filter
4864                + " match=" + match
4865                + " activity=" + activity);
4866            filter.dump(new PrintStreamPrinter(System.out), "    ");
4867        }
4868        intent.setComponent(null);
4869        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4870                userId);
4871        // Find any earlier preferred or last chosen entries and nuke them
4872        findPreferredActivity(intent, resolvedType,
4873                flags, query, 0, false, true, false, userId);
4874        // Add the new activity as the last chosen for this filter
4875        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4876                "Setting last chosen");
4877    }
4878
4879    @Override
4880    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4881        final int userId = UserHandle.getCallingUserId();
4882        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4883        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4884                userId);
4885        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4886                false, false, false, userId);
4887    }
4888
4889    private boolean isEphemeralDisabled() {
4890        // ephemeral apps have been disabled across the board
4891        if (DISABLE_EPHEMERAL_APPS) {
4892            return true;
4893        }
4894        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4895        if (!mSystemReady) {
4896            return true;
4897        }
4898        // we can't get a content resolver until the system is ready; these checks must happen last
4899        final ContentResolver resolver = mContext.getContentResolver();
4900        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4901            return true;
4902        }
4903        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4904    }
4905
4906    private boolean isEphemeralAllowed(
4907            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4908            boolean skipPackageCheck) {
4909        // Short circuit and return early if possible.
4910        if (isEphemeralDisabled()) {
4911            return false;
4912        }
4913        final int callingUser = UserHandle.getCallingUserId();
4914        if (callingUser != UserHandle.USER_SYSTEM) {
4915            return false;
4916        }
4917        if (mEphemeralResolverConnection == null) {
4918            return false;
4919        }
4920        if (intent.getComponent() != null) {
4921            return false;
4922        }
4923        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4924            return false;
4925        }
4926        if (!skipPackageCheck && intent.getPackage() != null) {
4927            return false;
4928        }
4929        final boolean isWebUri = hasWebURI(intent);
4930        if (!isWebUri || intent.getData().getHost() == null) {
4931            return false;
4932        }
4933        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4934        synchronized (mPackages) {
4935            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4936            for (int n = 0; n < count; n++) {
4937                ResolveInfo info = resolvedActivities.get(n);
4938                String packageName = info.activityInfo.packageName;
4939                PackageSetting ps = mSettings.mPackages.get(packageName);
4940                if (ps != null) {
4941                    // Try to get the status from User settings first
4942                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4943                    int status = (int) (packedStatus >> 32);
4944                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4945                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4946                        if (DEBUG_EPHEMERAL) {
4947                            Slog.v(TAG, "DENY ephemeral apps;"
4948                                + " pkg: " + packageName + ", status: " + status);
4949                        }
4950                        return false;
4951                    }
4952                }
4953            }
4954        }
4955        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4956        return true;
4957    }
4958
4959    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
4960            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
4961            int userId) {
4962        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
4963                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
4964                        callingPackage, userId));
4965        mHandler.sendMessage(msg);
4966    }
4967
4968    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4969            int flags, List<ResolveInfo> query, int userId) {
4970        if (query != null) {
4971            final int N = query.size();
4972            if (N == 1) {
4973                return query.get(0);
4974            } else if (N > 1) {
4975                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4976                // If there is more than one activity with the same priority,
4977                // then let the user decide between them.
4978                ResolveInfo r0 = query.get(0);
4979                ResolveInfo r1 = query.get(1);
4980                if (DEBUG_INTENT_MATCHING || debug) {
4981                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4982                            + r1.activityInfo.name + "=" + r1.priority);
4983                }
4984                // If the first activity has a higher priority, or a different
4985                // default, then it is always desirable to pick it.
4986                if (r0.priority != r1.priority
4987                        || r0.preferredOrder != r1.preferredOrder
4988                        || r0.isDefault != r1.isDefault) {
4989                    return query.get(0);
4990                }
4991                // If we have saved a preference for a preferred activity for
4992                // this Intent, use that.
4993                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4994                        flags, query, r0.priority, true, false, debug, userId);
4995                if (ri != null) {
4996                    return ri;
4997                }
4998                ri = new ResolveInfo(mResolveInfo);
4999                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5000                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5001                // If all of the options come from the same package, show the application's
5002                // label and icon instead of the generic resolver's.
5003                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5004                // and then throw away the ResolveInfo itself, meaning that the caller loses
5005                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5006                // a fallback for this case; we only set the target package's resources on
5007                // the ResolveInfo, not the ActivityInfo.
5008                final String intentPackage = intent.getPackage();
5009                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5010                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5011                    ri.resolvePackageName = intentPackage;
5012                    if (userNeedsBadging(userId)) {
5013                        ri.noResourceId = true;
5014                    } else {
5015                        ri.icon = appi.icon;
5016                    }
5017                    ri.iconResourceId = appi.icon;
5018                    ri.labelRes = appi.labelRes;
5019                }
5020                ri.activityInfo.applicationInfo = new ApplicationInfo(
5021                        ri.activityInfo.applicationInfo);
5022                if (userId != 0) {
5023                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5024                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5025                }
5026                // Make sure that the resolver is displayable in car mode
5027                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5028                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5029                return ri;
5030            }
5031        }
5032        return null;
5033    }
5034
5035    /**
5036     * Return true if the given list is not empty and all of its contents have
5037     * an activityInfo with the given package name.
5038     */
5039    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5040        if (ArrayUtils.isEmpty(list)) {
5041            return false;
5042        }
5043        for (int i = 0, N = list.size(); i < N; i++) {
5044            final ResolveInfo ri = list.get(i);
5045            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5046            if (ai == null || !packageName.equals(ai.packageName)) {
5047                return false;
5048            }
5049        }
5050        return true;
5051    }
5052
5053    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5054            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5055        final int N = query.size();
5056        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5057                .get(userId);
5058        // Get the list of persistent preferred activities that handle the intent
5059        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5060        List<PersistentPreferredActivity> pprefs = ppir != null
5061                ? ppir.queryIntent(intent, resolvedType,
5062                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5063                : null;
5064        if (pprefs != null && pprefs.size() > 0) {
5065            final int M = pprefs.size();
5066            for (int i=0; i<M; i++) {
5067                final PersistentPreferredActivity ppa = pprefs.get(i);
5068                if (DEBUG_PREFERRED || debug) {
5069                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5070                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5071                            + "\n  component=" + ppa.mComponent);
5072                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5073                }
5074                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5075                        flags | MATCH_DISABLED_COMPONENTS, userId);
5076                if (DEBUG_PREFERRED || debug) {
5077                    Slog.v(TAG, "Found persistent preferred activity:");
5078                    if (ai != null) {
5079                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5080                    } else {
5081                        Slog.v(TAG, "  null");
5082                    }
5083                }
5084                if (ai == null) {
5085                    // This previously registered persistent preferred activity
5086                    // component is no longer known. Ignore it and do NOT remove it.
5087                    continue;
5088                }
5089                for (int j=0; j<N; j++) {
5090                    final ResolveInfo ri = query.get(j);
5091                    if (!ri.activityInfo.applicationInfo.packageName
5092                            .equals(ai.applicationInfo.packageName)) {
5093                        continue;
5094                    }
5095                    if (!ri.activityInfo.name.equals(ai.name)) {
5096                        continue;
5097                    }
5098                    //  Found a persistent preference that can handle the intent.
5099                    if (DEBUG_PREFERRED || debug) {
5100                        Slog.v(TAG, "Returning persistent preferred activity: " +
5101                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5102                    }
5103                    return ri;
5104                }
5105            }
5106        }
5107        return null;
5108    }
5109
5110    // TODO: handle preferred activities missing while user has amnesia
5111    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5112            List<ResolveInfo> query, int priority, boolean always,
5113            boolean removeMatches, boolean debug, int userId) {
5114        if (!sUserManager.exists(userId)) return null;
5115        flags = updateFlagsForResolve(flags, userId, intent);
5116        // writer
5117        synchronized (mPackages) {
5118            if (intent.getSelector() != null) {
5119                intent = intent.getSelector();
5120            }
5121            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5122
5123            // Try to find a matching persistent preferred activity.
5124            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5125                    debug, userId);
5126
5127            // If a persistent preferred activity matched, use it.
5128            if (pri != null) {
5129                return pri;
5130            }
5131
5132            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5133            // Get the list of preferred activities that handle the intent
5134            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5135            List<PreferredActivity> prefs = pir != null
5136                    ? pir.queryIntent(intent, resolvedType,
5137                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5138                    : null;
5139            if (prefs != null && prefs.size() > 0) {
5140                boolean changed = false;
5141                try {
5142                    // First figure out how good the original match set is.
5143                    // We will only allow preferred activities that came
5144                    // from the same match quality.
5145                    int match = 0;
5146
5147                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5148
5149                    final int N = query.size();
5150                    for (int j=0; j<N; j++) {
5151                        final ResolveInfo ri = query.get(j);
5152                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5153                                + ": 0x" + Integer.toHexString(match));
5154                        if (ri.match > match) {
5155                            match = ri.match;
5156                        }
5157                    }
5158
5159                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5160                            + Integer.toHexString(match));
5161
5162                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5163                    final int M = prefs.size();
5164                    for (int i=0; i<M; i++) {
5165                        final PreferredActivity pa = prefs.get(i);
5166                        if (DEBUG_PREFERRED || debug) {
5167                            Slog.v(TAG, "Checking PreferredActivity ds="
5168                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5169                                    + "\n  component=" + pa.mPref.mComponent);
5170                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5171                        }
5172                        if (pa.mPref.mMatch != match) {
5173                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5174                                    + Integer.toHexString(pa.mPref.mMatch));
5175                            continue;
5176                        }
5177                        // If it's not an "always" type preferred activity and that's what we're
5178                        // looking for, skip it.
5179                        if (always && !pa.mPref.mAlways) {
5180                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5181                            continue;
5182                        }
5183                        final ActivityInfo ai = getActivityInfo(
5184                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5185                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5186                                userId);
5187                        if (DEBUG_PREFERRED || debug) {
5188                            Slog.v(TAG, "Found preferred activity:");
5189                            if (ai != null) {
5190                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5191                            } else {
5192                                Slog.v(TAG, "  null");
5193                            }
5194                        }
5195                        if (ai == null) {
5196                            // This previously registered preferred activity
5197                            // component is no longer known.  Most likely an update
5198                            // to the app was installed and in the new version this
5199                            // component no longer exists.  Clean it up by removing
5200                            // it from the preferred activities list, and skip it.
5201                            Slog.w(TAG, "Removing dangling preferred activity: "
5202                                    + pa.mPref.mComponent);
5203                            pir.removeFilter(pa);
5204                            changed = true;
5205                            continue;
5206                        }
5207                        for (int j=0; j<N; j++) {
5208                            final ResolveInfo ri = query.get(j);
5209                            if (!ri.activityInfo.applicationInfo.packageName
5210                                    .equals(ai.applicationInfo.packageName)) {
5211                                continue;
5212                            }
5213                            if (!ri.activityInfo.name.equals(ai.name)) {
5214                                continue;
5215                            }
5216
5217                            if (removeMatches) {
5218                                pir.removeFilter(pa);
5219                                changed = true;
5220                                if (DEBUG_PREFERRED) {
5221                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5222                                }
5223                                break;
5224                            }
5225
5226                            // Okay we found a previously set preferred or last chosen app.
5227                            // If the result set is different from when this
5228                            // was created, we need to clear it and re-ask the
5229                            // user their preference, if we're looking for an "always" type entry.
5230                            if (always && !pa.mPref.sameSet(query)) {
5231                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5232                                        + intent + " type " + resolvedType);
5233                                if (DEBUG_PREFERRED) {
5234                                    Slog.v(TAG, "Removing preferred activity since set changed "
5235                                            + pa.mPref.mComponent);
5236                                }
5237                                pir.removeFilter(pa);
5238                                // Re-add the filter as a "last chosen" entry (!always)
5239                                PreferredActivity lastChosen = new PreferredActivity(
5240                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5241                                pir.addFilter(lastChosen);
5242                                changed = true;
5243                                return null;
5244                            }
5245
5246                            // Yay! Either the set matched or we're looking for the last chosen
5247                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5248                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5249                            return ri;
5250                        }
5251                    }
5252                } finally {
5253                    if (changed) {
5254                        if (DEBUG_PREFERRED) {
5255                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5256                        }
5257                        scheduleWritePackageRestrictionsLocked(userId);
5258                    }
5259                }
5260            }
5261        }
5262        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5263        return null;
5264    }
5265
5266    /*
5267     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5268     */
5269    @Override
5270    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5271            int targetUserId) {
5272        mContext.enforceCallingOrSelfPermission(
5273                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5274        List<CrossProfileIntentFilter> matches =
5275                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5276        if (matches != null) {
5277            int size = matches.size();
5278            for (int i = 0; i < size; i++) {
5279                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5280            }
5281        }
5282        if (hasWebURI(intent)) {
5283            // cross-profile app linking works only towards the parent.
5284            final UserInfo parent = getProfileParent(sourceUserId);
5285            synchronized(mPackages) {
5286                int flags = updateFlagsForResolve(0, parent.id, intent);
5287                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5288                        intent, resolvedType, flags, sourceUserId, parent.id);
5289                return xpDomainInfo != null;
5290            }
5291        }
5292        return false;
5293    }
5294
5295    private UserInfo getProfileParent(int userId) {
5296        final long identity = Binder.clearCallingIdentity();
5297        try {
5298            return sUserManager.getProfileParent(userId);
5299        } finally {
5300            Binder.restoreCallingIdentity(identity);
5301        }
5302    }
5303
5304    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5305            String resolvedType, int userId) {
5306        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5307        if (resolver != null) {
5308            return resolver.queryIntent(intent, resolvedType, false, userId);
5309        }
5310        return null;
5311    }
5312
5313    @Override
5314    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5315            String resolvedType, int flags, int userId) {
5316        try {
5317            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5318
5319            return new ParceledListSlice<>(
5320                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5321        } finally {
5322            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5323        }
5324    }
5325
5326    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5327            String resolvedType, int flags, int userId) {
5328        if (!sUserManager.exists(userId)) return Collections.emptyList();
5329        flags = updateFlagsForResolve(flags, userId, intent);
5330        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5331                false /* requireFullPermission */, false /* checkShell */,
5332                "query intent activities");
5333        ComponentName comp = intent.getComponent();
5334        if (comp == null) {
5335            if (intent.getSelector() != null) {
5336                intent = intent.getSelector();
5337                comp = intent.getComponent();
5338            }
5339        }
5340
5341        if (comp != null) {
5342            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5343            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5344            if (ai != null) {
5345                final ResolveInfo ri = new ResolveInfo();
5346                ri.activityInfo = ai;
5347                list.add(ri);
5348            }
5349            return list;
5350        }
5351
5352        // reader
5353        boolean sortResult = false;
5354        boolean addEphemeral = false;
5355        boolean matchEphemeralPackage = false;
5356        List<ResolveInfo> result;
5357        final String pkgName = intent.getPackage();
5358        synchronized (mPackages) {
5359            if (pkgName == null) {
5360                List<CrossProfileIntentFilter> matchingFilters =
5361                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5362                // Check for results that need to skip the current profile.
5363                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5364                        resolvedType, flags, userId);
5365                if (xpResolveInfo != null) {
5366                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5367                    xpResult.add(xpResolveInfo);
5368                    return filterIfNotSystemUser(xpResult, userId);
5369                }
5370
5371                // Check for results in the current profile.
5372                result = filterIfNotSystemUser(mActivities.queryIntent(
5373                        intent, resolvedType, flags, userId), userId);
5374                addEphemeral =
5375                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5376
5377                // Check for cross profile results.
5378                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5379                xpResolveInfo = queryCrossProfileIntents(
5380                        matchingFilters, intent, resolvedType, flags, userId,
5381                        hasNonNegativePriorityResult);
5382                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5383                    boolean isVisibleToUser = filterIfNotSystemUser(
5384                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5385                    if (isVisibleToUser) {
5386                        result.add(xpResolveInfo);
5387                        sortResult = true;
5388                    }
5389                }
5390                if (hasWebURI(intent)) {
5391                    CrossProfileDomainInfo xpDomainInfo = null;
5392                    final UserInfo parent = getProfileParent(userId);
5393                    if (parent != null) {
5394                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5395                                flags, userId, parent.id);
5396                    }
5397                    if (xpDomainInfo != null) {
5398                        if (xpResolveInfo != null) {
5399                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5400                            // in the result.
5401                            result.remove(xpResolveInfo);
5402                        }
5403                        if (result.size() == 0 && !addEphemeral) {
5404                            // No result in current profile, but found candidate in parent user.
5405                            // And we are not going to add emphemeral app, so we can return the
5406                            // result straight away.
5407                            result.add(xpDomainInfo.resolveInfo);
5408                            return result;
5409                        }
5410                    } else if (result.size() <= 1 && !addEphemeral) {
5411                        // No result in parent user and <= 1 result in current profile, and we
5412                        // are not going to add emphemeral app, so we can return the result without
5413                        // further processing.
5414                        return result;
5415                    }
5416                    // We have more than one candidate (combining results from current and parent
5417                    // profile), so we need filtering and sorting.
5418                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5419                            intent, flags, result, xpDomainInfo, userId);
5420                    sortResult = true;
5421                }
5422            } else {
5423                final PackageParser.Package pkg = mPackages.get(pkgName);
5424                if (pkg != null) {
5425                    result = filterIfNotSystemUser(
5426                            mActivities.queryIntentForPackage(
5427                                    intent, resolvedType, flags, pkg.activities, userId),
5428                            userId);
5429                } else {
5430                    // the caller wants to resolve for a particular package; however, there
5431                    // were no installed results, so, try to find an ephemeral result
5432                    addEphemeral = isEphemeralAllowed(
5433                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5434                    matchEphemeralPackage = true;
5435                    result = new ArrayList<ResolveInfo>();
5436                }
5437            }
5438        }
5439        if (addEphemeral) {
5440            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5441            final EphemeralRequest requestObject = new EphemeralRequest(
5442                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5443                    null /*launchIntent*/, null /*callingPackage*/, userId);
5444            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5445                    mContext, mEphemeralResolverConnection, requestObject);
5446            if (intentInfo != null) {
5447                if (DEBUG_EPHEMERAL) {
5448                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5449                }
5450                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5451                ephemeralInstaller.ephemeralResponse = intentInfo;
5452                // make sure this resolver is the default
5453                ephemeralInstaller.isDefault = true;
5454                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5455                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5456                // add a non-generic filter
5457                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5458                ephemeralInstaller.filter.addDataPath(
5459                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5460                result.add(ephemeralInstaller);
5461            }
5462            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5463        }
5464        if (sortResult) {
5465            Collections.sort(result, mResolvePrioritySorter);
5466        }
5467        return result;
5468    }
5469
5470    private static class CrossProfileDomainInfo {
5471        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5472        ResolveInfo resolveInfo;
5473        /* Best domain verification status of the activities found in the other profile */
5474        int bestDomainVerificationStatus;
5475    }
5476
5477    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5478            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5479        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5480                sourceUserId)) {
5481            return null;
5482        }
5483        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5484                resolvedType, flags, parentUserId);
5485
5486        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5487            return null;
5488        }
5489        CrossProfileDomainInfo result = null;
5490        int size = resultTargetUser.size();
5491        for (int i = 0; i < size; i++) {
5492            ResolveInfo riTargetUser = resultTargetUser.get(i);
5493            // Intent filter verification is only for filters that specify a host. So don't return
5494            // those that handle all web uris.
5495            if (riTargetUser.handleAllWebDataURI) {
5496                continue;
5497            }
5498            String packageName = riTargetUser.activityInfo.packageName;
5499            PackageSetting ps = mSettings.mPackages.get(packageName);
5500            if (ps == null) {
5501                continue;
5502            }
5503            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5504            int status = (int)(verificationState >> 32);
5505            if (result == null) {
5506                result = new CrossProfileDomainInfo();
5507                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5508                        sourceUserId, parentUserId);
5509                result.bestDomainVerificationStatus = status;
5510            } else {
5511                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5512                        result.bestDomainVerificationStatus);
5513            }
5514        }
5515        // Don't consider matches with status NEVER across profiles.
5516        if (result != null && result.bestDomainVerificationStatus
5517                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5518            return null;
5519        }
5520        return result;
5521    }
5522
5523    /**
5524     * Verification statuses are ordered from the worse to the best, except for
5525     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5526     */
5527    private int bestDomainVerificationStatus(int status1, int status2) {
5528        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5529            return status2;
5530        }
5531        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5532            return status1;
5533        }
5534        return (int) MathUtils.max(status1, status2);
5535    }
5536
5537    private boolean isUserEnabled(int userId) {
5538        long callingId = Binder.clearCallingIdentity();
5539        try {
5540            UserInfo userInfo = sUserManager.getUserInfo(userId);
5541            return userInfo != null && userInfo.isEnabled();
5542        } finally {
5543            Binder.restoreCallingIdentity(callingId);
5544        }
5545    }
5546
5547    /**
5548     * Filter out activities with systemUserOnly flag set, when current user is not System.
5549     *
5550     * @return filtered list
5551     */
5552    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5553        if (userId == UserHandle.USER_SYSTEM) {
5554            return resolveInfos;
5555        }
5556        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5557            ResolveInfo info = resolveInfos.get(i);
5558            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5559                resolveInfos.remove(i);
5560            }
5561        }
5562        return resolveInfos;
5563    }
5564
5565    /**
5566     * @param resolveInfos list of resolve infos in descending priority order
5567     * @return if the list contains a resolve info with non-negative priority
5568     */
5569    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5570        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5571    }
5572
5573    private static boolean hasWebURI(Intent intent) {
5574        if (intent.getData() == null) {
5575            return false;
5576        }
5577        final String scheme = intent.getScheme();
5578        if (TextUtils.isEmpty(scheme)) {
5579            return false;
5580        }
5581        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5582    }
5583
5584    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5585            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5586            int userId) {
5587        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5588
5589        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5590            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5591                    candidates.size());
5592        }
5593
5594        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5595        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5596        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5597        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5598        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5599        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5600
5601        synchronized (mPackages) {
5602            final int count = candidates.size();
5603            // First, try to use linked apps. Partition the candidates into four lists:
5604            // one for the final results, one for the "do not use ever", one for "undefined status"
5605            // and finally one for "browser app type".
5606            for (int n=0; n<count; n++) {
5607                ResolveInfo info = candidates.get(n);
5608                String packageName = info.activityInfo.packageName;
5609                PackageSetting ps = mSettings.mPackages.get(packageName);
5610                if (ps != null) {
5611                    // Add to the special match all list (Browser use case)
5612                    if (info.handleAllWebDataURI) {
5613                        matchAllList.add(info);
5614                        continue;
5615                    }
5616                    // Try to get the status from User settings first
5617                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5618                    int status = (int)(packedStatus >> 32);
5619                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5620                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5621                        if (DEBUG_DOMAIN_VERIFICATION) {
5622                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5623                                    + " : linkgen=" + linkGeneration);
5624                        }
5625                        // Use link-enabled generation as preferredOrder, i.e.
5626                        // prefer newly-enabled over earlier-enabled.
5627                        info.preferredOrder = linkGeneration;
5628                        alwaysList.add(info);
5629                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5630                        if (DEBUG_DOMAIN_VERIFICATION) {
5631                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5632                        }
5633                        neverList.add(info);
5634                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5635                        if (DEBUG_DOMAIN_VERIFICATION) {
5636                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5637                        }
5638                        alwaysAskList.add(info);
5639                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5640                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5641                        if (DEBUG_DOMAIN_VERIFICATION) {
5642                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5643                        }
5644                        undefinedList.add(info);
5645                    }
5646                }
5647            }
5648
5649            // We'll want to include browser possibilities in a few cases
5650            boolean includeBrowser = false;
5651
5652            // First try to add the "always" resolution(s) for the current user, if any
5653            if (alwaysList.size() > 0) {
5654                result.addAll(alwaysList);
5655            } else {
5656                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5657                result.addAll(undefinedList);
5658                // Maybe add one for the other profile.
5659                if (xpDomainInfo != null && (
5660                        xpDomainInfo.bestDomainVerificationStatus
5661                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5662                    result.add(xpDomainInfo.resolveInfo);
5663                }
5664                includeBrowser = true;
5665            }
5666
5667            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5668            // If there were 'always' entries their preferred order has been set, so we also
5669            // back that off to make the alternatives equivalent
5670            if (alwaysAskList.size() > 0) {
5671                for (ResolveInfo i : result) {
5672                    i.preferredOrder = 0;
5673                }
5674                result.addAll(alwaysAskList);
5675                includeBrowser = true;
5676            }
5677
5678            if (includeBrowser) {
5679                // Also add browsers (all of them or only the default one)
5680                if (DEBUG_DOMAIN_VERIFICATION) {
5681                    Slog.v(TAG, "   ...including browsers in candidate set");
5682                }
5683                if ((matchFlags & MATCH_ALL) != 0) {
5684                    result.addAll(matchAllList);
5685                } else {
5686                    // Browser/generic handling case.  If there's a default browser, go straight
5687                    // to that (but only if there is no other higher-priority match).
5688                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5689                    int maxMatchPrio = 0;
5690                    ResolveInfo defaultBrowserMatch = null;
5691                    final int numCandidates = matchAllList.size();
5692                    for (int n = 0; n < numCandidates; n++) {
5693                        ResolveInfo info = matchAllList.get(n);
5694                        // track the highest overall match priority...
5695                        if (info.priority > maxMatchPrio) {
5696                            maxMatchPrio = info.priority;
5697                        }
5698                        // ...and the highest-priority default browser match
5699                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5700                            if (defaultBrowserMatch == null
5701                                    || (defaultBrowserMatch.priority < info.priority)) {
5702                                if (debug) {
5703                                    Slog.v(TAG, "Considering default browser match " + info);
5704                                }
5705                                defaultBrowserMatch = info;
5706                            }
5707                        }
5708                    }
5709                    if (defaultBrowserMatch != null
5710                            && defaultBrowserMatch.priority >= maxMatchPrio
5711                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5712                    {
5713                        if (debug) {
5714                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5715                        }
5716                        result.add(defaultBrowserMatch);
5717                    } else {
5718                        result.addAll(matchAllList);
5719                    }
5720                }
5721
5722                // If there is nothing selected, add all candidates and remove the ones that the user
5723                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5724                if (result.size() == 0) {
5725                    result.addAll(candidates);
5726                    result.removeAll(neverList);
5727                }
5728            }
5729        }
5730        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5731            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5732                    result.size());
5733            for (ResolveInfo info : result) {
5734                Slog.v(TAG, "  + " + info.activityInfo);
5735            }
5736        }
5737        return result;
5738    }
5739
5740    // Returns a packed value as a long:
5741    //
5742    // high 'int'-sized word: link status: undefined/ask/never/always.
5743    // low 'int'-sized word: relative priority among 'always' results.
5744    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5745        long result = ps.getDomainVerificationStatusForUser(userId);
5746        // if none available, get the master status
5747        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5748            if (ps.getIntentFilterVerificationInfo() != null) {
5749                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5750            }
5751        }
5752        return result;
5753    }
5754
5755    private ResolveInfo querySkipCurrentProfileIntents(
5756            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5757            int flags, int sourceUserId) {
5758        if (matchingFilters != null) {
5759            int size = matchingFilters.size();
5760            for (int i = 0; i < size; i ++) {
5761                CrossProfileIntentFilter filter = matchingFilters.get(i);
5762                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5763                    // Checking if there are activities in the target user that can handle the
5764                    // intent.
5765                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5766                            resolvedType, flags, sourceUserId);
5767                    if (resolveInfo != null) {
5768                        return resolveInfo;
5769                    }
5770                }
5771            }
5772        }
5773        return null;
5774    }
5775
5776    // Return matching ResolveInfo in target user if any.
5777    private ResolveInfo queryCrossProfileIntents(
5778            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5779            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5780        if (matchingFilters != null) {
5781            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5782            // match the same intent. For performance reasons, it is better not to
5783            // run queryIntent twice for the same userId
5784            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5785            int size = matchingFilters.size();
5786            for (int i = 0; i < size; i++) {
5787                CrossProfileIntentFilter filter = matchingFilters.get(i);
5788                int targetUserId = filter.getTargetUserId();
5789                boolean skipCurrentProfile =
5790                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5791                boolean skipCurrentProfileIfNoMatchFound =
5792                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5793                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5794                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5795                    // Checking if there are activities in the target user that can handle the
5796                    // intent.
5797                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5798                            resolvedType, flags, sourceUserId);
5799                    if (resolveInfo != null) return resolveInfo;
5800                    alreadyTriedUserIds.put(targetUserId, true);
5801                }
5802            }
5803        }
5804        return null;
5805    }
5806
5807    /**
5808     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5809     * will forward the intent to the filter's target user.
5810     * Otherwise, returns null.
5811     */
5812    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5813            String resolvedType, int flags, int sourceUserId) {
5814        int targetUserId = filter.getTargetUserId();
5815        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5816                resolvedType, flags, targetUserId);
5817        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5818            // If all the matches in the target profile are suspended, return null.
5819            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5820                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5821                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5822                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5823                            targetUserId);
5824                }
5825            }
5826        }
5827        return null;
5828    }
5829
5830    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5831            int sourceUserId, int targetUserId) {
5832        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5833        long ident = Binder.clearCallingIdentity();
5834        boolean targetIsProfile;
5835        try {
5836            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5837        } finally {
5838            Binder.restoreCallingIdentity(ident);
5839        }
5840        String className;
5841        if (targetIsProfile) {
5842            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5843        } else {
5844            className = FORWARD_INTENT_TO_PARENT;
5845        }
5846        ComponentName forwardingActivityComponentName = new ComponentName(
5847                mAndroidApplication.packageName, className);
5848        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5849                sourceUserId);
5850        if (!targetIsProfile) {
5851            forwardingActivityInfo.showUserIcon = targetUserId;
5852            forwardingResolveInfo.noResourceId = true;
5853        }
5854        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5855        forwardingResolveInfo.priority = 0;
5856        forwardingResolveInfo.preferredOrder = 0;
5857        forwardingResolveInfo.match = 0;
5858        forwardingResolveInfo.isDefault = true;
5859        forwardingResolveInfo.filter = filter;
5860        forwardingResolveInfo.targetUserId = targetUserId;
5861        return forwardingResolveInfo;
5862    }
5863
5864    @Override
5865    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5866            Intent[] specifics, String[] specificTypes, Intent intent,
5867            String resolvedType, int flags, int userId) {
5868        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5869                specificTypes, intent, resolvedType, flags, userId));
5870    }
5871
5872    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5873            Intent[] specifics, String[] specificTypes, Intent intent,
5874            String resolvedType, int flags, int userId) {
5875        if (!sUserManager.exists(userId)) return Collections.emptyList();
5876        flags = updateFlagsForResolve(flags, userId, intent);
5877        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5878                false /* requireFullPermission */, false /* checkShell */,
5879                "query intent activity options");
5880        final String resultsAction = intent.getAction();
5881
5882        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5883                | PackageManager.GET_RESOLVED_FILTER, userId);
5884
5885        if (DEBUG_INTENT_MATCHING) {
5886            Log.v(TAG, "Query " + intent + ": " + results);
5887        }
5888
5889        int specificsPos = 0;
5890        int N;
5891
5892        // todo: note that the algorithm used here is O(N^2).  This
5893        // isn't a problem in our current environment, but if we start running
5894        // into situations where we have more than 5 or 10 matches then this
5895        // should probably be changed to something smarter...
5896
5897        // First we go through and resolve each of the specific items
5898        // that were supplied, taking care of removing any corresponding
5899        // duplicate items in the generic resolve list.
5900        if (specifics != null) {
5901            for (int i=0; i<specifics.length; i++) {
5902                final Intent sintent = specifics[i];
5903                if (sintent == null) {
5904                    continue;
5905                }
5906
5907                if (DEBUG_INTENT_MATCHING) {
5908                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5909                }
5910
5911                String action = sintent.getAction();
5912                if (resultsAction != null && resultsAction.equals(action)) {
5913                    // If this action was explicitly requested, then don't
5914                    // remove things that have it.
5915                    action = null;
5916                }
5917
5918                ResolveInfo ri = null;
5919                ActivityInfo ai = null;
5920
5921                ComponentName comp = sintent.getComponent();
5922                if (comp == null) {
5923                    ri = resolveIntent(
5924                        sintent,
5925                        specificTypes != null ? specificTypes[i] : null,
5926                            flags, userId);
5927                    if (ri == null) {
5928                        continue;
5929                    }
5930                    if (ri == mResolveInfo) {
5931                        // ACK!  Must do something better with this.
5932                    }
5933                    ai = ri.activityInfo;
5934                    comp = new ComponentName(ai.applicationInfo.packageName,
5935                            ai.name);
5936                } else {
5937                    ai = getActivityInfo(comp, flags, userId);
5938                    if (ai == null) {
5939                        continue;
5940                    }
5941                }
5942
5943                // Look for any generic query activities that are duplicates
5944                // of this specific one, and remove them from the results.
5945                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5946                N = results.size();
5947                int j;
5948                for (j=specificsPos; j<N; j++) {
5949                    ResolveInfo sri = results.get(j);
5950                    if ((sri.activityInfo.name.equals(comp.getClassName())
5951                            && sri.activityInfo.applicationInfo.packageName.equals(
5952                                    comp.getPackageName()))
5953                        || (action != null && sri.filter.matchAction(action))) {
5954                        results.remove(j);
5955                        if (DEBUG_INTENT_MATCHING) Log.v(
5956                            TAG, "Removing duplicate item from " + j
5957                            + " due to specific " + specificsPos);
5958                        if (ri == null) {
5959                            ri = sri;
5960                        }
5961                        j--;
5962                        N--;
5963                    }
5964                }
5965
5966                // Add this specific item to its proper place.
5967                if (ri == null) {
5968                    ri = new ResolveInfo();
5969                    ri.activityInfo = ai;
5970                }
5971                results.add(specificsPos, ri);
5972                ri.specificIndex = i;
5973                specificsPos++;
5974            }
5975        }
5976
5977        // Now we go through the remaining generic results and remove any
5978        // duplicate actions that are found here.
5979        N = results.size();
5980        for (int i=specificsPos; i<N-1; i++) {
5981            final ResolveInfo rii = results.get(i);
5982            if (rii.filter == null) {
5983                continue;
5984            }
5985
5986            // Iterate over all of the actions of this result's intent
5987            // filter...  typically this should be just one.
5988            final Iterator<String> it = rii.filter.actionsIterator();
5989            if (it == null) {
5990                continue;
5991            }
5992            while (it.hasNext()) {
5993                final String action = it.next();
5994                if (resultsAction != null && resultsAction.equals(action)) {
5995                    // If this action was explicitly requested, then don't
5996                    // remove things that have it.
5997                    continue;
5998                }
5999                for (int j=i+1; j<N; j++) {
6000                    final ResolveInfo rij = results.get(j);
6001                    if (rij.filter != null && rij.filter.hasAction(action)) {
6002                        results.remove(j);
6003                        if (DEBUG_INTENT_MATCHING) Log.v(
6004                            TAG, "Removing duplicate item from " + j
6005                            + " due to action " + action + " at " + i);
6006                        j--;
6007                        N--;
6008                    }
6009                }
6010            }
6011
6012            // If the caller didn't request filter information, drop it now
6013            // so we don't have to marshall/unmarshall it.
6014            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6015                rii.filter = null;
6016            }
6017        }
6018
6019        // Filter out the caller activity if so requested.
6020        if (caller != null) {
6021            N = results.size();
6022            for (int i=0; i<N; i++) {
6023                ActivityInfo ainfo = results.get(i).activityInfo;
6024                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6025                        && caller.getClassName().equals(ainfo.name)) {
6026                    results.remove(i);
6027                    break;
6028                }
6029            }
6030        }
6031
6032        // If the caller didn't request filter information,
6033        // drop them now so we don't have to
6034        // marshall/unmarshall it.
6035        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6036            N = results.size();
6037            for (int i=0; i<N; i++) {
6038                results.get(i).filter = null;
6039            }
6040        }
6041
6042        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6043        return results;
6044    }
6045
6046    @Override
6047    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6048            String resolvedType, int flags, int userId) {
6049        return new ParceledListSlice<>(
6050                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6051    }
6052
6053    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6054            String resolvedType, int flags, int userId) {
6055        if (!sUserManager.exists(userId)) return Collections.emptyList();
6056        flags = updateFlagsForResolve(flags, userId, intent);
6057        ComponentName comp = intent.getComponent();
6058        if (comp == null) {
6059            if (intent.getSelector() != null) {
6060                intent = intent.getSelector();
6061                comp = intent.getComponent();
6062            }
6063        }
6064        if (comp != null) {
6065            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6066            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6067            if (ai != null) {
6068                ResolveInfo ri = new ResolveInfo();
6069                ri.activityInfo = ai;
6070                list.add(ri);
6071            }
6072            return list;
6073        }
6074
6075        // reader
6076        synchronized (mPackages) {
6077            String pkgName = intent.getPackage();
6078            if (pkgName == null) {
6079                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6080            }
6081            final PackageParser.Package pkg = mPackages.get(pkgName);
6082            if (pkg != null) {
6083                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6084                        userId);
6085            }
6086            return Collections.emptyList();
6087        }
6088    }
6089
6090    @Override
6091    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6092        if (!sUserManager.exists(userId)) return null;
6093        flags = updateFlagsForResolve(flags, userId, intent);
6094        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6095        if (query != null) {
6096            if (query.size() >= 1) {
6097                // If there is more than one service with the same priority,
6098                // just arbitrarily pick the first one.
6099                return query.get(0);
6100            }
6101        }
6102        return null;
6103    }
6104
6105    @Override
6106    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6107            String resolvedType, int flags, int userId) {
6108        return new ParceledListSlice<>(
6109                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6110    }
6111
6112    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6113            String resolvedType, int flags, int userId) {
6114        if (!sUserManager.exists(userId)) return Collections.emptyList();
6115        flags = updateFlagsForResolve(flags, userId, intent);
6116        ComponentName comp = intent.getComponent();
6117        if (comp == null) {
6118            if (intent.getSelector() != null) {
6119                intent = intent.getSelector();
6120                comp = intent.getComponent();
6121            }
6122        }
6123        if (comp != null) {
6124            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6125            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6126            if (si != null) {
6127                final ResolveInfo ri = new ResolveInfo();
6128                ri.serviceInfo = si;
6129                list.add(ri);
6130            }
6131            return list;
6132        }
6133
6134        // reader
6135        synchronized (mPackages) {
6136            String pkgName = intent.getPackage();
6137            if (pkgName == null) {
6138                return mServices.queryIntent(intent, resolvedType, flags, userId);
6139            }
6140            final PackageParser.Package pkg = mPackages.get(pkgName);
6141            if (pkg != null) {
6142                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6143                        userId);
6144            }
6145            return Collections.emptyList();
6146        }
6147    }
6148
6149    @Override
6150    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6151            String resolvedType, int flags, int userId) {
6152        return new ParceledListSlice<>(
6153                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6154    }
6155
6156    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6157            Intent intent, String resolvedType, int flags, int userId) {
6158        if (!sUserManager.exists(userId)) return Collections.emptyList();
6159        flags = updateFlagsForResolve(flags, userId, intent);
6160        ComponentName comp = intent.getComponent();
6161        if (comp == null) {
6162            if (intent.getSelector() != null) {
6163                intent = intent.getSelector();
6164                comp = intent.getComponent();
6165            }
6166        }
6167        if (comp != null) {
6168            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6169            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6170            if (pi != null) {
6171                final ResolveInfo ri = new ResolveInfo();
6172                ri.providerInfo = pi;
6173                list.add(ri);
6174            }
6175            return list;
6176        }
6177
6178        // reader
6179        synchronized (mPackages) {
6180            String pkgName = intent.getPackage();
6181            if (pkgName == null) {
6182                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6183            }
6184            final PackageParser.Package pkg = mPackages.get(pkgName);
6185            if (pkg != null) {
6186                return mProviders.queryIntentForPackage(
6187                        intent, resolvedType, flags, pkg.providers, userId);
6188            }
6189            return Collections.emptyList();
6190        }
6191    }
6192
6193    @Override
6194    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6195        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6196        flags = updateFlagsForPackage(flags, userId, null);
6197        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6198        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6199                true /* requireFullPermission */, false /* checkShell */,
6200                "get installed packages");
6201
6202        // writer
6203        synchronized (mPackages) {
6204            ArrayList<PackageInfo> list;
6205            if (listUninstalled) {
6206                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6207                for (PackageSetting ps : mSettings.mPackages.values()) {
6208                    final PackageInfo pi;
6209                    if (ps.pkg != null) {
6210                        pi = generatePackageInfo(ps, flags, userId);
6211                    } else {
6212                        pi = generatePackageInfo(ps, flags, userId);
6213                    }
6214                    if (pi != null) {
6215                        list.add(pi);
6216                    }
6217                }
6218            } else {
6219                list = new ArrayList<PackageInfo>(mPackages.size());
6220                for (PackageParser.Package p : mPackages.values()) {
6221                    final PackageInfo pi =
6222                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6223                    if (pi != null) {
6224                        list.add(pi);
6225                    }
6226                }
6227            }
6228
6229            return new ParceledListSlice<PackageInfo>(list);
6230        }
6231    }
6232
6233    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6234            String[] permissions, boolean[] tmp, int flags, int userId) {
6235        int numMatch = 0;
6236        final PermissionsState permissionsState = ps.getPermissionsState();
6237        for (int i=0; i<permissions.length; i++) {
6238            final String permission = permissions[i];
6239            if (permissionsState.hasPermission(permission, userId)) {
6240                tmp[i] = true;
6241                numMatch++;
6242            } else {
6243                tmp[i] = false;
6244            }
6245        }
6246        if (numMatch == 0) {
6247            return;
6248        }
6249        final PackageInfo pi;
6250        if (ps.pkg != null) {
6251            pi = generatePackageInfo(ps, flags, userId);
6252        } else {
6253            pi = generatePackageInfo(ps, flags, userId);
6254        }
6255        // The above might return null in cases of uninstalled apps or install-state
6256        // skew across users/profiles.
6257        if (pi != null) {
6258            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6259                if (numMatch == permissions.length) {
6260                    pi.requestedPermissions = permissions;
6261                } else {
6262                    pi.requestedPermissions = new String[numMatch];
6263                    numMatch = 0;
6264                    for (int i=0; i<permissions.length; i++) {
6265                        if (tmp[i]) {
6266                            pi.requestedPermissions[numMatch] = permissions[i];
6267                            numMatch++;
6268                        }
6269                    }
6270                }
6271            }
6272            list.add(pi);
6273        }
6274    }
6275
6276    @Override
6277    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6278            String[] permissions, int flags, int userId) {
6279        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6280        flags = updateFlagsForPackage(flags, userId, permissions);
6281        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6282
6283        // writer
6284        synchronized (mPackages) {
6285            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6286            boolean[] tmpBools = new boolean[permissions.length];
6287            if (listUninstalled) {
6288                for (PackageSetting ps : mSettings.mPackages.values()) {
6289                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6290                }
6291            } else {
6292                for (PackageParser.Package pkg : mPackages.values()) {
6293                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6294                    if (ps != null) {
6295                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6296                                userId);
6297                    }
6298                }
6299            }
6300
6301            return new ParceledListSlice<PackageInfo>(list);
6302        }
6303    }
6304
6305    @Override
6306    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6307        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6308        flags = updateFlagsForApplication(flags, userId, null);
6309        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6310
6311        // writer
6312        synchronized (mPackages) {
6313            ArrayList<ApplicationInfo> list;
6314            if (listUninstalled) {
6315                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6316                for (PackageSetting ps : mSettings.mPackages.values()) {
6317                    ApplicationInfo ai;
6318                    if (ps.pkg != null) {
6319                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6320                                ps.readUserState(userId), userId);
6321                    } else {
6322                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6323                    }
6324                    if (ai != null) {
6325                        list.add(ai);
6326                    }
6327                }
6328            } else {
6329                list = new ArrayList<ApplicationInfo>(mPackages.size());
6330                for (PackageParser.Package p : mPackages.values()) {
6331                    if (p.mExtras != null) {
6332                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6333                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6334                        if (ai != null) {
6335                            list.add(ai);
6336                        }
6337                    }
6338                }
6339            }
6340
6341            return new ParceledListSlice<ApplicationInfo>(list);
6342        }
6343    }
6344
6345    @Override
6346    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6347        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6348            return null;
6349        }
6350
6351        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6352                "getEphemeralApplications");
6353        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6354                true /* requireFullPermission */, false /* checkShell */,
6355                "getEphemeralApplications");
6356        synchronized (mPackages) {
6357            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6358                    .getEphemeralApplicationsLPw(userId);
6359            if (ephemeralApps != null) {
6360                return new ParceledListSlice<>(ephemeralApps);
6361            }
6362        }
6363        return null;
6364    }
6365
6366    @Override
6367    public boolean isEphemeralApplication(String packageName, int userId) {
6368        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6369                true /* requireFullPermission */, false /* checkShell */,
6370                "isEphemeral");
6371        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6372            return false;
6373        }
6374
6375        if (!isCallerSameApp(packageName)) {
6376            return false;
6377        }
6378        synchronized (mPackages) {
6379            PackageParser.Package pkg = mPackages.get(packageName);
6380            if (pkg != null) {
6381                return pkg.applicationInfo.isEphemeralApp();
6382            }
6383        }
6384        return false;
6385    }
6386
6387    @Override
6388    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6389        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6390            return null;
6391        }
6392
6393        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6394                true /* requireFullPermission */, false /* checkShell */,
6395                "getCookie");
6396        if (!isCallerSameApp(packageName)) {
6397            return null;
6398        }
6399        synchronized (mPackages) {
6400            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6401                    packageName, userId);
6402        }
6403    }
6404
6405    @Override
6406    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6407        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6408            return true;
6409        }
6410
6411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6412                true /* requireFullPermission */, true /* checkShell */,
6413                "setCookie");
6414        if (!isCallerSameApp(packageName)) {
6415            return false;
6416        }
6417        synchronized (mPackages) {
6418            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6419                    packageName, cookie, userId);
6420        }
6421    }
6422
6423    @Override
6424    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6425        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6426            return null;
6427        }
6428
6429        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6430                "getEphemeralApplicationIcon");
6431        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6432                true /* requireFullPermission */, false /* checkShell */,
6433                "getEphemeralApplicationIcon");
6434        synchronized (mPackages) {
6435            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6436                    packageName, userId);
6437        }
6438    }
6439
6440    private boolean isCallerSameApp(String packageName) {
6441        PackageParser.Package pkg = mPackages.get(packageName);
6442        return pkg != null
6443                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6444    }
6445
6446    @Override
6447    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6448        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6449    }
6450
6451    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6452        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6453
6454        // reader
6455        synchronized (mPackages) {
6456            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6457            final int userId = UserHandle.getCallingUserId();
6458            while (i.hasNext()) {
6459                final PackageParser.Package p = i.next();
6460                if (p.applicationInfo == null) continue;
6461
6462                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6463                        && !p.applicationInfo.isDirectBootAware();
6464                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6465                        && p.applicationInfo.isDirectBootAware();
6466
6467                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6468                        && (!mSafeMode || isSystemApp(p))
6469                        && (matchesUnaware || matchesAware)) {
6470                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6471                    if (ps != null) {
6472                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6473                                ps.readUserState(userId), userId);
6474                        if (ai != null) {
6475                            finalList.add(ai);
6476                        }
6477                    }
6478                }
6479            }
6480        }
6481
6482        return finalList;
6483    }
6484
6485    @Override
6486    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6487        if (!sUserManager.exists(userId)) return null;
6488        flags = updateFlagsForComponent(flags, userId, name);
6489        // reader
6490        synchronized (mPackages) {
6491            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6492            PackageSetting ps = provider != null
6493                    ? mSettings.mPackages.get(provider.owner.packageName)
6494                    : null;
6495            return ps != null
6496                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6497                    ? PackageParser.generateProviderInfo(provider, flags,
6498                            ps.readUserState(userId), userId)
6499                    : null;
6500        }
6501    }
6502
6503    /**
6504     * @deprecated
6505     */
6506    @Deprecated
6507    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6508        // reader
6509        synchronized (mPackages) {
6510            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6511                    .entrySet().iterator();
6512            final int userId = UserHandle.getCallingUserId();
6513            while (i.hasNext()) {
6514                Map.Entry<String, PackageParser.Provider> entry = i.next();
6515                PackageParser.Provider p = entry.getValue();
6516                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6517
6518                if (ps != null && p.syncable
6519                        && (!mSafeMode || (p.info.applicationInfo.flags
6520                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6521                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6522                            ps.readUserState(userId), userId);
6523                    if (info != null) {
6524                        outNames.add(entry.getKey());
6525                        outInfo.add(info);
6526                    }
6527                }
6528            }
6529        }
6530    }
6531
6532    @Override
6533    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6534            int uid, int flags) {
6535        final int userId = processName != null ? UserHandle.getUserId(uid)
6536                : UserHandle.getCallingUserId();
6537        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6538        flags = updateFlagsForComponent(flags, userId, processName);
6539
6540        ArrayList<ProviderInfo> finalList = null;
6541        // reader
6542        synchronized (mPackages) {
6543            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6544            while (i.hasNext()) {
6545                final PackageParser.Provider p = i.next();
6546                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6547                if (ps != null && p.info.authority != null
6548                        && (processName == null
6549                                || (p.info.processName.equals(processName)
6550                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6551                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6552                    if (finalList == null) {
6553                        finalList = new ArrayList<ProviderInfo>(3);
6554                    }
6555                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6556                            ps.readUserState(userId), userId);
6557                    if (info != null) {
6558                        finalList.add(info);
6559                    }
6560                }
6561            }
6562        }
6563
6564        if (finalList != null) {
6565            Collections.sort(finalList, mProviderInitOrderSorter);
6566            return new ParceledListSlice<ProviderInfo>(finalList);
6567        }
6568
6569        return ParceledListSlice.emptyList();
6570    }
6571
6572    @Override
6573    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6574        // reader
6575        synchronized (mPackages) {
6576            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6577            return PackageParser.generateInstrumentationInfo(i, flags);
6578        }
6579    }
6580
6581    @Override
6582    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6583            String targetPackage, int flags) {
6584        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6585    }
6586
6587    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6588            int flags) {
6589        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6590
6591        // reader
6592        synchronized (mPackages) {
6593            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6594            while (i.hasNext()) {
6595                final PackageParser.Instrumentation p = i.next();
6596                if (targetPackage == null
6597                        || targetPackage.equals(p.info.targetPackage)) {
6598                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6599                            flags);
6600                    if (ii != null) {
6601                        finalList.add(ii);
6602                    }
6603                }
6604            }
6605        }
6606
6607        return finalList;
6608    }
6609
6610    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6611        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6612        if (overlays == null) {
6613            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6614            return;
6615        }
6616        for (PackageParser.Package opkg : overlays.values()) {
6617            // Not much to do if idmap fails: we already logged the error
6618            // and we certainly don't want to abort installation of pkg simply
6619            // because an overlay didn't fit properly. For these reasons,
6620            // ignore the return value of createIdmapForPackagePairLI.
6621            createIdmapForPackagePairLI(pkg, opkg);
6622        }
6623    }
6624
6625    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6626            PackageParser.Package opkg) {
6627        if (!opkg.mTrustedOverlay) {
6628            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6629                    opkg.baseCodePath + ": overlay not trusted");
6630            return false;
6631        }
6632        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6633        if (overlaySet == null) {
6634            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6635                    opkg.baseCodePath + " but target package has no known overlays");
6636            return false;
6637        }
6638        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6639        // TODO: generate idmap for split APKs
6640        try {
6641            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6642        } catch (InstallerException e) {
6643            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6644                    + opkg.baseCodePath);
6645            return false;
6646        }
6647        PackageParser.Package[] overlayArray =
6648            overlaySet.values().toArray(new PackageParser.Package[0]);
6649        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6650            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6651                return p1.mOverlayPriority - p2.mOverlayPriority;
6652            }
6653        };
6654        Arrays.sort(overlayArray, cmp);
6655
6656        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6657        int i = 0;
6658        for (PackageParser.Package p : overlayArray) {
6659            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6660        }
6661        return true;
6662    }
6663
6664    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6665        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6666        try {
6667            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6668        } finally {
6669            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6670        }
6671    }
6672
6673    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6674        final File[] files = dir.listFiles();
6675        if (ArrayUtils.isEmpty(files)) {
6676            Log.d(TAG, "No files in app dir " + dir);
6677            return;
6678        }
6679
6680        if (DEBUG_PACKAGE_SCANNING) {
6681            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6682                    + " flags=0x" + Integer.toHexString(parseFlags));
6683        }
6684
6685        for (File file : files) {
6686            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6687                    && !PackageInstallerService.isStageName(file.getName());
6688            if (!isPackage) {
6689                // Ignore entries which are not packages
6690                continue;
6691            }
6692            try {
6693                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6694                        scanFlags, currentTime, null);
6695            } catch (PackageManagerException e) {
6696                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6697
6698                // Delete invalid userdata apps
6699                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6700                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6701                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6702                    removeCodePathLI(file);
6703                }
6704            }
6705        }
6706    }
6707
6708    private static File getSettingsProblemFile() {
6709        File dataDir = Environment.getDataDirectory();
6710        File systemDir = new File(dataDir, "system");
6711        File fname = new File(systemDir, "uiderrors.txt");
6712        return fname;
6713    }
6714
6715    static void reportSettingsProblem(int priority, String msg) {
6716        logCriticalInfo(priority, msg);
6717    }
6718
6719    static void logCriticalInfo(int priority, String msg) {
6720        Slog.println(priority, TAG, msg);
6721        EventLogTags.writePmCriticalInfo(msg);
6722        try {
6723            File fname = getSettingsProblemFile();
6724            FileOutputStream out = new FileOutputStream(fname, true);
6725            PrintWriter pw = new FastPrintWriter(out);
6726            SimpleDateFormat formatter = new SimpleDateFormat();
6727            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6728            pw.println(dateString + ": " + msg);
6729            pw.close();
6730            FileUtils.setPermissions(
6731                    fname.toString(),
6732                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6733                    -1, -1);
6734        } catch (java.io.IOException e) {
6735        }
6736    }
6737
6738    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6739        if (srcFile.isDirectory()) {
6740            final File baseFile = new File(pkg.baseCodePath);
6741            long maxModifiedTime = baseFile.lastModified();
6742            if (pkg.splitCodePaths != null) {
6743                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6744                    final File splitFile = new File(pkg.splitCodePaths[i]);
6745                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6746                }
6747            }
6748            return maxModifiedTime;
6749        }
6750        return srcFile.lastModified();
6751    }
6752
6753    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6754            final int policyFlags) throws PackageManagerException {
6755        // When upgrading from pre-N MR1, verify the package time stamp using the package
6756        // directory and not the APK file.
6757        final long lastModifiedTime = mIsPreNMR1Upgrade
6758                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6759        if (ps != null
6760                && ps.codePath.equals(srcFile)
6761                && ps.timeStamp == lastModifiedTime
6762                && !isCompatSignatureUpdateNeeded(pkg)
6763                && !isRecoverSignatureUpdateNeeded(pkg)) {
6764            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6765            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6766            ArraySet<PublicKey> signingKs;
6767            synchronized (mPackages) {
6768                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6769            }
6770            if (ps.signatures.mSignatures != null
6771                    && ps.signatures.mSignatures.length != 0
6772                    && signingKs != null) {
6773                // Optimization: reuse the existing cached certificates
6774                // if the package appears to be unchanged.
6775                pkg.mSignatures = ps.signatures.mSignatures;
6776                pkg.mSigningKeys = signingKs;
6777                return;
6778            }
6779
6780            Slog.w(TAG, "PackageSetting for " + ps.name
6781                    + " is missing signatures.  Collecting certs again to recover them.");
6782        } else {
6783            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6784        }
6785
6786        try {
6787            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6788            PackageParser.collectCertificates(pkg, policyFlags);
6789        } catch (PackageParserException e) {
6790            throw PackageManagerException.from(e);
6791        } finally {
6792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6793        }
6794    }
6795
6796    /**
6797     *  Traces a package scan.
6798     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6799     */
6800    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6801            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6803        try {
6804            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6805        } finally {
6806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6807        }
6808    }
6809
6810    /**
6811     *  Scans a package and returns the newly parsed package.
6812     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6813     */
6814    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6815            long currentTime, UserHandle user) throws PackageManagerException {
6816        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6817        PackageParser pp = new PackageParser();
6818        pp.setSeparateProcesses(mSeparateProcesses);
6819        pp.setOnlyCoreApps(mOnlyCore);
6820        pp.setDisplayMetrics(mMetrics);
6821
6822        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6823            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6824        }
6825
6826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6827        final PackageParser.Package pkg;
6828        try {
6829            pkg = pp.parsePackage(scanFile, parseFlags);
6830        } catch (PackageParserException e) {
6831            throw PackageManagerException.from(e);
6832        } finally {
6833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6834        }
6835
6836        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6837    }
6838
6839    /**
6840     *  Scans a package and returns the newly parsed package.
6841     *  @throws PackageManagerException on a parse error.
6842     */
6843    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6844            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6845            throws PackageManagerException {
6846        // If the package has children and this is the first dive in the function
6847        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6848        // packages (parent and children) would be successfully scanned before the
6849        // actual scan since scanning mutates internal state and we want to atomically
6850        // install the package and its children.
6851        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6852            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6853                scanFlags |= SCAN_CHECK_ONLY;
6854            }
6855        } else {
6856            scanFlags &= ~SCAN_CHECK_ONLY;
6857        }
6858
6859        // Scan the parent
6860        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6861                scanFlags, currentTime, user);
6862
6863        // Scan the children
6864        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6865        for (int i = 0; i < childCount; i++) {
6866            PackageParser.Package childPackage = pkg.childPackages.get(i);
6867            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6868                    currentTime, user);
6869        }
6870
6871
6872        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6873            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6874        }
6875
6876        return scannedPkg;
6877    }
6878
6879    /**
6880     *  Scans a package and returns the newly parsed package.
6881     *  @throws PackageManagerException on a parse error.
6882     */
6883    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6884            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6885            throws PackageManagerException {
6886        PackageSetting ps = null;
6887        PackageSetting updatedPkg;
6888        // reader
6889        synchronized (mPackages) {
6890            // Look to see if we already know about this package.
6891            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6892            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6893                // This package has been renamed to its original name.  Let's
6894                // use that.
6895                ps = mSettings.getPackageLPr(oldName);
6896            }
6897            // If there was no original package, see one for the real package name.
6898            if (ps == null) {
6899                ps = mSettings.getPackageLPr(pkg.packageName);
6900            }
6901            // Check to see if this package could be hiding/updating a system
6902            // package.  Must look for it either under the original or real
6903            // package name depending on our state.
6904            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6905            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6906
6907            // If this is a package we don't know about on the system partition, we
6908            // may need to remove disabled child packages on the system partition
6909            // or may need to not add child packages if the parent apk is updated
6910            // on the data partition and no longer defines this child package.
6911            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6912                // If this is a parent package for an updated system app and this system
6913                // app got an OTA update which no longer defines some of the child packages
6914                // we have to prune them from the disabled system packages.
6915                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6916                if (disabledPs != null) {
6917                    final int scannedChildCount = (pkg.childPackages != null)
6918                            ? pkg.childPackages.size() : 0;
6919                    final int disabledChildCount = disabledPs.childPackageNames != null
6920                            ? disabledPs.childPackageNames.size() : 0;
6921                    for (int i = 0; i < disabledChildCount; i++) {
6922                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6923                        boolean disabledPackageAvailable = false;
6924                        for (int j = 0; j < scannedChildCount; j++) {
6925                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6926                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6927                                disabledPackageAvailable = true;
6928                                break;
6929                            }
6930                         }
6931                         if (!disabledPackageAvailable) {
6932                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6933                         }
6934                    }
6935                }
6936            }
6937        }
6938
6939        boolean updatedPkgBetter = false;
6940        // First check if this is a system package that may involve an update
6941        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6942            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6943            // it needs to drop FLAG_PRIVILEGED.
6944            if (locationIsPrivileged(scanFile)) {
6945                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6946            } else {
6947                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6948            }
6949
6950            if (ps != null && !ps.codePath.equals(scanFile)) {
6951                // The path has changed from what was last scanned...  check the
6952                // version of the new path against what we have stored to determine
6953                // what to do.
6954                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6955                if (pkg.mVersionCode <= ps.versionCode) {
6956                    // The system package has been updated and the code path does not match
6957                    // Ignore entry. Skip it.
6958                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6959                            + " ignored: updated version " + ps.versionCode
6960                            + " better than this " + pkg.mVersionCode);
6961                    if (!updatedPkg.codePath.equals(scanFile)) {
6962                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6963                                + ps.name + " changing from " + updatedPkg.codePathString
6964                                + " to " + scanFile);
6965                        updatedPkg.codePath = scanFile;
6966                        updatedPkg.codePathString = scanFile.toString();
6967                        updatedPkg.resourcePath = scanFile;
6968                        updatedPkg.resourcePathString = scanFile.toString();
6969                    }
6970                    updatedPkg.pkg = pkg;
6971                    updatedPkg.versionCode = pkg.mVersionCode;
6972
6973                    // Update the disabled system child packages to point to the package too.
6974                    final int childCount = updatedPkg.childPackageNames != null
6975                            ? updatedPkg.childPackageNames.size() : 0;
6976                    for (int i = 0; i < childCount; i++) {
6977                        String childPackageName = updatedPkg.childPackageNames.get(i);
6978                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6979                                childPackageName);
6980                        if (updatedChildPkg != null) {
6981                            updatedChildPkg.pkg = pkg;
6982                            updatedChildPkg.versionCode = pkg.mVersionCode;
6983                        }
6984                    }
6985
6986                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6987                            + scanFile + " ignored: updated version " + ps.versionCode
6988                            + " better than this " + pkg.mVersionCode);
6989                } else {
6990                    // The current app on the system partition is better than
6991                    // what we have updated to on the data partition; switch
6992                    // back to the system partition version.
6993                    // At this point, its safely assumed that package installation for
6994                    // apps in system partition will go through. If not there won't be a working
6995                    // version of the app
6996                    // writer
6997                    synchronized (mPackages) {
6998                        // Just remove the loaded entries from package lists.
6999                        mPackages.remove(ps.name);
7000                    }
7001
7002                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7003                            + " reverting from " + ps.codePathString
7004                            + ": new version " + pkg.mVersionCode
7005                            + " better than installed " + ps.versionCode);
7006
7007                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7008                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7009                    synchronized (mInstallLock) {
7010                        args.cleanUpResourcesLI();
7011                    }
7012                    synchronized (mPackages) {
7013                        mSettings.enableSystemPackageLPw(ps.name);
7014                    }
7015                    updatedPkgBetter = true;
7016                }
7017            }
7018        }
7019
7020        if (updatedPkg != null) {
7021            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7022            // initially
7023            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7024
7025            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7026            // flag set initially
7027            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7028                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7029            }
7030        }
7031
7032        // Verify certificates against what was last scanned
7033        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7034
7035        /*
7036         * A new system app appeared, but we already had a non-system one of the
7037         * same name installed earlier.
7038         */
7039        boolean shouldHideSystemApp = false;
7040        if (updatedPkg == null && ps != null
7041                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7042            /*
7043             * Check to make sure the signatures match first. If they don't,
7044             * wipe the installed application and its data.
7045             */
7046            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7047                    != PackageManager.SIGNATURE_MATCH) {
7048                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7049                        + " signatures don't match existing userdata copy; removing");
7050                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7051                        "scanPackageInternalLI")) {
7052                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7053                }
7054                ps = null;
7055            } else {
7056                /*
7057                 * If the newly-added system app is an older version than the
7058                 * already installed version, hide it. It will be scanned later
7059                 * and re-added like an update.
7060                 */
7061                if (pkg.mVersionCode <= ps.versionCode) {
7062                    shouldHideSystemApp = true;
7063                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7064                            + " but new version " + pkg.mVersionCode + " better than installed "
7065                            + ps.versionCode + "; hiding system");
7066                } else {
7067                    /*
7068                     * The newly found system app is a newer version that the
7069                     * one previously installed. Simply remove the
7070                     * already-installed application and replace it with our own
7071                     * while keeping the application data.
7072                     */
7073                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7074                            + " reverting from " + ps.codePathString + ": new version "
7075                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7076                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7077                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7078                    synchronized (mInstallLock) {
7079                        args.cleanUpResourcesLI();
7080                    }
7081                }
7082            }
7083        }
7084
7085        // The apk is forward locked (not public) if its code and resources
7086        // are kept in different files. (except for app in either system or
7087        // vendor path).
7088        // TODO grab this value from PackageSettings
7089        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7090            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7091                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7092            }
7093        }
7094
7095        // TODO: extend to support forward-locked splits
7096        String resourcePath = null;
7097        String baseResourcePath = null;
7098        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7099            if (ps != null && ps.resourcePathString != null) {
7100                resourcePath = ps.resourcePathString;
7101                baseResourcePath = ps.resourcePathString;
7102            } else {
7103                // Should not happen at all. Just log an error.
7104                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7105            }
7106        } else {
7107            resourcePath = pkg.codePath;
7108            baseResourcePath = pkg.baseCodePath;
7109        }
7110
7111        // Set application objects path explicitly.
7112        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7113        pkg.setApplicationInfoCodePath(pkg.codePath);
7114        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7115        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7116        pkg.setApplicationInfoResourcePath(resourcePath);
7117        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7118        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7119
7120        // Note that we invoke the following method only if we are about to unpack an application
7121        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7122                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7123
7124        /*
7125         * If the system app should be overridden by a previously installed
7126         * data, hide the system app now and let the /data/app scan pick it up
7127         * again.
7128         */
7129        if (shouldHideSystemApp) {
7130            synchronized (mPackages) {
7131                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7132            }
7133        }
7134
7135        return scannedPkg;
7136    }
7137
7138    private static String fixProcessName(String defProcessName,
7139            String processName) {
7140        if (processName == null) {
7141            return defProcessName;
7142        }
7143        return processName;
7144    }
7145
7146    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7147            throws PackageManagerException {
7148        if (pkgSetting.signatures.mSignatures != null) {
7149            // Already existing package. Make sure signatures match
7150            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7151                    == PackageManager.SIGNATURE_MATCH;
7152            if (!match) {
7153                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7154                        == PackageManager.SIGNATURE_MATCH;
7155            }
7156            if (!match) {
7157                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7158                        == PackageManager.SIGNATURE_MATCH;
7159            }
7160            if (!match) {
7161                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7162                        + pkg.packageName + " signatures do not match the "
7163                        + "previously installed version; ignoring!");
7164            }
7165        }
7166
7167        // Check for shared user signatures
7168        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7169            // Already existing package. Make sure signatures match
7170            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7171                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7172            if (!match) {
7173                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7174                        == PackageManager.SIGNATURE_MATCH;
7175            }
7176            if (!match) {
7177                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7178                        == PackageManager.SIGNATURE_MATCH;
7179            }
7180            if (!match) {
7181                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7182                        "Package " + pkg.packageName
7183                        + " has no signatures that match those in shared user "
7184                        + pkgSetting.sharedUser.name + "; ignoring!");
7185            }
7186        }
7187    }
7188
7189    /**
7190     * Enforces that only the system UID or root's UID can call a method exposed
7191     * via Binder.
7192     *
7193     * @param message used as message if SecurityException is thrown
7194     * @throws SecurityException if the caller is not system or root
7195     */
7196    private static final void enforceSystemOrRoot(String message) {
7197        final int uid = Binder.getCallingUid();
7198        if (uid != Process.SYSTEM_UID && uid != 0) {
7199            throw new SecurityException(message);
7200        }
7201    }
7202
7203    @Override
7204    public void performFstrimIfNeeded() {
7205        enforceSystemOrRoot("Only the system can request fstrim");
7206
7207        // Before everything else, see whether we need to fstrim.
7208        try {
7209            IStorageManager sm = PackageHelper.getStorageManager();
7210            if (sm != null) {
7211                boolean doTrim = false;
7212                final long interval = android.provider.Settings.Global.getLong(
7213                        mContext.getContentResolver(),
7214                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7215                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7216                if (interval > 0) {
7217                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7218                    if (timeSinceLast > interval) {
7219                        doTrim = true;
7220                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7221                                + "; running immediately");
7222                    }
7223                }
7224                if (doTrim) {
7225                    final boolean dexOptDialogShown;
7226                    synchronized (mPackages) {
7227                        dexOptDialogShown = mDexOptDialogShown;
7228                    }
7229                    if (!isFirstBoot() && dexOptDialogShown) {
7230                        try {
7231                            ActivityManager.getService().showBootMessage(
7232                                    mContext.getResources().getString(
7233                                            R.string.android_upgrading_fstrim), true);
7234                        } catch (RemoteException e) {
7235                        }
7236                    }
7237                    sm.runMaintenance();
7238                }
7239            } else {
7240                Slog.e(TAG, "storageManager service unavailable!");
7241            }
7242        } catch (RemoteException e) {
7243            // Can't happen; StorageManagerService is local
7244        }
7245    }
7246
7247    @Override
7248    public void updatePackagesIfNeeded() {
7249        enforceSystemOrRoot("Only the system can request package update");
7250
7251        // We need to re-extract after an OTA.
7252        boolean causeUpgrade = isUpgrade();
7253
7254        // First boot or factory reset.
7255        // Note: we also handle devices that are upgrading to N right now as if it is their
7256        //       first boot, as they do not have profile data.
7257        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7258
7259        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7260        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7261
7262        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7263            return;
7264        }
7265
7266        List<PackageParser.Package> pkgs;
7267        synchronized (mPackages) {
7268            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7269        }
7270
7271        final long startTime = System.nanoTime();
7272        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7273                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7274
7275        final int elapsedTimeSeconds =
7276                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7277
7278        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7279        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7280        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7281        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7282        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7283    }
7284
7285    /**
7286     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7287     * containing statistics about the invocation. The array consists of three elements,
7288     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7289     * and {@code numberOfPackagesFailed}.
7290     */
7291    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7292            String compilerFilter) {
7293
7294        int numberOfPackagesVisited = 0;
7295        int numberOfPackagesOptimized = 0;
7296        int numberOfPackagesSkipped = 0;
7297        int numberOfPackagesFailed = 0;
7298        final int numberOfPackagesToDexopt = pkgs.size();
7299
7300        for (PackageParser.Package pkg : pkgs) {
7301            numberOfPackagesVisited++;
7302
7303            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7304                if (DEBUG_DEXOPT) {
7305                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7306                }
7307                numberOfPackagesSkipped++;
7308                continue;
7309            }
7310
7311            if (DEBUG_DEXOPT) {
7312                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7313                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7314            }
7315
7316            if (showDialog) {
7317                try {
7318                    ActivityManager.getService().showBootMessage(
7319                            mContext.getResources().getString(R.string.android_upgrading_apk,
7320                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7321                } catch (RemoteException e) {
7322                }
7323                synchronized (mPackages) {
7324                    mDexOptDialogShown = true;
7325                }
7326            }
7327
7328            // If the OTA updates a system app which was previously preopted to a non-preopted state
7329            // the app might end up being verified at runtime. That's because by default the apps
7330            // are verify-profile but for preopted apps there's no profile.
7331            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7332            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7333            // filter (by default interpret-only).
7334            // Note that at this stage unused apps are already filtered.
7335            if (isSystemApp(pkg) &&
7336                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7337                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7338                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7339            }
7340
7341            // If the OTA updates a system app which was previously preopted to a non-preopted state
7342            // the app might end up being verified at runtime. That's because by default the apps
7343            // are verify-profile but for preopted apps there's no profile.
7344            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7345            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7346            // filter (by default interpret-only).
7347            // Note that at this stage unused apps are already filtered.
7348            if (isSystemApp(pkg) &&
7349                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7350                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7351                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7352            }
7353
7354            // checkProfiles is false to avoid merging profiles during boot which
7355            // might interfere with background compilation (b/28612421).
7356            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7357            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7358            // trade-off worth doing to save boot time work.
7359            int dexOptStatus = performDexOptTraced(pkg.packageName,
7360                    false /* checkProfiles */,
7361                    compilerFilter,
7362                    false /* force */);
7363            switch (dexOptStatus) {
7364                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7365                    numberOfPackagesOptimized++;
7366                    break;
7367                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7368                    numberOfPackagesSkipped++;
7369                    break;
7370                case PackageDexOptimizer.DEX_OPT_FAILED:
7371                    numberOfPackagesFailed++;
7372                    break;
7373                default:
7374                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7375                    break;
7376            }
7377        }
7378
7379        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7380                numberOfPackagesFailed };
7381    }
7382
7383    @Override
7384    public void notifyPackageUse(String packageName, int reason) {
7385        synchronized (mPackages) {
7386            PackageParser.Package p = mPackages.get(packageName);
7387            if (p == null) {
7388                return;
7389            }
7390            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7391        }
7392    }
7393
7394    // TODO: this is not used nor needed. Delete it.
7395    @Override
7396    public boolean performDexOptIfNeeded(String packageName) {
7397        int dexOptStatus = performDexOptTraced(packageName,
7398                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7399        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7400    }
7401
7402    @Override
7403    public boolean performDexOpt(String packageName,
7404            boolean checkProfiles, int compileReason, boolean force) {
7405        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7406                getCompilerFilterForReason(compileReason), force);
7407        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7408    }
7409
7410    @Override
7411    public boolean performDexOptMode(String packageName,
7412            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7413        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7414                targetCompilerFilter, force);
7415        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7416    }
7417
7418    private int performDexOptTraced(String packageName,
7419                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7420        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7421        try {
7422            return performDexOptInternal(packageName, checkProfiles,
7423                    targetCompilerFilter, force);
7424        } finally {
7425            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7426        }
7427    }
7428
7429    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7430    // if the package can now be considered up to date for the given filter.
7431    private int performDexOptInternal(String packageName,
7432                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7433        PackageParser.Package p;
7434        synchronized (mPackages) {
7435            p = mPackages.get(packageName);
7436            if (p == null) {
7437                // Package could not be found. Report failure.
7438                return PackageDexOptimizer.DEX_OPT_FAILED;
7439            }
7440            mPackageUsage.maybeWriteAsync(mPackages);
7441            mCompilerStats.maybeWriteAsync();
7442        }
7443        long callingId = Binder.clearCallingIdentity();
7444        try {
7445            synchronized (mInstallLock) {
7446                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7447                        targetCompilerFilter, force);
7448            }
7449        } finally {
7450            Binder.restoreCallingIdentity(callingId);
7451        }
7452    }
7453
7454    public ArraySet<String> getOptimizablePackages() {
7455        ArraySet<String> pkgs = new ArraySet<String>();
7456        synchronized (mPackages) {
7457            for (PackageParser.Package p : mPackages.values()) {
7458                if (PackageDexOptimizer.canOptimizePackage(p)) {
7459                    pkgs.add(p.packageName);
7460                }
7461            }
7462        }
7463        return pkgs;
7464    }
7465
7466    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7467            boolean checkProfiles, String targetCompilerFilter,
7468            boolean force) {
7469        // Select the dex optimizer based on the force parameter.
7470        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7471        //       allocate an object here.
7472        PackageDexOptimizer pdo = force
7473                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7474                : mPackageDexOptimizer;
7475
7476        // Optimize all dependencies first. Note: we ignore the return value and march on
7477        // on errors.
7478        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7479        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7480        if (!deps.isEmpty()) {
7481            for (PackageParser.Package depPackage : deps) {
7482                // TODO: Analyze and investigate if we (should) profile libraries.
7483                // Currently this will do a full compilation of the library by default.
7484                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7485                        false /* checkProfiles */,
7486                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7487                        getOrCreateCompilerPackageStats(depPackage));
7488            }
7489        }
7490        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7491                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7492    }
7493
7494    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7495        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7496            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7497            Set<String> collectedNames = new HashSet<>();
7498            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7499
7500            retValue.remove(p);
7501
7502            return retValue;
7503        } else {
7504            return Collections.emptyList();
7505        }
7506    }
7507
7508    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7509            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7510        if (!collectedNames.contains(p.packageName)) {
7511            collectedNames.add(p.packageName);
7512            collected.add(p);
7513
7514            if (p.usesLibraries != null) {
7515                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7516            }
7517            if (p.usesOptionalLibraries != null) {
7518                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7519                        collectedNames);
7520            }
7521        }
7522    }
7523
7524    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7525            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7526        for (String libName : libs) {
7527            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7528            if (libPkg != null) {
7529                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7530            }
7531        }
7532    }
7533
7534    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7535        synchronized (mPackages) {
7536            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7537            if (lib != null && lib.apk != null) {
7538                return mPackages.get(lib.apk);
7539            }
7540        }
7541        return null;
7542    }
7543
7544    public void shutdown() {
7545        mPackageUsage.writeNow(mPackages);
7546        mCompilerStats.writeNow();
7547    }
7548
7549    @Override
7550    public void dumpProfiles(String packageName) {
7551        PackageParser.Package pkg;
7552        synchronized (mPackages) {
7553            pkg = mPackages.get(packageName);
7554            if (pkg == null) {
7555                throw new IllegalArgumentException("Unknown package: " + packageName);
7556            }
7557        }
7558        /* Only the shell, root, or the app user should be able to dump profiles. */
7559        int callingUid = Binder.getCallingUid();
7560        if (callingUid != Process.SHELL_UID &&
7561            callingUid != Process.ROOT_UID &&
7562            callingUid != pkg.applicationInfo.uid) {
7563            throw new SecurityException("dumpProfiles");
7564        }
7565
7566        synchronized (mInstallLock) {
7567            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7568            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7569            try {
7570                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7571                String gid = Integer.toString(sharedGid);
7572                String codePaths = TextUtils.join(";", allCodePaths);
7573                mInstaller.dumpProfiles(gid, packageName, codePaths);
7574            } catch (InstallerException e) {
7575                Slog.w(TAG, "Failed to dump profiles", e);
7576            }
7577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7578        }
7579    }
7580
7581    @Override
7582    public void forceDexOpt(String packageName) {
7583        enforceSystemOrRoot("forceDexOpt");
7584
7585        PackageParser.Package pkg;
7586        synchronized (mPackages) {
7587            pkg = mPackages.get(packageName);
7588            if (pkg == null) {
7589                throw new IllegalArgumentException("Unknown package: " + packageName);
7590            }
7591        }
7592
7593        synchronized (mInstallLock) {
7594            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7595
7596            // Whoever is calling forceDexOpt wants a fully compiled package.
7597            // Don't use profiles since that may cause compilation to be skipped.
7598            final int res = performDexOptInternalWithDependenciesLI(pkg,
7599                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7600                    true /* force */);
7601
7602            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7603            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7604                throw new IllegalStateException("Failed to dexopt: " + res);
7605            }
7606        }
7607    }
7608
7609    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7610        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7611            Slog.w(TAG, "Unable to update from " + oldPkg.name
7612                    + " to " + newPkg.packageName
7613                    + ": old package not in system partition");
7614            return false;
7615        } else if (mPackages.get(oldPkg.name) != null) {
7616            Slog.w(TAG, "Unable to update from " + oldPkg.name
7617                    + " to " + newPkg.packageName
7618                    + ": old package still exists");
7619            return false;
7620        }
7621        return true;
7622    }
7623
7624    void removeCodePathLI(File codePath) {
7625        if (codePath.isDirectory()) {
7626            try {
7627                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7628            } catch (InstallerException e) {
7629                Slog.w(TAG, "Failed to remove code path", e);
7630            }
7631        } else {
7632            codePath.delete();
7633        }
7634    }
7635
7636    private int[] resolveUserIds(int userId) {
7637        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7638    }
7639
7640    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7641        if (pkg == null) {
7642            Slog.wtf(TAG, "Package was null!", new Throwable());
7643            return;
7644        }
7645        clearAppDataLeafLIF(pkg, userId, flags);
7646        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7647        for (int i = 0; i < childCount; i++) {
7648            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7649        }
7650    }
7651
7652    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7653        final PackageSetting ps;
7654        synchronized (mPackages) {
7655            ps = mSettings.mPackages.get(pkg.packageName);
7656        }
7657        for (int realUserId : resolveUserIds(userId)) {
7658            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7659            try {
7660                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7661                        ceDataInode);
7662            } catch (InstallerException e) {
7663                Slog.w(TAG, String.valueOf(e));
7664            }
7665        }
7666    }
7667
7668    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7669        if (pkg == null) {
7670            Slog.wtf(TAG, "Package was null!", new Throwable());
7671            return;
7672        }
7673        destroyAppDataLeafLIF(pkg, userId, flags);
7674        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7675        for (int i = 0; i < childCount; i++) {
7676            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7677        }
7678    }
7679
7680    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7681        final PackageSetting ps;
7682        synchronized (mPackages) {
7683            ps = mSettings.mPackages.get(pkg.packageName);
7684        }
7685        for (int realUserId : resolveUserIds(userId)) {
7686            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7687            try {
7688                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7689                        ceDataInode);
7690            } catch (InstallerException e) {
7691                Slog.w(TAG, String.valueOf(e));
7692            }
7693        }
7694    }
7695
7696    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7697        if (pkg == null) {
7698            Slog.wtf(TAG, "Package was null!", new Throwable());
7699            return;
7700        }
7701        destroyAppProfilesLeafLIF(pkg);
7702        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7703        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7704        for (int i = 0; i < childCount; i++) {
7705            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7706            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7707                    true /* removeBaseMarker */);
7708        }
7709    }
7710
7711    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7712            boolean removeBaseMarker) {
7713        if (pkg.isForwardLocked()) {
7714            return;
7715        }
7716
7717        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7718            try {
7719                path = PackageManagerServiceUtils.realpath(new File(path));
7720            } catch (IOException e) {
7721                // TODO: Should we return early here ?
7722                Slog.w(TAG, "Failed to get canonical path", e);
7723                continue;
7724            }
7725
7726            final String useMarker = path.replace('/', '@');
7727            for (int realUserId : resolveUserIds(userId)) {
7728                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7729                if (removeBaseMarker) {
7730                    File foreignUseMark = new File(profileDir, useMarker);
7731                    if (foreignUseMark.exists()) {
7732                        if (!foreignUseMark.delete()) {
7733                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7734                                    + pkg.packageName);
7735                        }
7736                    }
7737                }
7738
7739                File[] markers = profileDir.listFiles();
7740                if (markers != null) {
7741                    final String searchString = "@" + pkg.packageName + "@";
7742                    // We also delete all markers that contain the package name we're
7743                    // uninstalling. These are associated with secondary dex-files belonging
7744                    // to the package. Reconstructing the path of these dex files is messy
7745                    // in general.
7746                    for (File marker : markers) {
7747                        if (marker.getName().indexOf(searchString) > 0) {
7748                            if (!marker.delete()) {
7749                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7750                                    + pkg.packageName);
7751                            }
7752                        }
7753                    }
7754                }
7755            }
7756        }
7757    }
7758
7759    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7760        try {
7761            mInstaller.destroyAppProfiles(pkg.packageName);
7762        } catch (InstallerException e) {
7763            Slog.w(TAG, String.valueOf(e));
7764        }
7765    }
7766
7767    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7768        if (pkg == null) {
7769            Slog.wtf(TAG, "Package was null!", new Throwable());
7770            return;
7771        }
7772        clearAppProfilesLeafLIF(pkg);
7773        // We don't remove the base foreign use marker when clearing profiles because
7774        // we will rename it when the app is updated. Unlike the actual profile contents,
7775        // the foreign use marker is good across installs.
7776        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7777        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7778        for (int i = 0; i < childCount; i++) {
7779            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7780        }
7781    }
7782
7783    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7784        try {
7785            mInstaller.clearAppProfiles(pkg.packageName);
7786        } catch (InstallerException e) {
7787            Slog.w(TAG, String.valueOf(e));
7788        }
7789    }
7790
7791    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7792            long lastUpdateTime) {
7793        // Set parent install/update time
7794        PackageSetting ps = (PackageSetting) pkg.mExtras;
7795        if (ps != null) {
7796            ps.firstInstallTime = firstInstallTime;
7797            ps.lastUpdateTime = lastUpdateTime;
7798        }
7799        // Set children install/update time
7800        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7801        for (int i = 0; i < childCount; i++) {
7802            PackageParser.Package childPkg = pkg.childPackages.get(i);
7803            ps = (PackageSetting) childPkg.mExtras;
7804            if (ps != null) {
7805                ps.firstInstallTime = firstInstallTime;
7806                ps.lastUpdateTime = lastUpdateTime;
7807            }
7808        }
7809    }
7810
7811    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7812            PackageParser.Package changingLib) {
7813        if (file.path != null) {
7814            usesLibraryFiles.add(file.path);
7815            return;
7816        }
7817        PackageParser.Package p = mPackages.get(file.apk);
7818        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7819            // If we are doing this while in the middle of updating a library apk,
7820            // then we need to make sure to use that new apk for determining the
7821            // dependencies here.  (We haven't yet finished committing the new apk
7822            // to the package manager state.)
7823            if (p == null || p.packageName.equals(changingLib.packageName)) {
7824                p = changingLib;
7825            }
7826        }
7827        if (p != null) {
7828            usesLibraryFiles.addAll(p.getAllCodePaths());
7829        }
7830    }
7831
7832    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
7833            PackageParser.Package changingLib) throws PackageManagerException {
7834        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7835            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7836            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7837            for (int i=0; i<N; i++) {
7838                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7839                if (file == null) {
7840                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7841                            "Package " + pkg.packageName + " requires unavailable shared library "
7842                            + pkg.usesLibraries.get(i) + "; failing!");
7843                }
7844                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7845            }
7846            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7847            for (int i=0; i<N; i++) {
7848                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7849                if (file == null) {
7850                    Slog.w(TAG, "Package " + pkg.packageName
7851                            + " desires unavailable shared library "
7852                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7853                } else {
7854                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7855                }
7856            }
7857            N = usesLibraryFiles.size();
7858            if (N > 0) {
7859                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7860            } else {
7861                pkg.usesLibraryFiles = null;
7862            }
7863        }
7864    }
7865
7866    private static boolean hasString(List<String> list, List<String> which) {
7867        if (list == null) {
7868            return false;
7869        }
7870        for (int i=list.size()-1; i>=0; i--) {
7871            for (int j=which.size()-1; j>=0; j--) {
7872                if (which.get(j).equals(list.get(i))) {
7873                    return true;
7874                }
7875            }
7876        }
7877        return false;
7878    }
7879
7880    private void updateAllSharedLibrariesLPw() {
7881        for (PackageParser.Package pkg : mPackages.values()) {
7882            try {
7883                updateSharedLibrariesLPr(pkg, null);
7884            } catch (PackageManagerException e) {
7885                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7886            }
7887        }
7888    }
7889
7890    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7891            PackageParser.Package changingPkg) {
7892        ArrayList<PackageParser.Package> res = null;
7893        for (PackageParser.Package pkg : mPackages.values()) {
7894            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7895                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7896                if (res == null) {
7897                    res = new ArrayList<PackageParser.Package>();
7898                }
7899                res.add(pkg);
7900                try {
7901                    updateSharedLibrariesLPr(pkg, changingPkg);
7902                } catch (PackageManagerException e) {
7903                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7904                }
7905            }
7906        }
7907        return res;
7908    }
7909
7910    /**
7911     * Derive the value of the {@code cpuAbiOverride} based on the provided
7912     * value and an optional stored value from the package settings.
7913     */
7914    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7915        String cpuAbiOverride = null;
7916
7917        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7918            cpuAbiOverride = null;
7919        } else if (abiOverride != null) {
7920            cpuAbiOverride = abiOverride;
7921        } else if (settings != null) {
7922            cpuAbiOverride = settings.cpuAbiOverrideString;
7923        }
7924
7925        return cpuAbiOverride;
7926    }
7927
7928    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7929            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7930                    throws PackageManagerException {
7931        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7932        // If the package has children and this is the first dive in the function
7933        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7934        // whether all packages (parent and children) would be successfully scanned
7935        // before the actual scan since scanning mutates internal state and we want
7936        // to atomically install the package and its children.
7937        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7938            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7939                scanFlags |= SCAN_CHECK_ONLY;
7940            }
7941        } else {
7942            scanFlags &= ~SCAN_CHECK_ONLY;
7943        }
7944
7945        final PackageParser.Package scannedPkg;
7946        try {
7947            // Scan the parent
7948            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7949            // Scan the children
7950            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7951            for (int i = 0; i < childCount; i++) {
7952                PackageParser.Package childPkg = pkg.childPackages.get(i);
7953                scanPackageLI(childPkg, policyFlags,
7954                        scanFlags, currentTime, user);
7955            }
7956        } finally {
7957            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7958        }
7959
7960        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7961            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7962        }
7963
7964        return scannedPkg;
7965    }
7966
7967    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7968            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7969        boolean success = false;
7970        try {
7971            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7972                    currentTime, user);
7973            success = true;
7974            return res;
7975        } finally {
7976            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7977                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7978                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7979                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7980                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7981            }
7982        }
7983    }
7984
7985    /**
7986     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7987     */
7988    private static boolean apkHasCode(String fileName) {
7989        StrictJarFile jarFile = null;
7990        try {
7991            jarFile = new StrictJarFile(fileName,
7992                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7993            return jarFile.findEntry("classes.dex") != null;
7994        } catch (IOException ignore) {
7995        } finally {
7996            try {
7997                if (jarFile != null) {
7998                    jarFile.close();
7999                }
8000            } catch (IOException ignore) {}
8001        }
8002        return false;
8003    }
8004
8005    /**
8006     * Enforces code policy for the package. This ensures that if an APK has
8007     * declared hasCode="true" in its manifest that the APK actually contains
8008     * code.
8009     *
8010     * @throws PackageManagerException If bytecode could not be found when it should exist
8011     */
8012    private static void assertCodePolicy(PackageParser.Package pkg)
8013            throws PackageManagerException {
8014        final boolean shouldHaveCode =
8015                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8016        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8017            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8018                    "Package " + pkg.baseCodePath + " code is missing");
8019        }
8020
8021        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8022            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8023                final boolean splitShouldHaveCode =
8024                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8025                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8026                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8027                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8028                }
8029            }
8030        }
8031    }
8032
8033    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8034            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8035                    throws PackageManagerException {
8036        if (DEBUG_PACKAGE_SCANNING) {
8037            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8038                Log.d(TAG, "Scanning package " + pkg.packageName);
8039        }
8040
8041        applyPolicy(pkg, policyFlags);
8042
8043        assertPackageIsValid(pkg, policyFlags, scanFlags);
8044
8045        // Initialize package source and resource directories
8046        final File scanFile = new File(pkg.codePath);
8047        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8048        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8049
8050        SharedUserSetting suid = null;
8051        PackageSetting pkgSetting = null;
8052
8053        // Getting the package setting may have a side-effect, so if we
8054        // are only checking if scan would succeed, stash a copy of the
8055        // old setting to restore at the end.
8056        PackageSetting nonMutatedPs = null;
8057
8058        // writer
8059        synchronized (mPackages) {
8060            if (pkg.mSharedUserId != null) {
8061                // SIDE EFFECTS; may potentially allocate a new shared user
8062                suid = mSettings.getSharedUserLPw(
8063                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8064                if (DEBUG_PACKAGE_SCANNING) {
8065                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8066                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8067                                + "): packages=" + suid.packages);
8068                }
8069            }
8070
8071            // Check if we are renaming from an original package name.
8072            PackageSetting origPackage = null;
8073            String realName = null;
8074            if (pkg.mOriginalPackages != null) {
8075                // This package may need to be renamed to a previously
8076                // installed name.  Let's check on that...
8077                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8078                if (pkg.mOriginalPackages.contains(renamed)) {
8079                    // This package had originally been installed as the
8080                    // original name, and we have already taken care of
8081                    // transitioning to the new one.  Just update the new
8082                    // one to continue using the old name.
8083                    realName = pkg.mRealPackage;
8084                    if (!pkg.packageName.equals(renamed)) {
8085                        // Callers into this function may have already taken
8086                        // care of renaming the package; only do it here if
8087                        // it is not already done.
8088                        pkg.setPackageName(renamed);
8089                    }
8090                } else {
8091                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8092                        if ((origPackage = mSettings.getPackageLPr(
8093                                pkg.mOriginalPackages.get(i))) != null) {
8094                            // We do have the package already installed under its
8095                            // original name...  should we use it?
8096                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8097                                // New package is not compatible with original.
8098                                origPackage = null;
8099                                continue;
8100                            } else if (origPackage.sharedUser != null) {
8101                                // Make sure uid is compatible between packages.
8102                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8103                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8104                                            + " to " + pkg.packageName + ": old uid "
8105                                            + origPackage.sharedUser.name
8106                                            + " differs from " + pkg.mSharedUserId);
8107                                    origPackage = null;
8108                                    continue;
8109                                }
8110                                // TODO: Add case when shared user id is added [b/28144775]
8111                            } else {
8112                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8113                                        + pkg.packageName + " to old name " + origPackage.name);
8114                            }
8115                            break;
8116                        }
8117                    }
8118                }
8119            }
8120
8121            if (mTransferedPackages.contains(pkg.packageName)) {
8122                Slog.w(TAG, "Package " + pkg.packageName
8123                        + " was transferred to another, but its .apk remains");
8124            }
8125
8126            // See comments in nonMutatedPs declaration
8127            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8128                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8129                if (foundPs != null) {
8130                    nonMutatedPs = new PackageSetting(foundPs);
8131                }
8132            }
8133
8134            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8135            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8136                PackageManagerService.reportSettingsProblem(Log.WARN,
8137                        "Package " + pkg.packageName + " shared user changed from "
8138                                + (pkgSetting.sharedUser != null
8139                                        ? pkgSetting.sharedUser.name : "<nothing>")
8140                                + " to "
8141                                + (suid != null ? suid.name : "<nothing>")
8142                                + "; replacing with new");
8143                pkgSetting = null;
8144            }
8145            final PackageSetting oldPkgSetting =
8146                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8147            final PackageSetting disabledPkgSetting =
8148                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8149            if (pkgSetting == null) {
8150                final String parentPackageName = (pkg.parentPackage != null)
8151                        ? pkg.parentPackage.packageName : null;
8152                // REMOVE SharedUserSetting from method; update in a separate call
8153                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8154                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8155                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8156                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8157                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8158                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8159                        UserManagerService.getInstance());
8160                // SIDE EFFECTS; updates system state; move elsewhere
8161                if (origPackage != null) {
8162                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8163                }
8164                mSettings.addUserToSettingLPw(pkgSetting);
8165            } else {
8166                // REMOVE SharedUserSetting from method; update in a separate call
8167                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8168                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8169                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8170                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8171                        UserManagerService.getInstance());
8172            }
8173            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8174            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8175
8176            // SIDE EFFECTS; modifies system state; move elsewhere
8177            if (pkgSetting.origPackage != null) {
8178                // If we are first transitioning from an original package,
8179                // fix up the new package's name now.  We need to do this after
8180                // looking up the package under its new name, so getPackageLP
8181                // can take care of fiddling things correctly.
8182                pkg.setPackageName(origPackage.name);
8183
8184                // File a report about this.
8185                String msg = "New package " + pkgSetting.realName
8186                        + " renamed to replace old package " + pkgSetting.name;
8187                reportSettingsProblem(Log.WARN, msg);
8188
8189                // Make a note of it.
8190                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8191                    mTransferedPackages.add(origPackage.name);
8192                }
8193
8194                // No longer need to retain this.
8195                pkgSetting.origPackage = null;
8196            }
8197
8198            // SIDE EFFECTS; modifies system state; move elsewhere
8199            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8200                // Make a note of it.
8201                mTransferedPackages.add(pkg.packageName);
8202            }
8203
8204            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8205                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8206            }
8207
8208            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8209                // Check all shared libraries and map to their actual file path.
8210                // We only do this here for apps not on a system dir, because those
8211                // are the only ones that can fail an install due to this.  We
8212                // will take care of the system apps by updating all of their
8213                // library paths after the scan is done.
8214                updateSharedLibrariesLPr(pkg, null);
8215            }
8216
8217            if (mFoundPolicyFile) {
8218                SELinuxMMAC.assignSeinfoValue(pkg);
8219            }
8220
8221            pkg.applicationInfo.uid = pkgSetting.appId;
8222            pkg.mExtras = pkgSetting;
8223            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8224                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8225                    // We just determined the app is signed correctly, so bring
8226                    // over the latest parsed certs.
8227                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8228                } else {
8229                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8230                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8231                                "Package " + pkg.packageName + " upgrade keys do not match the "
8232                                + "previously installed version");
8233                    } else {
8234                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8235                        String msg = "System package " + pkg.packageName
8236                                + " signature changed; retaining data.";
8237                        reportSettingsProblem(Log.WARN, msg);
8238                    }
8239                }
8240            } else {
8241                try {
8242                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8243                    verifySignaturesLP(pkgSetting, pkg);
8244                    // We just determined the app is signed correctly, so bring
8245                    // over the latest parsed certs.
8246                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8247                } catch (PackageManagerException e) {
8248                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8249                        throw e;
8250                    }
8251                    // The signature has changed, but this package is in the system
8252                    // image...  let's recover!
8253                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8254                    // However...  if this package is part of a shared user, but it
8255                    // doesn't match the signature of the shared user, let's fail.
8256                    // What this means is that you can't change the signatures
8257                    // associated with an overall shared user, which doesn't seem all
8258                    // that unreasonable.
8259                    if (pkgSetting.sharedUser != null) {
8260                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8261                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8262                            throw new PackageManagerException(
8263                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8264                                    "Signature mismatch for shared user: "
8265                                            + pkgSetting.sharedUser);
8266                        }
8267                    }
8268                    // File a report about this.
8269                    String msg = "System package " + pkg.packageName
8270                            + " signature changed; retaining data.";
8271                    reportSettingsProblem(Log.WARN, msg);
8272                }
8273            }
8274
8275            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8276                // This package wants to adopt ownership of permissions from
8277                // another package.
8278                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8279                    final String origName = pkg.mAdoptPermissions.get(i);
8280                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8281                    if (orig != null) {
8282                        if (verifyPackageUpdateLPr(orig, pkg)) {
8283                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8284                                    + pkg.packageName);
8285                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8286                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8287                        }
8288                    }
8289                }
8290            }
8291        }
8292
8293        pkg.applicationInfo.processName = fixProcessName(
8294                pkg.applicationInfo.packageName,
8295                pkg.applicationInfo.processName);
8296
8297        if (pkg != mPlatformPackage) {
8298            // Get all of our default paths setup
8299            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8300        }
8301
8302        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8303
8304        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8305            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8306            derivePackageAbi(
8307                    pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8308            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8309
8310            // Some system apps still use directory structure for native libraries
8311            // in which case we might end up not detecting abi solely based on apk
8312            // structure. Try to detect abi based on directory structure.
8313            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8314                    pkg.applicationInfo.primaryCpuAbi == null) {
8315                setBundledAppAbisAndRoots(pkg, pkgSetting);
8316                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8317            }
8318        } else {
8319            if ((scanFlags & SCAN_MOVE) != 0) {
8320                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8321                // but we already have this packages package info in the PackageSetting. We just
8322                // use that and derive the native library path based on the new codepath.
8323                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8324                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8325            }
8326
8327            // Set native library paths again. For moves, the path will be updated based on the
8328            // ABIs we've determined above. For non-moves, the path will be updated based on the
8329            // ABIs we determined during compilation, but the path will depend on the final
8330            // package path (after the rename away from the stage path).
8331            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8332        }
8333
8334        // This is a special case for the "system" package, where the ABI is
8335        // dictated by the zygote configuration (and init.rc). We should keep track
8336        // of this ABI so that we can deal with "normal" applications that run under
8337        // the same UID correctly.
8338        if (mPlatformPackage == pkg) {
8339            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8340                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8341        }
8342
8343        // If there's a mismatch between the abi-override in the package setting
8344        // and the abiOverride specified for the install. Warn about this because we
8345        // would've already compiled the app without taking the package setting into
8346        // account.
8347        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8348            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8349                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8350                        " for package " + pkg.packageName);
8351            }
8352        }
8353
8354        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8355        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8356        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8357
8358        // Copy the derived override back to the parsed package, so that we can
8359        // update the package settings accordingly.
8360        pkg.cpuAbiOverride = cpuAbiOverride;
8361
8362        if (DEBUG_ABI_SELECTION) {
8363            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8364                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8365                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8366        }
8367
8368        // Push the derived path down into PackageSettings so we know what to
8369        // clean up at uninstall time.
8370        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8371
8372        if (DEBUG_ABI_SELECTION) {
8373            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8374                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8375                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8376        }
8377
8378        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8379        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8380            // We don't do this here during boot because we can do it all
8381            // at once after scanning all existing packages.
8382            //
8383            // We also do this *before* we perform dexopt on this package, so that
8384            // we can avoid redundant dexopts, and also to make sure we've got the
8385            // code and package path correct.
8386            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8387        }
8388
8389        if (mFactoryTest && pkg.requestedPermissions.contains(
8390                android.Manifest.permission.FACTORY_TEST)) {
8391            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8392        }
8393
8394        if (isSystemApp(pkg)) {
8395            pkgSetting.isOrphaned = true;
8396        }
8397
8398        // Take care of first install / last update times.
8399        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8400        if (currentTime != 0) {
8401            if (pkgSetting.firstInstallTime == 0) {
8402                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8403            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8404                pkgSetting.lastUpdateTime = currentTime;
8405            }
8406        } else if (pkgSetting.firstInstallTime == 0) {
8407            // We need *something*.  Take time time stamp of the file.
8408            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8409        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8410            if (scanFileTime != pkgSetting.timeStamp) {
8411                // A package on the system image has changed; consider this
8412                // to be an update.
8413                pkgSetting.lastUpdateTime = scanFileTime;
8414            }
8415        }
8416        pkgSetting.setTimeStamp(scanFileTime);
8417
8418        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8419            if (nonMutatedPs != null) {
8420                synchronized (mPackages) {
8421                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8422                }
8423            }
8424        } else {
8425            // Modify state for the given package setting
8426            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8427                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8428        }
8429        return pkg;
8430    }
8431
8432    /**
8433     * Applies policy to the parsed package based upon the given policy flags.
8434     * Ensures the package is in a good state.
8435     * <p>
8436     * Implementation detail: This method must NOT have any side effect. It would
8437     * ideally be static, but, it requires locks to read system state.
8438     */
8439    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8440        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8441            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8442            if (pkg.applicationInfo.isDirectBootAware()) {
8443                // we're direct boot aware; set for all components
8444                for (PackageParser.Service s : pkg.services) {
8445                    s.info.encryptionAware = s.info.directBootAware = true;
8446                }
8447                for (PackageParser.Provider p : pkg.providers) {
8448                    p.info.encryptionAware = p.info.directBootAware = true;
8449                }
8450                for (PackageParser.Activity a : pkg.activities) {
8451                    a.info.encryptionAware = a.info.directBootAware = true;
8452                }
8453                for (PackageParser.Activity r : pkg.receivers) {
8454                    r.info.encryptionAware = r.info.directBootAware = true;
8455                }
8456            }
8457        } else {
8458            // Only allow system apps to be flagged as core apps.
8459            pkg.coreApp = false;
8460            // clear flags not applicable to regular apps
8461            pkg.applicationInfo.privateFlags &=
8462                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8463            pkg.applicationInfo.privateFlags &=
8464                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8465        }
8466        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8467
8468        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8469            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8470        }
8471
8472        if (!isSystemApp(pkg)) {
8473            // Only system apps can use these features.
8474            pkg.mOriginalPackages = null;
8475            pkg.mRealPackage = null;
8476            pkg.mAdoptPermissions = null;
8477        }
8478    }
8479
8480    /**
8481     * Asserts the parsed package is valid according to teh given policy. If the
8482     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8483     * <p>
8484     * Implementation detail: This method must NOT have any side effects. It would
8485     * ideally be static, but, it requires locks to read system state.
8486     *
8487     * @throws PackageManagerException If the package fails any of the validation checks
8488     */
8489    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8490            throws PackageManagerException {
8491        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8492            assertCodePolicy(pkg);
8493        }
8494
8495        if (pkg.applicationInfo.getCodePath() == null ||
8496                pkg.applicationInfo.getResourcePath() == null) {
8497            // Bail out. The resource and code paths haven't been set.
8498            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8499                    "Code and resource paths haven't been set correctly");
8500        }
8501
8502        // Make sure we're not adding any bogus keyset info
8503        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8504        ksms.assertScannedPackageValid(pkg);
8505
8506        synchronized (mPackages) {
8507            // The special "android" package can only be defined once
8508            if (pkg.packageName.equals("android")) {
8509                if (mAndroidApplication != null) {
8510                    Slog.w(TAG, "*************************************************");
8511                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8512                    Slog.w(TAG, " codePath=" + pkg.codePath);
8513                    Slog.w(TAG, "*************************************************");
8514                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8515                            "Core android package being redefined.  Skipping.");
8516                }
8517            }
8518
8519            // A package name must be unique; don't allow duplicates
8520            if (mPackages.containsKey(pkg.packageName)
8521                    || mSharedLibraries.containsKey(pkg.packageName)) {
8522                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8523                        "Application package " + pkg.packageName
8524                        + " already installed.  Skipping duplicate.");
8525            }
8526
8527            // Only privileged apps and updated privileged apps can add child packages.
8528            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8529                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8530                    throw new PackageManagerException("Only privileged apps can add child "
8531                            + "packages. Ignoring package " + pkg.packageName);
8532                }
8533                final int childCount = pkg.childPackages.size();
8534                for (int i = 0; i < childCount; i++) {
8535                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8536                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8537                            childPkg.packageName)) {
8538                        throw new PackageManagerException("Can't override child of "
8539                                + "another disabled app. Ignoring package " + pkg.packageName);
8540                    }
8541                }
8542            }
8543
8544            // If we're only installing presumed-existing packages, require that the
8545            // scanned APK is both already known and at the path previously established
8546            // for it.  Previously unknown packages we pick up normally, but if we have an
8547            // a priori expectation about this package's install presence, enforce it.
8548            // With a singular exception for new system packages. When an OTA contains
8549            // a new system package, we allow the codepath to change from a system location
8550            // to the user-installed location. If we don't allow this change, any newer,
8551            // user-installed version of the application will be ignored.
8552            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8553                if (mExpectingBetter.containsKey(pkg.packageName)) {
8554                    logCriticalInfo(Log.WARN,
8555                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8556                } else {
8557                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8558                    if (known != null) {
8559                        if (DEBUG_PACKAGE_SCANNING) {
8560                            Log.d(TAG, "Examining " + pkg.codePath
8561                                    + " and requiring known paths " + known.codePathString
8562                                    + " & " + known.resourcePathString);
8563                        }
8564                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8565                                || !pkg.applicationInfo.getResourcePath().equals(
8566                                        known.resourcePathString)) {
8567                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8568                                    "Application package " + pkg.packageName
8569                                    + " found at " + pkg.applicationInfo.getCodePath()
8570                                    + " but expected at " + known.codePathString
8571                                    + "; ignoring.");
8572                        }
8573                    }
8574                }
8575            }
8576
8577            // Verify that this new package doesn't have any content providers
8578            // that conflict with existing packages.  Only do this if the
8579            // package isn't already installed, since we don't want to break
8580            // things that are installed.
8581            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8582                final int N = pkg.providers.size();
8583                int i;
8584                for (i=0; i<N; i++) {
8585                    PackageParser.Provider p = pkg.providers.get(i);
8586                    if (p.info.authority != null) {
8587                        String names[] = p.info.authority.split(";");
8588                        for (int j = 0; j < names.length; j++) {
8589                            if (mProvidersByAuthority.containsKey(names[j])) {
8590                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8591                                final String otherPackageName =
8592                                        ((other != null && other.getComponentName() != null) ?
8593                                                other.getComponentName().getPackageName() : "?");
8594                                throw new PackageManagerException(
8595                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8596                                        "Can't install because provider name " + names[j]
8597                                                + " (in package " + pkg.applicationInfo.packageName
8598                                                + ") is already used by " + otherPackageName);
8599                            }
8600                        }
8601                    }
8602                }
8603            }
8604        }
8605    }
8606
8607    /**
8608     * Adds a scanned package to the system. When this method is finished, the package will
8609     * be available for query, resolution, etc...
8610     */
8611    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8612            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8613        final String pkgName = pkg.packageName;
8614        if (mCustomResolverComponentName != null &&
8615                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8616            setUpCustomResolverActivity(pkg);
8617        }
8618
8619        if (pkg.packageName.equals("android")) {
8620            synchronized (mPackages) {
8621                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8622                    // Set up information for our fall-back user intent resolution activity.
8623                    mPlatformPackage = pkg;
8624                    pkg.mVersionCode = mSdkVersion;
8625                    mAndroidApplication = pkg.applicationInfo;
8626
8627                    if (!mResolverReplaced) {
8628                        mResolveActivity.applicationInfo = mAndroidApplication;
8629                        mResolveActivity.name = ResolverActivity.class.getName();
8630                        mResolveActivity.packageName = mAndroidApplication.packageName;
8631                        mResolveActivity.processName = "system:ui";
8632                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8633                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8634                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8635                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8636                        mResolveActivity.exported = true;
8637                        mResolveActivity.enabled = true;
8638                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8639                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8640                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8641                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8642                                | ActivityInfo.CONFIG_ORIENTATION
8643                                | ActivityInfo.CONFIG_KEYBOARD
8644                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8645                        mResolveInfo.activityInfo = mResolveActivity;
8646                        mResolveInfo.priority = 0;
8647                        mResolveInfo.preferredOrder = 0;
8648                        mResolveInfo.match = 0;
8649                        mResolveComponentName = new ComponentName(
8650                                mAndroidApplication.packageName, mResolveActivity.name);
8651                    }
8652                }
8653            }
8654        }
8655
8656        ArrayList<PackageParser.Package> clientLibPkgs = null;
8657        // writer
8658        synchronized (mPackages) {
8659            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8660                // Only system apps can add new shared libraries.
8661                if (pkg.libraryNames != null) {
8662                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8663                        String name = pkg.libraryNames.get(i);
8664                        boolean allowed = false;
8665                        if (pkg.isUpdatedSystemApp()) {
8666                            // New library entries can only be added through the
8667                            // system image.  This is important to get rid of a lot
8668                            // of nasty edge cases: for example if we allowed a non-
8669                            // system update of the app to add a library, then uninstalling
8670                            // the update would make the library go away, and assumptions
8671                            // we made such as through app install filtering would now
8672                            // have allowed apps on the device which aren't compatible
8673                            // with it.  Better to just have the restriction here, be
8674                            // conservative, and create many fewer cases that can negatively
8675                            // impact the user experience.
8676                            final PackageSetting sysPs = mSettings
8677                                    .getDisabledSystemPkgLPr(pkg.packageName);
8678                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8679                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8680                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8681                                        allowed = true;
8682                                        break;
8683                                    }
8684                                }
8685                            }
8686                        } else {
8687                            allowed = true;
8688                        }
8689                        if (allowed) {
8690                            if (!mSharedLibraries.containsKey(name)) {
8691                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8692                            } else if (!name.equals(pkg.packageName)) {
8693                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8694                                        + name + " already exists; skipping");
8695                            }
8696                        } else {
8697                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8698                                    + name + " that is not declared on system image; skipping");
8699                        }
8700                    }
8701                    if ((scanFlags & SCAN_BOOTING) == 0) {
8702                        // If we are not booting, we need to update any applications
8703                        // that are clients of our shared library.  If we are booting,
8704                        // this will all be done once the scan is complete.
8705                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8706                    }
8707                }
8708            }
8709        }
8710
8711        if ((scanFlags & SCAN_BOOTING) != 0) {
8712            // No apps can run during boot scan, so they don't need to be frozen
8713        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8714            // Caller asked to not kill app, so it's probably not frozen
8715        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8716            // Caller asked us to ignore frozen check for some reason; they
8717            // probably didn't know the package name
8718        } else {
8719            // We're doing major surgery on this package, so it better be frozen
8720            // right now to keep it from launching
8721            checkPackageFrozen(pkgName);
8722        }
8723
8724        // Also need to kill any apps that are dependent on the library.
8725        if (clientLibPkgs != null) {
8726            for (int i=0; i<clientLibPkgs.size(); i++) {
8727                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8728                killApplication(clientPkg.applicationInfo.packageName,
8729                        clientPkg.applicationInfo.uid, "update lib");
8730            }
8731        }
8732
8733        // writer
8734        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8735
8736        boolean createIdmapFailed = false;
8737        synchronized (mPackages) {
8738            // We don't expect installation to fail beyond this point
8739
8740            if (pkgSetting.pkg != null) {
8741                // Note that |user| might be null during the initial boot scan. If a codePath
8742                // for an app has changed during a boot scan, it's due to an app update that's
8743                // part of the system partition and marker changes must be applied to all users.
8744                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
8745                final int[] userIds = resolveUserIds(userId);
8746                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
8747            }
8748
8749            // Add the new setting to mSettings
8750            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8751            // Add the new setting to mPackages
8752            mPackages.put(pkg.applicationInfo.packageName, pkg);
8753            // Make sure we don't accidentally delete its data.
8754            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8755            while (iter.hasNext()) {
8756                PackageCleanItem item = iter.next();
8757                if (pkgName.equals(item.packageName)) {
8758                    iter.remove();
8759                }
8760            }
8761
8762            // Add the package's KeySets to the global KeySetManagerService
8763            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8764            ksms.addScannedPackageLPw(pkg);
8765
8766            int N = pkg.providers.size();
8767            StringBuilder r = null;
8768            int i;
8769            for (i=0; i<N; i++) {
8770                PackageParser.Provider p = pkg.providers.get(i);
8771                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8772                        p.info.processName);
8773                mProviders.addProvider(p);
8774                p.syncable = p.info.isSyncable;
8775                if (p.info.authority != null) {
8776                    String names[] = p.info.authority.split(";");
8777                    p.info.authority = null;
8778                    for (int j = 0; j < names.length; j++) {
8779                        if (j == 1 && p.syncable) {
8780                            // We only want the first authority for a provider to possibly be
8781                            // syncable, so if we already added this provider using a different
8782                            // authority clear the syncable flag. We copy the provider before
8783                            // changing it because the mProviders object contains a reference
8784                            // to a provider that we don't want to change.
8785                            // Only do this for the second authority since the resulting provider
8786                            // object can be the same for all future authorities for this provider.
8787                            p = new PackageParser.Provider(p);
8788                            p.syncable = false;
8789                        }
8790                        if (!mProvidersByAuthority.containsKey(names[j])) {
8791                            mProvidersByAuthority.put(names[j], p);
8792                            if (p.info.authority == null) {
8793                                p.info.authority = names[j];
8794                            } else {
8795                                p.info.authority = p.info.authority + ";" + names[j];
8796                            }
8797                            if (DEBUG_PACKAGE_SCANNING) {
8798                                if (chatty)
8799                                    Log.d(TAG, "Registered content provider: " + names[j]
8800                                            + ", className = " + p.info.name + ", isSyncable = "
8801                                            + p.info.isSyncable);
8802                            }
8803                        } else {
8804                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8805                            Slog.w(TAG, "Skipping provider name " + names[j] +
8806                                    " (in package " + pkg.applicationInfo.packageName +
8807                                    "): name already used by "
8808                                    + ((other != null && other.getComponentName() != null)
8809                                            ? other.getComponentName().getPackageName() : "?"));
8810                        }
8811                    }
8812                }
8813                if (chatty) {
8814                    if (r == null) {
8815                        r = new StringBuilder(256);
8816                    } else {
8817                        r.append(' ');
8818                    }
8819                    r.append(p.info.name);
8820                }
8821            }
8822            if (r != null) {
8823                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8824            }
8825
8826            N = pkg.services.size();
8827            r = null;
8828            for (i=0; i<N; i++) {
8829                PackageParser.Service s = pkg.services.get(i);
8830                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8831                        s.info.processName);
8832                mServices.addService(s);
8833                if (chatty) {
8834                    if (r == null) {
8835                        r = new StringBuilder(256);
8836                    } else {
8837                        r.append(' ');
8838                    }
8839                    r.append(s.info.name);
8840                }
8841            }
8842            if (r != null) {
8843                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8844            }
8845
8846            N = pkg.receivers.size();
8847            r = null;
8848            for (i=0; i<N; i++) {
8849                PackageParser.Activity a = pkg.receivers.get(i);
8850                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8851                        a.info.processName);
8852                mReceivers.addActivity(a, "receiver");
8853                if (chatty) {
8854                    if (r == null) {
8855                        r = new StringBuilder(256);
8856                    } else {
8857                        r.append(' ');
8858                    }
8859                    r.append(a.info.name);
8860                }
8861            }
8862            if (r != null) {
8863                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8864            }
8865
8866            N = pkg.activities.size();
8867            r = null;
8868            for (i=0; i<N; i++) {
8869                PackageParser.Activity a = pkg.activities.get(i);
8870                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8871                        a.info.processName);
8872                mActivities.addActivity(a, "activity");
8873                if (chatty) {
8874                    if (r == null) {
8875                        r = new StringBuilder(256);
8876                    } else {
8877                        r.append(' ');
8878                    }
8879                    r.append(a.info.name);
8880                }
8881            }
8882            if (r != null) {
8883                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8884            }
8885
8886            N = pkg.permissionGroups.size();
8887            r = null;
8888            for (i=0; i<N; i++) {
8889                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8890                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8891                final String curPackageName = cur == null ? null : cur.info.packageName;
8892                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8893                if (cur == null || isPackageUpdate) {
8894                    mPermissionGroups.put(pg.info.name, pg);
8895                    if (chatty) {
8896                        if (r == null) {
8897                            r = new StringBuilder(256);
8898                        } else {
8899                            r.append(' ');
8900                        }
8901                        if (isPackageUpdate) {
8902                            r.append("UPD:");
8903                        }
8904                        r.append(pg.info.name);
8905                    }
8906                } else {
8907                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8908                            + pg.info.packageName + " ignored: original from "
8909                            + cur.info.packageName);
8910                    if (chatty) {
8911                        if (r == null) {
8912                            r = new StringBuilder(256);
8913                        } else {
8914                            r.append(' ');
8915                        }
8916                        r.append("DUP:");
8917                        r.append(pg.info.name);
8918                    }
8919                }
8920            }
8921            if (r != null) {
8922                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8923            }
8924
8925            N = pkg.permissions.size();
8926            r = null;
8927            for (i=0; i<N; i++) {
8928                PackageParser.Permission p = pkg.permissions.get(i);
8929
8930                // Assume by default that we did not install this permission into the system.
8931                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8932
8933                // Now that permission groups have a special meaning, we ignore permission
8934                // groups for legacy apps to prevent unexpected behavior. In particular,
8935                // permissions for one app being granted to someone just becase they happen
8936                // to be in a group defined by another app (before this had no implications).
8937                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8938                    p.group = mPermissionGroups.get(p.info.group);
8939                    // Warn for a permission in an unknown group.
8940                    if (p.info.group != null && p.group == null) {
8941                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8942                                + p.info.packageName + " in an unknown group " + p.info.group);
8943                    }
8944                }
8945
8946                ArrayMap<String, BasePermission> permissionMap =
8947                        p.tree ? mSettings.mPermissionTrees
8948                                : mSettings.mPermissions;
8949                BasePermission bp = permissionMap.get(p.info.name);
8950
8951                // Allow system apps to redefine non-system permissions
8952                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8953                    final boolean currentOwnerIsSystem = (bp.perm != null
8954                            && isSystemApp(bp.perm.owner));
8955                    if (isSystemApp(p.owner)) {
8956                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8957                            // It's a built-in permission and no owner, take ownership now
8958                            bp.packageSetting = pkgSetting;
8959                            bp.perm = p;
8960                            bp.uid = pkg.applicationInfo.uid;
8961                            bp.sourcePackage = p.info.packageName;
8962                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8963                        } else if (!currentOwnerIsSystem) {
8964                            String msg = "New decl " + p.owner + " of permission  "
8965                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8966                            reportSettingsProblem(Log.WARN, msg);
8967                            bp = null;
8968                        }
8969                    }
8970                }
8971
8972                if (bp == null) {
8973                    bp = new BasePermission(p.info.name, p.info.packageName,
8974                            BasePermission.TYPE_NORMAL);
8975                    permissionMap.put(p.info.name, bp);
8976                }
8977
8978                if (bp.perm == null) {
8979                    if (bp.sourcePackage == null
8980                            || bp.sourcePackage.equals(p.info.packageName)) {
8981                        BasePermission tree = findPermissionTreeLP(p.info.name);
8982                        if (tree == null
8983                                || tree.sourcePackage.equals(p.info.packageName)) {
8984                            bp.packageSetting = pkgSetting;
8985                            bp.perm = p;
8986                            bp.uid = pkg.applicationInfo.uid;
8987                            bp.sourcePackage = p.info.packageName;
8988                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8989                            if (chatty) {
8990                                if (r == null) {
8991                                    r = new StringBuilder(256);
8992                                } else {
8993                                    r.append(' ');
8994                                }
8995                                r.append(p.info.name);
8996                            }
8997                        } else {
8998                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8999                                    + p.info.packageName + " ignored: base tree "
9000                                    + tree.name + " is from package "
9001                                    + tree.sourcePackage);
9002                        }
9003                    } else {
9004                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9005                                + p.info.packageName + " ignored: original from "
9006                                + bp.sourcePackage);
9007                    }
9008                } else if (chatty) {
9009                    if (r == null) {
9010                        r = new StringBuilder(256);
9011                    } else {
9012                        r.append(' ');
9013                    }
9014                    r.append("DUP:");
9015                    r.append(p.info.name);
9016                }
9017                if (bp.perm == p) {
9018                    bp.protectionLevel = p.info.protectionLevel;
9019                }
9020            }
9021
9022            if (r != null) {
9023                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9024            }
9025
9026            N = pkg.instrumentation.size();
9027            r = null;
9028            for (i=0; i<N; i++) {
9029                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9030                a.info.packageName = pkg.applicationInfo.packageName;
9031                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9032                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9033                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9034                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9035                a.info.dataDir = pkg.applicationInfo.dataDir;
9036                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9037                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9038                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9039                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9040                mInstrumentation.put(a.getComponentName(), a);
9041                if (chatty) {
9042                    if (r == null) {
9043                        r = new StringBuilder(256);
9044                    } else {
9045                        r.append(' ');
9046                    }
9047                    r.append(a.info.name);
9048                }
9049            }
9050            if (r != null) {
9051                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9052            }
9053
9054            if (pkg.protectedBroadcasts != null) {
9055                N = pkg.protectedBroadcasts.size();
9056                for (i=0; i<N; i++) {
9057                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9058                }
9059            }
9060
9061            // Create idmap files for pairs of (packages, overlay packages).
9062            // Note: "android", ie framework-res.apk, is handled by native layers.
9063            if (pkg.mOverlayTarget != null) {
9064                // This is an overlay package.
9065                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9066                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9067                        mOverlays.put(pkg.mOverlayTarget,
9068                                new ArrayMap<String, PackageParser.Package>());
9069                    }
9070                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9071                    map.put(pkg.packageName, pkg);
9072                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9073                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9074                        createIdmapFailed = true;
9075                    }
9076                }
9077            } else if (mOverlays.containsKey(pkg.packageName) &&
9078                    !pkg.packageName.equals("android")) {
9079                // This is a regular package, with one or more known overlay packages.
9080                createIdmapsForPackageLI(pkg);
9081            }
9082        }
9083
9084        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9085
9086        if (createIdmapFailed) {
9087            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9088                    "scanPackageLI failed to createIdmap");
9089        }
9090    }
9091
9092    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9093            PackageParser.Package update, int[] userIds) {
9094        if (existing.applicationInfo == null || update.applicationInfo == null) {
9095            // This isn't due to an app installation.
9096            return;
9097        }
9098
9099        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9100        final File newCodePath = new File(update.applicationInfo.getCodePath());
9101
9102        // The codePath hasn't changed, so there's nothing for us to do.
9103        if (Objects.equals(oldCodePath, newCodePath)) {
9104            return;
9105        }
9106
9107        File canonicalNewCodePath;
9108        try {
9109            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9110        } catch (IOException e) {
9111            Slog.w(TAG, "Failed to get canonical path.", e);
9112            return;
9113        }
9114
9115        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9116        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9117        // that the last component of the path (i.e, the name) doesn't need canonicalization
9118        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9119        // but may change in the future. Hopefully this function won't exist at that point.
9120        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9121                oldCodePath.getName());
9122
9123        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9124        // with "@".
9125        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9126        if (!oldMarkerPrefix.endsWith("@")) {
9127            oldMarkerPrefix += "@";
9128        }
9129        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9130        if (!newMarkerPrefix.endsWith("@")) {
9131            newMarkerPrefix += "@";
9132        }
9133
9134        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9135        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9136        for (String updatedPath : updatedPaths) {
9137            String updatedPathName = new File(updatedPath).getName();
9138            markerSuffixes.add(updatedPathName.replace('/', '@'));
9139        }
9140
9141        for (int userId : userIds) {
9142            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9143
9144            for (String markerSuffix : markerSuffixes) {
9145                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9146                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9147                if (oldForeignUseMark.exists()) {
9148                    try {
9149                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9150                                newForeignUseMark.getAbsolutePath());
9151                    } catch (ErrnoException e) {
9152                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9153                        oldForeignUseMark.delete();
9154                    }
9155                }
9156            }
9157        }
9158    }
9159
9160    /**
9161     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9162     * is derived purely on the basis of the contents of {@code scanFile} and
9163     * {@code cpuAbiOverride}.
9164     *
9165     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9166     */
9167    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9168                                 String cpuAbiOverride, boolean extractLibs,
9169                                 File appLib32InstallDir)
9170            throws PackageManagerException {
9171        // TODO: We can probably be smarter about this stuff. For installed apps,
9172        // we can calculate this information at install time once and for all. For
9173        // system apps, we can probably assume that this information doesn't change
9174        // after the first boot scan. As things stand, we do lots of unnecessary work.
9175
9176        // Give ourselves some initial paths; we'll come back for another
9177        // pass once we've determined ABI below.
9178        setNativeLibraryPaths(pkg, appLib32InstallDir);
9179
9180        // We would never need to extract libs for forward-locked and external packages,
9181        // since the container service will do it for us. We shouldn't attempt to
9182        // extract libs from system app when it was not updated.
9183        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9184                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9185            extractLibs = false;
9186        }
9187
9188        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9189        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9190
9191        NativeLibraryHelper.Handle handle = null;
9192        try {
9193            handle = NativeLibraryHelper.Handle.create(pkg);
9194            // TODO(multiArch): This can be null for apps that didn't go through the
9195            // usual installation process. We can calculate it again, like we
9196            // do during install time.
9197            //
9198            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9199            // unnecessary.
9200            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9201
9202            // Null out the abis so that they can be recalculated.
9203            pkg.applicationInfo.primaryCpuAbi = null;
9204            pkg.applicationInfo.secondaryCpuAbi = null;
9205            if (isMultiArch(pkg.applicationInfo)) {
9206                // Warn if we've set an abiOverride for multi-lib packages..
9207                // By definition, we need to copy both 32 and 64 bit libraries for
9208                // such packages.
9209                if (pkg.cpuAbiOverride != null
9210                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9211                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9212                }
9213
9214                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9215                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9216                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9217                    if (extractLibs) {
9218                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9219                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9220                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9221                                useIsaSpecificSubdirs);
9222                    } else {
9223                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9224                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9225                    }
9226                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9227                }
9228
9229                maybeThrowExceptionForMultiArchCopy(
9230                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9231
9232                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9233                    if (extractLibs) {
9234                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9235                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9236                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9237                                useIsaSpecificSubdirs);
9238                    } else {
9239                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9240                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9241                    }
9242                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9243                }
9244
9245                maybeThrowExceptionForMultiArchCopy(
9246                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9247
9248                if (abi64 >= 0) {
9249                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9250                }
9251
9252                if (abi32 >= 0) {
9253                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9254                    if (abi64 >= 0) {
9255                        if (pkg.use32bitAbi) {
9256                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9257                            pkg.applicationInfo.primaryCpuAbi = abi;
9258                        } else {
9259                            pkg.applicationInfo.secondaryCpuAbi = abi;
9260                        }
9261                    } else {
9262                        pkg.applicationInfo.primaryCpuAbi = abi;
9263                    }
9264                }
9265
9266            } else {
9267                String[] abiList = (cpuAbiOverride != null) ?
9268                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9269
9270                // Enable gross and lame hacks for apps that are built with old
9271                // SDK tools. We must scan their APKs for renderscript bitcode and
9272                // not launch them if it's present. Don't bother checking on devices
9273                // that don't have 64 bit support.
9274                boolean needsRenderScriptOverride = false;
9275                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9276                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9277                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9278                    needsRenderScriptOverride = true;
9279                }
9280
9281                final int copyRet;
9282                if (extractLibs) {
9283                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9284                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9285                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9286                } else {
9287                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9288                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9289                }
9290                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9291
9292                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9293                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9294                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9295                }
9296
9297                if (copyRet >= 0) {
9298                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9299                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9300                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9301                } else if (needsRenderScriptOverride) {
9302                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9303                }
9304            }
9305        } catch (IOException ioe) {
9306            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9307        } finally {
9308            IoUtils.closeQuietly(handle);
9309        }
9310
9311        // Now that we've calculated the ABIs and determined if it's an internal app,
9312        // we will go ahead and populate the nativeLibraryPath.
9313        setNativeLibraryPaths(pkg, appLib32InstallDir);
9314    }
9315
9316    /**
9317     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9318     * i.e, so that all packages can be run inside a single process if required.
9319     *
9320     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9321     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9322     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9323     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9324     * updating a package that belongs to a shared user.
9325     *
9326     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9327     * adds unnecessary complexity.
9328     */
9329    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9330            PackageParser.Package scannedPackage) {
9331        String requiredInstructionSet = null;
9332        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9333            requiredInstructionSet = VMRuntime.getInstructionSet(
9334                     scannedPackage.applicationInfo.primaryCpuAbi);
9335        }
9336
9337        PackageSetting requirer = null;
9338        for (PackageSetting ps : packagesForUser) {
9339            // If packagesForUser contains scannedPackage, we skip it. This will happen
9340            // when scannedPackage is an update of an existing package. Without this check,
9341            // we will never be able to change the ABI of any package belonging to a shared
9342            // user, even if it's compatible with other packages.
9343            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9344                if (ps.primaryCpuAbiString == null) {
9345                    continue;
9346                }
9347
9348                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9349                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9350                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9351                    // this but there's not much we can do.
9352                    String errorMessage = "Instruction set mismatch, "
9353                            + ((requirer == null) ? "[caller]" : requirer)
9354                            + " requires " + requiredInstructionSet + " whereas " + ps
9355                            + " requires " + instructionSet;
9356                    Slog.w(TAG, errorMessage);
9357                }
9358
9359                if (requiredInstructionSet == null) {
9360                    requiredInstructionSet = instructionSet;
9361                    requirer = ps;
9362                }
9363            }
9364        }
9365
9366        if (requiredInstructionSet != null) {
9367            String adjustedAbi;
9368            if (requirer != null) {
9369                // requirer != null implies that either scannedPackage was null or that scannedPackage
9370                // did not require an ABI, in which case we have to adjust scannedPackage to match
9371                // the ABI of the set (which is the same as requirer's ABI)
9372                adjustedAbi = requirer.primaryCpuAbiString;
9373                if (scannedPackage != null) {
9374                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9375                }
9376            } else {
9377                // requirer == null implies that we're updating all ABIs in the set to
9378                // match scannedPackage.
9379                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9380            }
9381
9382            for (PackageSetting ps : packagesForUser) {
9383                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9384                    if (ps.primaryCpuAbiString != null) {
9385                        continue;
9386                    }
9387
9388                    ps.primaryCpuAbiString = adjustedAbi;
9389                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9390                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9391                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9392                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9393                                + " (requirer="
9394                                + (requirer == null ? "null" : requirer.pkg.packageName)
9395                                + ", scannedPackage="
9396                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9397                                + ")");
9398                        try {
9399                            mInstaller.rmdex(ps.codePathString,
9400                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9401                        } catch (InstallerException ignored) {
9402                        }
9403                    }
9404                }
9405            }
9406        }
9407    }
9408
9409    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9410        synchronized (mPackages) {
9411            mResolverReplaced = true;
9412            // Set up information for custom user intent resolution activity.
9413            mResolveActivity.applicationInfo = pkg.applicationInfo;
9414            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9415            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9416            mResolveActivity.processName = pkg.applicationInfo.packageName;
9417            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9418            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9419                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9420            mResolveActivity.theme = 0;
9421            mResolveActivity.exported = true;
9422            mResolveActivity.enabled = true;
9423            mResolveInfo.activityInfo = mResolveActivity;
9424            mResolveInfo.priority = 0;
9425            mResolveInfo.preferredOrder = 0;
9426            mResolveInfo.match = 0;
9427            mResolveComponentName = mCustomResolverComponentName;
9428            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9429                    mResolveComponentName);
9430        }
9431    }
9432
9433    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9434        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9435
9436        // Set up information for ephemeral installer activity
9437        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9438        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9439        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9440        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9441        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9442        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9443                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9444        mEphemeralInstallerActivity.theme = 0;
9445        mEphemeralInstallerActivity.exported = true;
9446        mEphemeralInstallerActivity.enabled = true;
9447        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9448        mEphemeralInstallerInfo.priority = 0;
9449        mEphemeralInstallerInfo.preferredOrder = 1;
9450        mEphemeralInstallerInfo.isDefault = true;
9451        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9452                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9453
9454        if (DEBUG_EPHEMERAL) {
9455            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9456        }
9457    }
9458
9459    private static String calculateBundledApkRoot(final String codePathString) {
9460        final File codePath = new File(codePathString);
9461        final File codeRoot;
9462        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9463            codeRoot = Environment.getRootDirectory();
9464        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9465            codeRoot = Environment.getOemDirectory();
9466        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9467            codeRoot = Environment.getVendorDirectory();
9468        } else {
9469            // Unrecognized code path; take its top real segment as the apk root:
9470            // e.g. /something/app/blah.apk => /something
9471            try {
9472                File f = codePath.getCanonicalFile();
9473                File parent = f.getParentFile();    // non-null because codePath is a file
9474                File tmp;
9475                while ((tmp = parent.getParentFile()) != null) {
9476                    f = parent;
9477                    parent = tmp;
9478                }
9479                codeRoot = f;
9480                Slog.w(TAG, "Unrecognized code path "
9481                        + codePath + " - using " + codeRoot);
9482            } catch (IOException e) {
9483                // Can't canonicalize the code path -- shenanigans?
9484                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9485                return Environment.getRootDirectory().getPath();
9486            }
9487        }
9488        return codeRoot.getPath();
9489    }
9490
9491    /**
9492     * Derive and set the location of native libraries for the given package,
9493     * which varies depending on where and how the package was installed.
9494     */
9495    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9496        final ApplicationInfo info = pkg.applicationInfo;
9497        final String codePath = pkg.codePath;
9498        final File codeFile = new File(codePath);
9499        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9500        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9501
9502        info.nativeLibraryRootDir = null;
9503        info.nativeLibraryRootRequiresIsa = false;
9504        info.nativeLibraryDir = null;
9505        info.secondaryNativeLibraryDir = null;
9506
9507        if (isApkFile(codeFile)) {
9508            // Monolithic install
9509            if (bundledApp) {
9510                // If "/system/lib64/apkname" exists, assume that is the per-package
9511                // native library directory to use; otherwise use "/system/lib/apkname".
9512                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9513                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9514                        getPrimaryInstructionSet(info));
9515
9516                // This is a bundled system app so choose the path based on the ABI.
9517                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9518                // is just the default path.
9519                final String apkName = deriveCodePathName(codePath);
9520                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9521                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9522                        apkName).getAbsolutePath();
9523
9524                if (info.secondaryCpuAbi != null) {
9525                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9526                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9527                            secondaryLibDir, apkName).getAbsolutePath();
9528                }
9529            } else if (asecApp) {
9530                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9531                        .getAbsolutePath();
9532            } else {
9533                final String apkName = deriveCodePathName(codePath);
9534                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9535                        .getAbsolutePath();
9536            }
9537
9538            info.nativeLibraryRootRequiresIsa = false;
9539            info.nativeLibraryDir = info.nativeLibraryRootDir;
9540        } else {
9541            // Cluster install
9542            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9543            info.nativeLibraryRootRequiresIsa = true;
9544
9545            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9546                    getPrimaryInstructionSet(info)).getAbsolutePath();
9547
9548            if (info.secondaryCpuAbi != null) {
9549                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9550                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9551            }
9552        }
9553    }
9554
9555    /**
9556     * Calculate the abis and roots for a bundled app. These can uniquely
9557     * be determined from the contents of the system partition, i.e whether
9558     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9559     * of this information, and instead assume that the system was built
9560     * sensibly.
9561     */
9562    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9563                                           PackageSetting pkgSetting) {
9564        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9565
9566        // If "/system/lib64/apkname" exists, assume that is the per-package
9567        // native library directory to use; otherwise use "/system/lib/apkname".
9568        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9569        setBundledAppAbi(pkg, apkRoot, apkName);
9570        // pkgSetting might be null during rescan following uninstall of updates
9571        // to a bundled app, so accommodate that possibility.  The settings in
9572        // that case will be established later from the parsed package.
9573        //
9574        // If the settings aren't null, sync them up with what we've just derived.
9575        // note that apkRoot isn't stored in the package settings.
9576        if (pkgSetting != null) {
9577            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9578            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9579        }
9580    }
9581
9582    /**
9583     * Deduces the ABI of a bundled app and sets the relevant fields on the
9584     * parsed pkg object.
9585     *
9586     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9587     *        under which system libraries are installed.
9588     * @param apkName the name of the installed package.
9589     */
9590    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9591        final File codeFile = new File(pkg.codePath);
9592
9593        final boolean has64BitLibs;
9594        final boolean has32BitLibs;
9595        if (isApkFile(codeFile)) {
9596            // Monolithic install
9597            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9598            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9599        } else {
9600            // Cluster install
9601            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9602            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9603                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9604                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9605                has64BitLibs = (new File(rootDir, isa)).exists();
9606            } else {
9607                has64BitLibs = false;
9608            }
9609            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9610                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9611                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9612                has32BitLibs = (new File(rootDir, isa)).exists();
9613            } else {
9614                has32BitLibs = false;
9615            }
9616        }
9617
9618        if (has64BitLibs && !has32BitLibs) {
9619            // The package has 64 bit libs, but not 32 bit libs. Its primary
9620            // ABI should be 64 bit. We can safely assume here that the bundled
9621            // native libraries correspond to the most preferred ABI in the list.
9622
9623            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9624            pkg.applicationInfo.secondaryCpuAbi = null;
9625        } else if (has32BitLibs && !has64BitLibs) {
9626            // The package has 32 bit libs but not 64 bit libs. Its primary
9627            // ABI should be 32 bit.
9628
9629            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9630            pkg.applicationInfo.secondaryCpuAbi = null;
9631        } else if (has32BitLibs && has64BitLibs) {
9632            // The application has both 64 and 32 bit bundled libraries. We check
9633            // here that the app declares multiArch support, and warn if it doesn't.
9634            //
9635            // We will be lenient here and record both ABIs. The primary will be the
9636            // ABI that's higher on the list, i.e, a device that's configured to prefer
9637            // 64 bit apps will see a 64 bit primary ABI,
9638
9639            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9640                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9641            }
9642
9643            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9644                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9645                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9646            } else {
9647                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9648                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9649            }
9650        } else {
9651            pkg.applicationInfo.primaryCpuAbi = null;
9652            pkg.applicationInfo.secondaryCpuAbi = null;
9653        }
9654    }
9655
9656    private void killApplication(String pkgName, int appId, String reason) {
9657        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9658    }
9659
9660    private void killApplication(String pkgName, int appId, int userId, String reason) {
9661        // Request the ActivityManager to kill the process(only for existing packages)
9662        // so that we do not end up in a confused state while the user is still using the older
9663        // version of the application while the new one gets installed.
9664        final long token = Binder.clearCallingIdentity();
9665        try {
9666            IActivityManager am = ActivityManager.getService();
9667            if (am != null) {
9668                try {
9669                    am.killApplication(pkgName, appId, userId, reason);
9670                } catch (RemoteException e) {
9671                }
9672            }
9673        } finally {
9674            Binder.restoreCallingIdentity(token);
9675        }
9676    }
9677
9678    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9679        // Remove the parent package setting
9680        PackageSetting ps = (PackageSetting) pkg.mExtras;
9681        if (ps != null) {
9682            removePackageLI(ps, chatty);
9683        }
9684        // Remove the child package setting
9685        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9686        for (int i = 0; i < childCount; i++) {
9687            PackageParser.Package childPkg = pkg.childPackages.get(i);
9688            ps = (PackageSetting) childPkg.mExtras;
9689            if (ps != null) {
9690                removePackageLI(ps, chatty);
9691            }
9692        }
9693    }
9694
9695    void removePackageLI(PackageSetting ps, boolean chatty) {
9696        if (DEBUG_INSTALL) {
9697            if (chatty)
9698                Log.d(TAG, "Removing package " + ps.name);
9699        }
9700
9701        // writer
9702        synchronized (mPackages) {
9703            mPackages.remove(ps.name);
9704            final PackageParser.Package pkg = ps.pkg;
9705            if (pkg != null) {
9706                cleanPackageDataStructuresLILPw(pkg, chatty);
9707            }
9708        }
9709    }
9710
9711    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9712        if (DEBUG_INSTALL) {
9713            if (chatty)
9714                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9715        }
9716
9717        // writer
9718        synchronized (mPackages) {
9719            // Remove the parent package
9720            mPackages.remove(pkg.applicationInfo.packageName);
9721            cleanPackageDataStructuresLILPw(pkg, chatty);
9722
9723            // Remove the child packages
9724            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9725            for (int i = 0; i < childCount; i++) {
9726                PackageParser.Package childPkg = pkg.childPackages.get(i);
9727                mPackages.remove(childPkg.applicationInfo.packageName);
9728                cleanPackageDataStructuresLILPw(childPkg, chatty);
9729            }
9730        }
9731    }
9732
9733    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9734        int N = pkg.providers.size();
9735        StringBuilder r = null;
9736        int i;
9737        for (i=0; i<N; i++) {
9738            PackageParser.Provider p = pkg.providers.get(i);
9739            mProviders.removeProvider(p);
9740            if (p.info.authority == null) {
9741
9742                /* There was another ContentProvider with this authority when
9743                 * this app was installed so this authority is null,
9744                 * Ignore it as we don't have to unregister the provider.
9745                 */
9746                continue;
9747            }
9748            String names[] = p.info.authority.split(";");
9749            for (int j = 0; j < names.length; j++) {
9750                if (mProvidersByAuthority.get(names[j]) == p) {
9751                    mProvidersByAuthority.remove(names[j]);
9752                    if (DEBUG_REMOVE) {
9753                        if (chatty)
9754                            Log.d(TAG, "Unregistered content provider: " + names[j]
9755                                    + ", className = " + p.info.name + ", isSyncable = "
9756                                    + p.info.isSyncable);
9757                    }
9758                }
9759            }
9760            if (DEBUG_REMOVE && chatty) {
9761                if (r == null) {
9762                    r = new StringBuilder(256);
9763                } else {
9764                    r.append(' ');
9765                }
9766                r.append(p.info.name);
9767            }
9768        }
9769        if (r != null) {
9770            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9771        }
9772
9773        N = pkg.services.size();
9774        r = null;
9775        for (i=0; i<N; i++) {
9776            PackageParser.Service s = pkg.services.get(i);
9777            mServices.removeService(s);
9778            if (chatty) {
9779                if (r == null) {
9780                    r = new StringBuilder(256);
9781                } else {
9782                    r.append(' ');
9783                }
9784                r.append(s.info.name);
9785            }
9786        }
9787        if (r != null) {
9788            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9789        }
9790
9791        N = pkg.receivers.size();
9792        r = null;
9793        for (i=0; i<N; i++) {
9794            PackageParser.Activity a = pkg.receivers.get(i);
9795            mReceivers.removeActivity(a, "receiver");
9796            if (DEBUG_REMOVE && chatty) {
9797                if (r == null) {
9798                    r = new StringBuilder(256);
9799                } else {
9800                    r.append(' ');
9801                }
9802                r.append(a.info.name);
9803            }
9804        }
9805        if (r != null) {
9806            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9807        }
9808
9809        N = pkg.activities.size();
9810        r = null;
9811        for (i=0; i<N; i++) {
9812            PackageParser.Activity a = pkg.activities.get(i);
9813            mActivities.removeActivity(a, "activity");
9814            if (DEBUG_REMOVE && chatty) {
9815                if (r == null) {
9816                    r = new StringBuilder(256);
9817                } else {
9818                    r.append(' ');
9819                }
9820                r.append(a.info.name);
9821            }
9822        }
9823        if (r != null) {
9824            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9825        }
9826
9827        N = pkg.permissions.size();
9828        r = null;
9829        for (i=0; i<N; i++) {
9830            PackageParser.Permission p = pkg.permissions.get(i);
9831            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9832            if (bp == null) {
9833                bp = mSettings.mPermissionTrees.get(p.info.name);
9834            }
9835            if (bp != null && bp.perm == p) {
9836                bp.perm = null;
9837                if (DEBUG_REMOVE && chatty) {
9838                    if (r == null) {
9839                        r = new StringBuilder(256);
9840                    } else {
9841                        r.append(' ');
9842                    }
9843                    r.append(p.info.name);
9844                }
9845            }
9846            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9847                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9848                if (appOpPkgs != null) {
9849                    appOpPkgs.remove(pkg.packageName);
9850                }
9851            }
9852        }
9853        if (r != null) {
9854            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9855        }
9856
9857        N = pkg.requestedPermissions.size();
9858        r = null;
9859        for (i=0; i<N; i++) {
9860            String perm = pkg.requestedPermissions.get(i);
9861            BasePermission bp = mSettings.mPermissions.get(perm);
9862            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9863                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9864                if (appOpPkgs != null) {
9865                    appOpPkgs.remove(pkg.packageName);
9866                    if (appOpPkgs.isEmpty()) {
9867                        mAppOpPermissionPackages.remove(perm);
9868                    }
9869                }
9870            }
9871        }
9872        if (r != null) {
9873            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9874        }
9875
9876        N = pkg.instrumentation.size();
9877        r = null;
9878        for (i=0; i<N; i++) {
9879            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9880            mInstrumentation.remove(a.getComponentName());
9881            if (DEBUG_REMOVE && chatty) {
9882                if (r == null) {
9883                    r = new StringBuilder(256);
9884                } else {
9885                    r.append(' ');
9886                }
9887                r.append(a.info.name);
9888            }
9889        }
9890        if (r != null) {
9891            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9892        }
9893
9894        r = null;
9895        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9896            // Only system apps can hold shared libraries.
9897            if (pkg.libraryNames != null) {
9898                for (i=0; i<pkg.libraryNames.size(); i++) {
9899                    String name = pkg.libraryNames.get(i);
9900                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9901                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9902                        mSharedLibraries.remove(name);
9903                        if (DEBUG_REMOVE && chatty) {
9904                            if (r == null) {
9905                                r = new StringBuilder(256);
9906                            } else {
9907                                r.append(' ');
9908                            }
9909                            r.append(name);
9910                        }
9911                    }
9912                }
9913            }
9914        }
9915        if (r != null) {
9916            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9917        }
9918    }
9919
9920    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9921        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9922            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9923                return true;
9924            }
9925        }
9926        return false;
9927    }
9928
9929    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9930    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9931    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9932
9933    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9934        // Update the parent permissions
9935        updatePermissionsLPw(pkg.packageName, pkg, flags);
9936        // Update the child permissions
9937        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9938        for (int i = 0; i < childCount; i++) {
9939            PackageParser.Package childPkg = pkg.childPackages.get(i);
9940            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9941        }
9942    }
9943
9944    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9945            int flags) {
9946        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9947        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9948    }
9949
9950    private void updatePermissionsLPw(String changingPkg,
9951            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9952        // Make sure there are no dangling permission trees.
9953        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9954        while (it.hasNext()) {
9955            final BasePermission bp = it.next();
9956            if (bp.packageSetting == null) {
9957                // We may not yet have parsed the package, so just see if
9958                // we still know about its settings.
9959                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9960            }
9961            if (bp.packageSetting == null) {
9962                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9963                        + " from package " + bp.sourcePackage);
9964                it.remove();
9965            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9966                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9967                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9968                            + " from package " + bp.sourcePackage);
9969                    flags |= UPDATE_PERMISSIONS_ALL;
9970                    it.remove();
9971                }
9972            }
9973        }
9974
9975        // Make sure all dynamic permissions have been assigned to a package,
9976        // and make sure there are no dangling permissions.
9977        it = mSettings.mPermissions.values().iterator();
9978        while (it.hasNext()) {
9979            final BasePermission bp = it.next();
9980            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9981                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9982                        + bp.name + " pkg=" + bp.sourcePackage
9983                        + " info=" + bp.pendingInfo);
9984                if (bp.packageSetting == null && bp.pendingInfo != null) {
9985                    final BasePermission tree = findPermissionTreeLP(bp.name);
9986                    if (tree != null && tree.perm != null) {
9987                        bp.packageSetting = tree.packageSetting;
9988                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9989                                new PermissionInfo(bp.pendingInfo));
9990                        bp.perm.info.packageName = tree.perm.info.packageName;
9991                        bp.perm.info.name = bp.name;
9992                        bp.uid = tree.uid;
9993                    }
9994                }
9995            }
9996            if (bp.packageSetting == null) {
9997                // We may not yet have parsed the package, so just see if
9998                // we still know about its settings.
9999                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10000            }
10001            if (bp.packageSetting == null) {
10002                Slog.w(TAG, "Removing dangling permission: " + bp.name
10003                        + " from package " + bp.sourcePackage);
10004                it.remove();
10005            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10006                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10007                    Slog.i(TAG, "Removing old permission: " + bp.name
10008                            + " from package " + bp.sourcePackage);
10009                    flags |= UPDATE_PERMISSIONS_ALL;
10010                    it.remove();
10011                }
10012            }
10013        }
10014
10015        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10016        // Now update the permissions for all packages, in particular
10017        // replace the granted permissions of the system packages.
10018        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10019            for (PackageParser.Package pkg : mPackages.values()) {
10020                if (pkg != pkgInfo) {
10021                    // Only replace for packages on requested volume
10022                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10023                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10024                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10025                    grantPermissionsLPw(pkg, replace, changingPkg);
10026                }
10027            }
10028        }
10029
10030        if (pkgInfo != null) {
10031            // Only replace for packages on requested volume
10032            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10033            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10034                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10035            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10036        }
10037        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10038    }
10039
10040    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10041            String packageOfInterest) {
10042        // IMPORTANT: There are two types of permissions: install and runtime.
10043        // Install time permissions are granted when the app is installed to
10044        // all device users and users added in the future. Runtime permissions
10045        // are granted at runtime explicitly to specific users. Normal and signature
10046        // protected permissions are install time permissions. Dangerous permissions
10047        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10048        // otherwise they are runtime permissions. This function does not manage
10049        // runtime permissions except for the case an app targeting Lollipop MR1
10050        // being upgraded to target a newer SDK, in which case dangerous permissions
10051        // are transformed from install time to runtime ones.
10052
10053        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10054        if (ps == null) {
10055            return;
10056        }
10057
10058        PermissionsState permissionsState = ps.getPermissionsState();
10059        PermissionsState origPermissions = permissionsState;
10060
10061        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10062
10063        boolean runtimePermissionsRevoked = false;
10064        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10065
10066        boolean changedInstallPermission = false;
10067
10068        if (replace) {
10069            ps.installPermissionsFixed = false;
10070            if (!ps.isSharedUser()) {
10071                origPermissions = new PermissionsState(permissionsState);
10072                permissionsState.reset();
10073            } else {
10074                // We need to know only about runtime permission changes since the
10075                // calling code always writes the install permissions state but
10076                // the runtime ones are written only if changed. The only cases of
10077                // changed runtime permissions here are promotion of an install to
10078                // runtime and revocation of a runtime from a shared user.
10079                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10080                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10081                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10082                    runtimePermissionsRevoked = true;
10083                }
10084            }
10085        }
10086
10087        permissionsState.setGlobalGids(mGlobalGids);
10088
10089        final int N = pkg.requestedPermissions.size();
10090        for (int i=0; i<N; i++) {
10091            final String name = pkg.requestedPermissions.get(i);
10092            final BasePermission bp = mSettings.mPermissions.get(name);
10093
10094            if (DEBUG_INSTALL) {
10095                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10096            }
10097
10098            if (bp == null || bp.packageSetting == null) {
10099                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10100                    Slog.w(TAG, "Unknown permission " + name
10101                            + " in package " + pkg.packageName);
10102                }
10103                continue;
10104            }
10105
10106
10107            // Limit ephemeral apps to ephemeral allowed permissions.
10108            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10109                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10110                        + pkg.packageName);
10111                continue;
10112            }
10113
10114            final String perm = bp.name;
10115            boolean allowedSig = false;
10116            int grant = GRANT_DENIED;
10117
10118            // Keep track of app op permissions.
10119            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10120                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10121                if (pkgs == null) {
10122                    pkgs = new ArraySet<>();
10123                    mAppOpPermissionPackages.put(bp.name, pkgs);
10124                }
10125                pkgs.add(pkg.packageName);
10126            }
10127
10128            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10129            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10130                    >= Build.VERSION_CODES.M;
10131            switch (level) {
10132                case PermissionInfo.PROTECTION_NORMAL: {
10133                    // For all apps normal permissions are install time ones.
10134                    grant = GRANT_INSTALL;
10135                } break;
10136
10137                case PermissionInfo.PROTECTION_DANGEROUS: {
10138                    // If a permission review is required for legacy apps we represent
10139                    // their permissions as always granted runtime ones since we need
10140                    // to keep the review required permission flag per user while an
10141                    // install permission's state is shared across all users.
10142                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10143                        // For legacy apps dangerous permissions are install time ones.
10144                        grant = GRANT_INSTALL;
10145                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10146                        // For legacy apps that became modern, install becomes runtime.
10147                        grant = GRANT_UPGRADE;
10148                    } else if (mPromoteSystemApps
10149                            && isSystemApp(ps)
10150                            && mExistingSystemPackages.contains(ps.name)) {
10151                        // For legacy system apps, install becomes runtime.
10152                        // We cannot check hasInstallPermission() for system apps since those
10153                        // permissions were granted implicitly and not persisted pre-M.
10154                        grant = GRANT_UPGRADE;
10155                    } else {
10156                        // For modern apps keep runtime permissions unchanged.
10157                        grant = GRANT_RUNTIME;
10158                    }
10159                } break;
10160
10161                case PermissionInfo.PROTECTION_SIGNATURE: {
10162                    // For all apps signature permissions are install time ones.
10163                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10164                    if (allowedSig) {
10165                        grant = GRANT_INSTALL;
10166                    }
10167                } break;
10168            }
10169
10170            if (DEBUG_INSTALL) {
10171                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10172            }
10173
10174            if (grant != GRANT_DENIED) {
10175                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10176                    // If this is an existing, non-system package, then
10177                    // we can't add any new permissions to it.
10178                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10179                        // Except...  if this is a permission that was added
10180                        // to the platform (note: need to only do this when
10181                        // updating the platform).
10182                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10183                            grant = GRANT_DENIED;
10184                        }
10185                    }
10186                }
10187
10188                switch (grant) {
10189                    case GRANT_INSTALL: {
10190                        // Revoke this as runtime permission to handle the case of
10191                        // a runtime permission being downgraded to an install one.
10192                        // Also in permission review mode we keep dangerous permissions
10193                        // for legacy apps
10194                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10195                            if (origPermissions.getRuntimePermissionState(
10196                                    bp.name, userId) != null) {
10197                                // Revoke the runtime permission and clear the flags.
10198                                origPermissions.revokeRuntimePermission(bp, userId);
10199                                origPermissions.updatePermissionFlags(bp, userId,
10200                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10201                                // If we revoked a permission permission, we have to write.
10202                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10203                                        changedRuntimePermissionUserIds, userId);
10204                            }
10205                        }
10206                        // Grant an install permission.
10207                        if (permissionsState.grantInstallPermission(bp) !=
10208                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10209                            changedInstallPermission = true;
10210                        }
10211                    } break;
10212
10213                    case GRANT_RUNTIME: {
10214                        // Grant previously granted runtime permissions.
10215                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10216                            PermissionState permissionState = origPermissions
10217                                    .getRuntimePermissionState(bp.name, userId);
10218                            int flags = permissionState != null
10219                                    ? permissionState.getFlags() : 0;
10220                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10221                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10222                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10223                                    // If we cannot put the permission as it was, we have to write.
10224                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10225                                            changedRuntimePermissionUserIds, userId);
10226                                }
10227                                // If the app supports runtime permissions no need for a review.
10228                                if (mPermissionReviewRequired
10229                                        && appSupportsRuntimePermissions
10230                                        && (flags & PackageManager
10231                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10232                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10233                                    // Since we changed the flags, we have to write.
10234                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10235                                            changedRuntimePermissionUserIds, userId);
10236                                }
10237                            } else if (mPermissionReviewRequired
10238                                    && !appSupportsRuntimePermissions) {
10239                                // For legacy apps that need a permission review, every new
10240                                // runtime permission is granted but it is pending a review.
10241                                // We also need to review only platform defined runtime
10242                                // permissions as these are the only ones the platform knows
10243                                // how to disable the API to simulate revocation as legacy
10244                                // apps don't expect to run with revoked permissions.
10245                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10246                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10247                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10248                                        // We changed the flags, hence have to write.
10249                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10250                                                changedRuntimePermissionUserIds, userId);
10251                                    }
10252                                }
10253                                if (permissionsState.grantRuntimePermission(bp, userId)
10254                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10255                                    // We changed the permission, hence have to write.
10256                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10257                                            changedRuntimePermissionUserIds, userId);
10258                                }
10259                            }
10260                            // Propagate the permission flags.
10261                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10262                        }
10263                    } break;
10264
10265                    case GRANT_UPGRADE: {
10266                        // Grant runtime permissions for a previously held install permission.
10267                        PermissionState permissionState = origPermissions
10268                                .getInstallPermissionState(bp.name);
10269                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10270
10271                        if (origPermissions.revokeInstallPermission(bp)
10272                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10273                            // We will be transferring the permission flags, so clear them.
10274                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10275                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10276                            changedInstallPermission = true;
10277                        }
10278
10279                        // If the permission is not to be promoted to runtime we ignore it and
10280                        // also its other flags as they are not applicable to install permissions.
10281                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10282                            for (int userId : currentUserIds) {
10283                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10284                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10285                                    // Transfer the permission flags.
10286                                    permissionsState.updatePermissionFlags(bp, userId,
10287                                            flags, flags);
10288                                    // If we granted the permission, we have to write.
10289                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10290                                            changedRuntimePermissionUserIds, userId);
10291                                }
10292                            }
10293                        }
10294                    } break;
10295
10296                    default: {
10297                        if (packageOfInterest == null
10298                                || packageOfInterest.equals(pkg.packageName)) {
10299                            Slog.w(TAG, "Not granting permission " + perm
10300                                    + " to package " + pkg.packageName
10301                                    + " because it was previously installed without");
10302                        }
10303                    } break;
10304                }
10305            } else {
10306                if (permissionsState.revokeInstallPermission(bp) !=
10307                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10308                    // Also drop the permission flags.
10309                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10310                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10311                    changedInstallPermission = true;
10312                    Slog.i(TAG, "Un-granting permission " + perm
10313                            + " from package " + pkg.packageName
10314                            + " (protectionLevel=" + bp.protectionLevel
10315                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10316                            + ")");
10317                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10318                    // Don't print warning for app op permissions, since it is fine for them
10319                    // not to be granted, there is a UI for the user to decide.
10320                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10321                        Slog.w(TAG, "Not granting permission " + perm
10322                                + " to package " + pkg.packageName
10323                                + " (protectionLevel=" + bp.protectionLevel
10324                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10325                                + ")");
10326                    }
10327                }
10328            }
10329        }
10330
10331        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10332                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10333            // This is the first that we have heard about this package, so the
10334            // permissions we have now selected are fixed until explicitly
10335            // changed.
10336            ps.installPermissionsFixed = true;
10337        }
10338
10339        // Persist the runtime permissions state for users with changes. If permissions
10340        // were revoked because no app in the shared user declares them we have to
10341        // write synchronously to avoid losing runtime permissions state.
10342        for (int userId : changedRuntimePermissionUserIds) {
10343            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10344        }
10345    }
10346
10347    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10348        boolean allowed = false;
10349        final int NP = PackageParser.NEW_PERMISSIONS.length;
10350        for (int ip=0; ip<NP; ip++) {
10351            final PackageParser.NewPermissionInfo npi
10352                    = PackageParser.NEW_PERMISSIONS[ip];
10353            if (npi.name.equals(perm)
10354                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10355                allowed = true;
10356                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10357                        + pkg.packageName);
10358                break;
10359            }
10360        }
10361        return allowed;
10362    }
10363
10364    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10365            BasePermission bp, PermissionsState origPermissions) {
10366        boolean privilegedPermission = (bp.protectionLevel
10367                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10368        boolean controlPrivappPermissions = RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS;
10369        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10370        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10371        if (controlPrivappPermissions && privilegedPermission && pkg.isPrivilegedApp()
10372                && !platformPackage && platformPermission) {
10373            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10374                    .getPrivAppPermissions(pkg.packageName);
10375            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10376            if (!whitelisted) {
10377                // Log for now. TODO Enforce permissions
10378                Slog.w(TAG, "Privileged permission " + perm + " for package "
10379                        + pkg.packageName + " - not in privapp-permissions whitelist");
10380            }
10381        }
10382        boolean allowed = (compareSignatures(
10383                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10384                        == PackageManager.SIGNATURE_MATCH)
10385                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10386                        == PackageManager.SIGNATURE_MATCH);
10387        if (!allowed && privilegedPermission) {
10388            if (isSystemApp(pkg)) {
10389                // For updated system applications, a system permission
10390                // is granted only if it had been defined by the original application.
10391                if (pkg.isUpdatedSystemApp()) {
10392                    final PackageSetting sysPs = mSettings
10393                            .getDisabledSystemPkgLPr(pkg.packageName);
10394                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10395                        // If the original was granted this permission, we take
10396                        // that grant decision as read and propagate it to the
10397                        // update.
10398                        if (sysPs.isPrivileged()) {
10399                            allowed = true;
10400                        }
10401                    } else {
10402                        // The system apk may have been updated with an older
10403                        // version of the one on the data partition, but which
10404                        // granted a new system permission that it didn't have
10405                        // before.  In this case we do want to allow the app to
10406                        // now get the new permission if the ancestral apk is
10407                        // privileged to get it.
10408                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10409                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10410                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10411                                    allowed = true;
10412                                    break;
10413                                }
10414                            }
10415                        }
10416                        // Also if a privileged parent package on the system image or any of
10417                        // its children requested a privileged permission, the updated child
10418                        // packages can also get the permission.
10419                        if (pkg.parentPackage != null) {
10420                            final PackageSetting disabledSysParentPs = mSettings
10421                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10422                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10423                                    && disabledSysParentPs.isPrivileged()) {
10424                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10425                                    allowed = true;
10426                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10427                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10428                                    for (int i = 0; i < count; i++) {
10429                                        PackageParser.Package disabledSysChildPkg =
10430                                                disabledSysParentPs.pkg.childPackages.get(i);
10431                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10432                                                perm)) {
10433                                            allowed = true;
10434                                            break;
10435                                        }
10436                                    }
10437                                }
10438                            }
10439                        }
10440                    }
10441                } else {
10442                    allowed = isPrivilegedApp(pkg);
10443                }
10444            }
10445        }
10446        if (!allowed) {
10447            if (!allowed && (bp.protectionLevel
10448                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10449                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10450                // If this was a previously normal/dangerous permission that got moved
10451                // to a system permission as part of the runtime permission redesign, then
10452                // we still want to blindly grant it to old apps.
10453                allowed = true;
10454            }
10455            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10456                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10457                // If this permission is to be granted to the system installer and
10458                // this app is an installer, then it gets the permission.
10459                allowed = true;
10460            }
10461            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10462                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10463                // If this permission is to be granted to the system verifier and
10464                // this app is a verifier, then it gets the permission.
10465                allowed = true;
10466            }
10467            if (!allowed && (bp.protectionLevel
10468                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10469                    && isSystemApp(pkg)) {
10470                // Any pre-installed system app is allowed to get this permission.
10471                allowed = true;
10472            }
10473            if (!allowed && (bp.protectionLevel
10474                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10475                // For development permissions, a development permission
10476                // is granted only if it was already granted.
10477                allowed = origPermissions.hasInstallPermission(perm);
10478            }
10479            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10480                    && pkg.packageName.equals(mSetupWizardPackage)) {
10481                // If this permission is to be granted to the system setup wizard and
10482                // this app is a setup wizard, then it gets the permission.
10483                allowed = true;
10484            }
10485        }
10486        return allowed;
10487    }
10488
10489    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10490        final int permCount = pkg.requestedPermissions.size();
10491        for (int j = 0; j < permCount; j++) {
10492            String requestedPermission = pkg.requestedPermissions.get(j);
10493            if (permission.equals(requestedPermission)) {
10494                return true;
10495            }
10496        }
10497        return false;
10498    }
10499
10500    final class ActivityIntentResolver
10501            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10502        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10503                boolean defaultOnly, int userId) {
10504            if (!sUserManager.exists(userId)) return null;
10505            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10506            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10507        }
10508
10509        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10510                int userId) {
10511            if (!sUserManager.exists(userId)) return null;
10512            mFlags = flags;
10513            return super.queryIntent(intent, resolvedType,
10514                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10515        }
10516
10517        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10518                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10519            if (!sUserManager.exists(userId)) return null;
10520            if (packageActivities == null) {
10521                return null;
10522            }
10523            mFlags = flags;
10524            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10525            final int N = packageActivities.size();
10526            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10527                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10528
10529            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10530            for (int i = 0; i < N; ++i) {
10531                intentFilters = packageActivities.get(i).intents;
10532                if (intentFilters != null && intentFilters.size() > 0) {
10533                    PackageParser.ActivityIntentInfo[] array =
10534                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10535                    intentFilters.toArray(array);
10536                    listCut.add(array);
10537                }
10538            }
10539            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10540        }
10541
10542        /**
10543         * Finds a privileged activity that matches the specified activity names.
10544         */
10545        private PackageParser.Activity findMatchingActivity(
10546                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10547            for (PackageParser.Activity sysActivity : activityList) {
10548                if (sysActivity.info.name.equals(activityInfo.name)) {
10549                    return sysActivity;
10550                }
10551                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10552                    return sysActivity;
10553                }
10554                if (sysActivity.info.targetActivity != null) {
10555                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10556                        return sysActivity;
10557                    }
10558                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10559                        return sysActivity;
10560                    }
10561                }
10562            }
10563            return null;
10564        }
10565
10566        public class IterGenerator<E> {
10567            public Iterator<E> generate(ActivityIntentInfo info) {
10568                return null;
10569            }
10570        }
10571
10572        public class ActionIterGenerator extends IterGenerator<String> {
10573            @Override
10574            public Iterator<String> generate(ActivityIntentInfo info) {
10575                return info.actionsIterator();
10576            }
10577        }
10578
10579        public class CategoriesIterGenerator extends IterGenerator<String> {
10580            @Override
10581            public Iterator<String> generate(ActivityIntentInfo info) {
10582                return info.categoriesIterator();
10583            }
10584        }
10585
10586        public class SchemesIterGenerator extends IterGenerator<String> {
10587            @Override
10588            public Iterator<String> generate(ActivityIntentInfo info) {
10589                return info.schemesIterator();
10590            }
10591        }
10592
10593        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10594            @Override
10595            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10596                return info.authoritiesIterator();
10597            }
10598        }
10599
10600        /**
10601         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10602         * MODIFIED. Do not pass in a list that should not be changed.
10603         */
10604        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10605                IterGenerator<T> generator, Iterator<T> searchIterator) {
10606            // loop through the set of actions; every one must be found in the intent filter
10607            while (searchIterator.hasNext()) {
10608                // we must have at least one filter in the list to consider a match
10609                if (intentList.size() == 0) {
10610                    break;
10611                }
10612
10613                final T searchAction = searchIterator.next();
10614
10615                // loop through the set of intent filters
10616                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10617                while (intentIter.hasNext()) {
10618                    final ActivityIntentInfo intentInfo = intentIter.next();
10619                    boolean selectionFound = false;
10620
10621                    // loop through the intent filter's selection criteria; at least one
10622                    // of them must match the searched criteria
10623                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10624                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10625                        final T intentSelection = intentSelectionIter.next();
10626                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10627                            selectionFound = true;
10628                            break;
10629                        }
10630                    }
10631
10632                    // the selection criteria wasn't found in this filter's set; this filter
10633                    // is not a potential match
10634                    if (!selectionFound) {
10635                        intentIter.remove();
10636                    }
10637                }
10638            }
10639        }
10640
10641        private boolean isProtectedAction(ActivityIntentInfo filter) {
10642            final Iterator<String> actionsIter = filter.actionsIterator();
10643            while (actionsIter != null && actionsIter.hasNext()) {
10644                final String filterAction = actionsIter.next();
10645                if (PROTECTED_ACTIONS.contains(filterAction)) {
10646                    return true;
10647                }
10648            }
10649            return false;
10650        }
10651
10652        /**
10653         * Adjusts the priority of the given intent filter according to policy.
10654         * <p>
10655         * <ul>
10656         * <li>The priority for non privileged applications is capped to '0'</li>
10657         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10658         * <li>The priority for unbundled updates to privileged applications is capped to the
10659         *      priority defined on the system partition</li>
10660         * </ul>
10661         * <p>
10662         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10663         * allowed to obtain any priority on any action.
10664         */
10665        private void adjustPriority(
10666                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10667            // nothing to do; priority is fine as-is
10668            if (intent.getPriority() <= 0) {
10669                return;
10670            }
10671
10672            final ActivityInfo activityInfo = intent.activity.info;
10673            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10674
10675            final boolean privilegedApp =
10676                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10677            if (!privilegedApp) {
10678                // non-privileged applications can never define a priority >0
10679                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10680                        + " package: " + applicationInfo.packageName
10681                        + " activity: " + intent.activity.className
10682                        + " origPrio: " + intent.getPriority());
10683                intent.setPriority(0);
10684                return;
10685            }
10686
10687            if (systemActivities == null) {
10688                // the system package is not disabled; we're parsing the system partition
10689                if (isProtectedAction(intent)) {
10690                    if (mDeferProtectedFilters) {
10691                        // We can't deal with these just yet. No component should ever obtain a
10692                        // >0 priority for a protected actions, with ONE exception -- the setup
10693                        // wizard. The setup wizard, however, cannot be known until we're able to
10694                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10695                        // until all intent filters have been processed. Chicken, meet egg.
10696                        // Let the filter temporarily have a high priority and rectify the
10697                        // priorities after all system packages have been scanned.
10698                        mProtectedFilters.add(intent);
10699                        if (DEBUG_FILTERS) {
10700                            Slog.i(TAG, "Protected action; save for later;"
10701                                    + " package: " + applicationInfo.packageName
10702                                    + " activity: " + intent.activity.className
10703                                    + " origPrio: " + intent.getPriority());
10704                        }
10705                        return;
10706                    } else {
10707                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10708                            Slog.i(TAG, "No setup wizard;"
10709                                + " All protected intents capped to priority 0");
10710                        }
10711                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10712                            if (DEBUG_FILTERS) {
10713                                Slog.i(TAG, "Found setup wizard;"
10714                                    + " allow priority " + intent.getPriority() + ";"
10715                                    + " package: " + intent.activity.info.packageName
10716                                    + " activity: " + intent.activity.className
10717                                    + " priority: " + intent.getPriority());
10718                            }
10719                            // setup wizard gets whatever it wants
10720                            return;
10721                        }
10722                        Slog.w(TAG, "Protected action; cap priority to 0;"
10723                                + " package: " + intent.activity.info.packageName
10724                                + " activity: " + intent.activity.className
10725                                + " origPrio: " + intent.getPriority());
10726                        intent.setPriority(0);
10727                        return;
10728                    }
10729                }
10730                // privileged apps on the system image get whatever priority they request
10731                return;
10732            }
10733
10734            // privileged app unbundled update ... try to find the same activity
10735            final PackageParser.Activity foundActivity =
10736                    findMatchingActivity(systemActivities, activityInfo);
10737            if (foundActivity == null) {
10738                // this is a new activity; it cannot obtain >0 priority
10739                if (DEBUG_FILTERS) {
10740                    Slog.i(TAG, "New activity; cap priority to 0;"
10741                            + " package: " + applicationInfo.packageName
10742                            + " activity: " + intent.activity.className
10743                            + " origPrio: " + intent.getPriority());
10744                }
10745                intent.setPriority(0);
10746                return;
10747            }
10748
10749            // found activity, now check for filter equivalence
10750
10751            // a shallow copy is enough; we modify the list, not its contents
10752            final List<ActivityIntentInfo> intentListCopy =
10753                    new ArrayList<>(foundActivity.intents);
10754            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10755
10756            // find matching action subsets
10757            final Iterator<String> actionsIterator = intent.actionsIterator();
10758            if (actionsIterator != null) {
10759                getIntentListSubset(
10760                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10761                if (intentListCopy.size() == 0) {
10762                    // no more intents to match; we're not equivalent
10763                    if (DEBUG_FILTERS) {
10764                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10765                                + " package: " + applicationInfo.packageName
10766                                + " activity: " + intent.activity.className
10767                                + " origPrio: " + intent.getPriority());
10768                    }
10769                    intent.setPriority(0);
10770                    return;
10771                }
10772            }
10773
10774            // find matching category subsets
10775            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10776            if (categoriesIterator != null) {
10777                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10778                        categoriesIterator);
10779                if (intentListCopy.size() == 0) {
10780                    // no more intents to match; we're not equivalent
10781                    if (DEBUG_FILTERS) {
10782                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10783                                + " package: " + applicationInfo.packageName
10784                                + " activity: " + intent.activity.className
10785                                + " origPrio: " + intent.getPriority());
10786                    }
10787                    intent.setPriority(0);
10788                    return;
10789                }
10790            }
10791
10792            // find matching schemes subsets
10793            final Iterator<String> schemesIterator = intent.schemesIterator();
10794            if (schemesIterator != null) {
10795                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10796                        schemesIterator);
10797                if (intentListCopy.size() == 0) {
10798                    // no more intents to match; we're not equivalent
10799                    if (DEBUG_FILTERS) {
10800                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10801                                + " package: " + applicationInfo.packageName
10802                                + " activity: " + intent.activity.className
10803                                + " origPrio: " + intent.getPriority());
10804                    }
10805                    intent.setPriority(0);
10806                    return;
10807                }
10808            }
10809
10810            // find matching authorities subsets
10811            final Iterator<IntentFilter.AuthorityEntry>
10812                    authoritiesIterator = intent.authoritiesIterator();
10813            if (authoritiesIterator != null) {
10814                getIntentListSubset(intentListCopy,
10815                        new AuthoritiesIterGenerator(),
10816                        authoritiesIterator);
10817                if (intentListCopy.size() == 0) {
10818                    // no more intents to match; we're not equivalent
10819                    if (DEBUG_FILTERS) {
10820                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10821                                + " package: " + applicationInfo.packageName
10822                                + " activity: " + intent.activity.className
10823                                + " origPrio: " + intent.getPriority());
10824                    }
10825                    intent.setPriority(0);
10826                    return;
10827                }
10828            }
10829
10830            // we found matching filter(s); app gets the max priority of all intents
10831            int cappedPriority = 0;
10832            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10833                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10834            }
10835            if (intent.getPriority() > cappedPriority) {
10836                if (DEBUG_FILTERS) {
10837                    Slog.i(TAG, "Found matching filter(s);"
10838                            + " cap priority to " + cappedPriority + ";"
10839                            + " package: " + applicationInfo.packageName
10840                            + " activity: " + intent.activity.className
10841                            + " origPrio: " + intent.getPriority());
10842                }
10843                intent.setPriority(cappedPriority);
10844                return;
10845            }
10846            // all this for nothing; the requested priority was <= what was on the system
10847        }
10848
10849        public final void addActivity(PackageParser.Activity a, String type) {
10850            mActivities.put(a.getComponentName(), a);
10851            if (DEBUG_SHOW_INFO)
10852                Log.v(
10853                TAG, "  " + type + " " +
10854                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10855            if (DEBUG_SHOW_INFO)
10856                Log.v(TAG, "    Class=" + a.info.name);
10857            final int NI = a.intents.size();
10858            for (int j=0; j<NI; j++) {
10859                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10860                if ("activity".equals(type)) {
10861                    final PackageSetting ps =
10862                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10863                    final List<PackageParser.Activity> systemActivities =
10864                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10865                    adjustPriority(systemActivities, intent);
10866                }
10867                if (DEBUG_SHOW_INFO) {
10868                    Log.v(TAG, "    IntentFilter:");
10869                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10870                }
10871                if (!intent.debugCheck()) {
10872                    Log.w(TAG, "==> For Activity " + a.info.name);
10873                }
10874                addFilter(intent);
10875            }
10876        }
10877
10878        public final void removeActivity(PackageParser.Activity a, String type) {
10879            mActivities.remove(a.getComponentName());
10880            if (DEBUG_SHOW_INFO) {
10881                Log.v(TAG, "  " + type + " "
10882                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10883                                : a.info.name) + ":");
10884                Log.v(TAG, "    Class=" + a.info.name);
10885            }
10886            final int NI = a.intents.size();
10887            for (int j=0; j<NI; j++) {
10888                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10889                if (DEBUG_SHOW_INFO) {
10890                    Log.v(TAG, "    IntentFilter:");
10891                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10892                }
10893                removeFilter(intent);
10894            }
10895        }
10896
10897        @Override
10898        protected boolean allowFilterResult(
10899                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10900            ActivityInfo filterAi = filter.activity.info;
10901            for (int i=dest.size()-1; i>=0; i--) {
10902                ActivityInfo destAi = dest.get(i).activityInfo;
10903                if (destAi.name == filterAi.name
10904                        && destAi.packageName == filterAi.packageName) {
10905                    return false;
10906                }
10907            }
10908            return true;
10909        }
10910
10911        @Override
10912        protected ActivityIntentInfo[] newArray(int size) {
10913            return new ActivityIntentInfo[size];
10914        }
10915
10916        @Override
10917        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10918            if (!sUserManager.exists(userId)) return true;
10919            PackageParser.Package p = filter.activity.owner;
10920            if (p != null) {
10921                PackageSetting ps = (PackageSetting)p.mExtras;
10922                if (ps != null) {
10923                    // System apps are never considered stopped for purposes of
10924                    // filtering, because there may be no way for the user to
10925                    // actually re-launch them.
10926                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10927                            && ps.getStopped(userId);
10928                }
10929            }
10930            return false;
10931        }
10932
10933        @Override
10934        protected boolean isPackageForFilter(String packageName,
10935                PackageParser.ActivityIntentInfo info) {
10936            return packageName.equals(info.activity.owner.packageName);
10937        }
10938
10939        @Override
10940        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10941                int match, int userId) {
10942            if (!sUserManager.exists(userId)) return null;
10943            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10944                return null;
10945            }
10946            final PackageParser.Activity activity = info.activity;
10947            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10948            if (ps == null) {
10949                return null;
10950            }
10951            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10952                    ps.readUserState(userId), userId);
10953            if (ai == null) {
10954                return null;
10955            }
10956            final ResolveInfo res = new ResolveInfo();
10957            res.activityInfo = ai;
10958            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10959                res.filter = info;
10960            }
10961            if (info != null) {
10962                res.handleAllWebDataURI = info.handleAllWebDataURI();
10963            }
10964            res.priority = info.getPriority();
10965            res.preferredOrder = activity.owner.mPreferredOrder;
10966            //System.out.println("Result: " + res.activityInfo.className +
10967            //                   " = " + res.priority);
10968            res.match = match;
10969            res.isDefault = info.hasDefault;
10970            res.labelRes = info.labelRes;
10971            res.nonLocalizedLabel = info.nonLocalizedLabel;
10972            if (userNeedsBadging(userId)) {
10973                res.noResourceId = true;
10974            } else {
10975                res.icon = info.icon;
10976            }
10977            res.iconResourceId = info.icon;
10978            res.system = res.activityInfo.applicationInfo.isSystemApp();
10979            return res;
10980        }
10981
10982        @Override
10983        protected void sortResults(List<ResolveInfo> results) {
10984            Collections.sort(results, mResolvePrioritySorter);
10985        }
10986
10987        @Override
10988        protected void dumpFilter(PrintWriter out, String prefix,
10989                PackageParser.ActivityIntentInfo filter) {
10990            out.print(prefix); out.print(
10991                    Integer.toHexString(System.identityHashCode(filter.activity)));
10992                    out.print(' ');
10993                    filter.activity.printComponentShortName(out);
10994                    out.print(" filter ");
10995                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10996        }
10997
10998        @Override
10999        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11000            return filter.activity;
11001        }
11002
11003        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11004            PackageParser.Activity activity = (PackageParser.Activity)label;
11005            out.print(prefix); out.print(
11006                    Integer.toHexString(System.identityHashCode(activity)));
11007                    out.print(' ');
11008                    activity.printComponentShortName(out);
11009            if (count > 1) {
11010                out.print(" ("); out.print(count); out.print(" filters)");
11011            }
11012            out.println();
11013        }
11014
11015        // Keys are String (activity class name), values are Activity.
11016        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11017                = new ArrayMap<ComponentName, PackageParser.Activity>();
11018        private int mFlags;
11019    }
11020
11021    private final class ServiceIntentResolver
11022            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11023        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11024                boolean defaultOnly, int userId) {
11025            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11026            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11027        }
11028
11029        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11030                int userId) {
11031            if (!sUserManager.exists(userId)) return null;
11032            mFlags = flags;
11033            return super.queryIntent(intent, resolvedType,
11034                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11035        }
11036
11037        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11038                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11039            if (!sUserManager.exists(userId)) return null;
11040            if (packageServices == null) {
11041                return null;
11042            }
11043            mFlags = flags;
11044            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11045            final int N = packageServices.size();
11046            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11047                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11048
11049            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11050            for (int i = 0; i < N; ++i) {
11051                intentFilters = packageServices.get(i).intents;
11052                if (intentFilters != null && intentFilters.size() > 0) {
11053                    PackageParser.ServiceIntentInfo[] array =
11054                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11055                    intentFilters.toArray(array);
11056                    listCut.add(array);
11057                }
11058            }
11059            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11060        }
11061
11062        public final void addService(PackageParser.Service s) {
11063            mServices.put(s.getComponentName(), s);
11064            if (DEBUG_SHOW_INFO) {
11065                Log.v(TAG, "  "
11066                        + (s.info.nonLocalizedLabel != null
11067                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11068                Log.v(TAG, "    Class=" + s.info.name);
11069            }
11070            final int NI = s.intents.size();
11071            int j;
11072            for (j=0; j<NI; j++) {
11073                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11074                if (DEBUG_SHOW_INFO) {
11075                    Log.v(TAG, "    IntentFilter:");
11076                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11077                }
11078                if (!intent.debugCheck()) {
11079                    Log.w(TAG, "==> For Service " + s.info.name);
11080                }
11081                addFilter(intent);
11082            }
11083        }
11084
11085        public final void removeService(PackageParser.Service s) {
11086            mServices.remove(s.getComponentName());
11087            if (DEBUG_SHOW_INFO) {
11088                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11089                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11090                Log.v(TAG, "    Class=" + s.info.name);
11091            }
11092            final int NI = s.intents.size();
11093            int j;
11094            for (j=0; j<NI; j++) {
11095                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11096                if (DEBUG_SHOW_INFO) {
11097                    Log.v(TAG, "    IntentFilter:");
11098                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11099                }
11100                removeFilter(intent);
11101            }
11102        }
11103
11104        @Override
11105        protected boolean allowFilterResult(
11106                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11107            ServiceInfo filterSi = filter.service.info;
11108            for (int i=dest.size()-1; i>=0; i--) {
11109                ServiceInfo destAi = dest.get(i).serviceInfo;
11110                if (destAi.name == filterSi.name
11111                        && destAi.packageName == filterSi.packageName) {
11112                    return false;
11113                }
11114            }
11115            return true;
11116        }
11117
11118        @Override
11119        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11120            return new PackageParser.ServiceIntentInfo[size];
11121        }
11122
11123        @Override
11124        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11125            if (!sUserManager.exists(userId)) return true;
11126            PackageParser.Package p = filter.service.owner;
11127            if (p != null) {
11128                PackageSetting ps = (PackageSetting)p.mExtras;
11129                if (ps != null) {
11130                    // System apps are never considered stopped for purposes of
11131                    // filtering, because there may be no way for the user to
11132                    // actually re-launch them.
11133                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11134                            && ps.getStopped(userId);
11135                }
11136            }
11137            return false;
11138        }
11139
11140        @Override
11141        protected boolean isPackageForFilter(String packageName,
11142                PackageParser.ServiceIntentInfo info) {
11143            return packageName.equals(info.service.owner.packageName);
11144        }
11145
11146        @Override
11147        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11148                int match, int userId) {
11149            if (!sUserManager.exists(userId)) return null;
11150            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11151            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11152                return null;
11153            }
11154            final PackageParser.Service service = info.service;
11155            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11156            if (ps == null) {
11157                return null;
11158            }
11159            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11160                    ps.readUserState(userId), userId);
11161            if (si == null) {
11162                return null;
11163            }
11164            final ResolveInfo res = new ResolveInfo();
11165            res.serviceInfo = si;
11166            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11167                res.filter = filter;
11168            }
11169            res.priority = info.getPriority();
11170            res.preferredOrder = service.owner.mPreferredOrder;
11171            res.match = match;
11172            res.isDefault = info.hasDefault;
11173            res.labelRes = info.labelRes;
11174            res.nonLocalizedLabel = info.nonLocalizedLabel;
11175            res.icon = info.icon;
11176            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11177            return res;
11178        }
11179
11180        @Override
11181        protected void sortResults(List<ResolveInfo> results) {
11182            Collections.sort(results, mResolvePrioritySorter);
11183        }
11184
11185        @Override
11186        protected void dumpFilter(PrintWriter out, String prefix,
11187                PackageParser.ServiceIntentInfo filter) {
11188            out.print(prefix); out.print(
11189                    Integer.toHexString(System.identityHashCode(filter.service)));
11190                    out.print(' ');
11191                    filter.service.printComponentShortName(out);
11192                    out.print(" filter ");
11193                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11194        }
11195
11196        @Override
11197        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11198            return filter.service;
11199        }
11200
11201        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11202            PackageParser.Service service = (PackageParser.Service)label;
11203            out.print(prefix); out.print(
11204                    Integer.toHexString(System.identityHashCode(service)));
11205                    out.print(' ');
11206                    service.printComponentShortName(out);
11207            if (count > 1) {
11208                out.print(" ("); out.print(count); out.print(" filters)");
11209            }
11210            out.println();
11211        }
11212
11213//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11214//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11215//            final List<ResolveInfo> retList = Lists.newArrayList();
11216//            while (i.hasNext()) {
11217//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11218//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11219//                    retList.add(resolveInfo);
11220//                }
11221//            }
11222//            return retList;
11223//        }
11224
11225        // Keys are String (activity class name), values are Activity.
11226        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11227                = new ArrayMap<ComponentName, PackageParser.Service>();
11228        private int mFlags;
11229    };
11230
11231    private final class ProviderIntentResolver
11232            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11233        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11234                boolean defaultOnly, int userId) {
11235            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11236            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11237        }
11238
11239        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11240                int userId) {
11241            if (!sUserManager.exists(userId))
11242                return null;
11243            mFlags = flags;
11244            return super.queryIntent(intent, resolvedType,
11245                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11246        }
11247
11248        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11249                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11250            if (!sUserManager.exists(userId))
11251                return null;
11252            if (packageProviders == null) {
11253                return null;
11254            }
11255            mFlags = flags;
11256            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11257            final int N = packageProviders.size();
11258            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11259                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11260
11261            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11262            for (int i = 0; i < N; ++i) {
11263                intentFilters = packageProviders.get(i).intents;
11264                if (intentFilters != null && intentFilters.size() > 0) {
11265                    PackageParser.ProviderIntentInfo[] array =
11266                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11267                    intentFilters.toArray(array);
11268                    listCut.add(array);
11269                }
11270            }
11271            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11272        }
11273
11274        public final void addProvider(PackageParser.Provider p) {
11275            if (mProviders.containsKey(p.getComponentName())) {
11276                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11277                return;
11278            }
11279
11280            mProviders.put(p.getComponentName(), p);
11281            if (DEBUG_SHOW_INFO) {
11282                Log.v(TAG, "  "
11283                        + (p.info.nonLocalizedLabel != null
11284                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11285                Log.v(TAG, "    Class=" + p.info.name);
11286            }
11287            final int NI = p.intents.size();
11288            int j;
11289            for (j = 0; j < NI; j++) {
11290                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11291                if (DEBUG_SHOW_INFO) {
11292                    Log.v(TAG, "    IntentFilter:");
11293                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11294                }
11295                if (!intent.debugCheck()) {
11296                    Log.w(TAG, "==> For Provider " + p.info.name);
11297                }
11298                addFilter(intent);
11299            }
11300        }
11301
11302        public final void removeProvider(PackageParser.Provider p) {
11303            mProviders.remove(p.getComponentName());
11304            if (DEBUG_SHOW_INFO) {
11305                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11306                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11307                Log.v(TAG, "    Class=" + p.info.name);
11308            }
11309            final int NI = p.intents.size();
11310            int j;
11311            for (j = 0; j < NI; j++) {
11312                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11313                if (DEBUG_SHOW_INFO) {
11314                    Log.v(TAG, "    IntentFilter:");
11315                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11316                }
11317                removeFilter(intent);
11318            }
11319        }
11320
11321        @Override
11322        protected boolean allowFilterResult(
11323                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11324            ProviderInfo filterPi = filter.provider.info;
11325            for (int i = dest.size() - 1; i >= 0; i--) {
11326                ProviderInfo destPi = dest.get(i).providerInfo;
11327                if (destPi.name == filterPi.name
11328                        && destPi.packageName == filterPi.packageName) {
11329                    return false;
11330                }
11331            }
11332            return true;
11333        }
11334
11335        @Override
11336        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11337            return new PackageParser.ProviderIntentInfo[size];
11338        }
11339
11340        @Override
11341        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11342            if (!sUserManager.exists(userId))
11343                return true;
11344            PackageParser.Package p = filter.provider.owner;
11345            if (p != null) {
11346                PackageSetting ps = (PackageSetting) p.mExtras;
11347                if (ps != null) {
11348                    // System apps are never considered stopped for purposes of
11349                    // filtering, because there may be no way for the user to
11350                    // actually re-launch them.
11351                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11352                            && ps.getStopped(userId);
11353                }
11354            }
11355            return false;
11356        }
11357
11358        @Override
11359        protected boolean isPackageForFilter(String packageName,
11360                PackageParser.ProviderIntentInfo info) {
11361            return packageName.equals(info.provider.owner.packageName);
11362        }
11363
11364        @Override
11365        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11366                int match, int userId) {
11367            if (!sUserManager.exists(userId))
11368                return null;
11369            final PackageParser.ProviderIntentInfo info = filter;
11370            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11371                return null;
11372            }
11373            final PackageParser.Provider provider = info.provider;
11374            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11375            if (ps == null) {
11376                return null;
11377            }
11378            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11379                    ps.readUserState(userId), userId);
11380            if (pi == null) {
11381                return null;
11382            }
11383            final ResolveInfo res = new ResolveInfo();
11384            res.providerInfo = pi;
11385            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11386                res.filter = filter;
11387            }
11388            res.priority = info.getPriority();
11389            res.preferredOrder = provider.owner.mPreferredOrder;
11390            res.match = match;
11391            res.isDefault = info.hasDefault;
11392            res.labelRes = info.labelRes;
11393            res.nonLocalizedLabel = info.nonLocalizedLabel;
11394            res.icon = info.icon;
11395            res.system = res.providerInfo.applicationInfo.isSystemApp();
11396            return res;
11397        }
11398
11399        @Override
11400        protected void sortResults(List<ResolveInfo> results) {
11401            Collections.sort(results, mResolvePrioritySorter);
11402        }
11403
11404        @Override
11405        protected void dumpFilter(PrintWriter out, String prefix,
11406                PackageParser.ProviderIntentInfo filter) {
11407            out.print(prefix);
11408            out.print(
11409                    Integer.toHexString(System.identityHashCode(filter.provider)));
11410            out.print(' ');
11411            filter.provider.printComponentShortName(out);
11412            out.print(" filter ");
11413            out.println(Integer.toHexString(System.identityHashCode(filter)));
11414        }
11415
11416        @Override
11417        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11418            return filter.provider;
11419        }
11420
11421        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11422            PackageParser.Provider provider = (PackageParser.Provider)label;
11423            out.print(prefix); out.print(
11424                    Integer.toHexString(System.identityHashCode(provider)));
11425                    out.print(' ');
11426                    provider.printComponentShortName(out);
11427            if (count > 1) {
11428                out.print(" ("); out.print(count); out.print(" filters)");
11429            }
11430            out.println();
11431        }
11432
11433        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11434                = new ArrayMap<ComponentName, PackageParser.Provider>();
11435        private int mFlags;
11436    }
11437
11438    static final class EphemeralIntentResolver
11439            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11440        /**
11441         * The result that has the highest defined order. Ordering applies on a
11442         * per-package basis. Mapping is from package name to Pair of order and
11443         * EphemeralResolveInfo.
11444         * <p>
11445         * NOTE: This is implemented as a field variable for convenience and efficiency.
11446         * By having a field variable, we're able to track filter ordering as soon as
11447         * a non-zero order is defined. Otherwise, multiple loops across the result set
11448         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11449         * this needs to be contained entirely within {@link #filterResults()}.
11450         */
11451        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11452
11453        @Override
11454        protected EphemeralResponse[] newArray(int size) {
11455            return new EphemeralResponse[size];
11456        }
11457
11458        @Override
11459        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11460            return true;
11461        }
11462
11463        @Override
11464        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11465                int userId) {
11466            if (!sUserManager.exists(userId)) {
11467                return null;
11468            }
11469            final String packageName = responseObj.resolveInfo.getPackageName();
11470            final Integer order = responseObj.getOrder();
11471            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11472                    mOrderResult.get(packageName);
11473            // ordering is enabled and this item's order isn't high enough
11474            if (lastOrderResult != null && lastOrderResult.first >= order) {
11475                return null;
11476            }
11477            final EphemeralResolveInfo res = responseObj.resolveInfo;
11478            if (order > 0) {
11479                // non-zero order, enable ordering
11480                mOrderResult.put(packageName, new Pair<>(order, res));
11481            }
11482            return responseObj;
11483        }
11484
11485        @Override
11486        protected void filterResults(List<EphemeralResponse> results) {
11487            // only do work if ordering is enabled [most of the time it won't be]
11488            if (mOrderResult.size() == 0) {
11489                return;
11490            }
11491            int resultSize = results.size();
11492            for (int i = 0; i < resultSize; i++) {
11493                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11494                final String packageName = info.getPackageName();
11495                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11496                if (savedInfo == null) {
11497                    // package doesn't having ordering
11498                    continue;
11499                }
11500                if (savedInfo.second == info) {
11501                    // circled back to the highest ordered item; remove from order list
11502                    mOrderResult.remove(savedInfo);
11503                    if (mOrderResult.size() == 0) {
11504                        // no more ordered items
11505                        break;
11506                    }
11507                    continue;
11508                }
11509                // item has a worse order, remove it from the result list
11510                results.remove(i);
11511                resultSize--;
11512                i--;
11513            }
11514        }
11515    }
11516
11517    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11518            new Comparator<ResolveInfo>() {
11519        public int compare(ResolveInfo r1, ResolveInfo r2) {
11520            int v1 = r1.priority;
11521            int v2 = r2.priority;
11522            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11523            if (v1 != v2) {
11524                return (v1 > v2) ? -1 : 1;
11525            }
11526            v1 = r1.preferredOrder;
11527            v2 = r2.preferredOrder;
11528            if (v1 != v2) {
11529                return (v1 > v2) ? -1 : 1;
11530            }
11531            if (r1.isDefault != r2.isDefault) {
11532                return r1.isDefault ? -1 : 1;
11533            }
11534            v1 = r1.match;
11535            v2 = r2.match;
11536            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11537            if (v1 != v2) {
11538                return (v1 > v2) ? -1 : 1;
11539            }
11540            if (r1.system != r2.system) {
11541                return r1.system ? -1 : 1;
11542            }
11543            if (r1.activityInfo != null) {
11544                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11545            }
11546            if (r1.serviceInfo != null) {
11547                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11548            }
11549            if (r1.providerInfo != null) {
11550                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11551            }
11552            return 0;
11553        }
11554    };
11555
11556    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11557            new Comparator<ProviderInfo>() {
11558        public int compare(ProviderInfo p1, ProviderInfo p2) {
11559            final int v1 = p1.initOrder;
11560            final int v2 = p2.initOrder;
11561            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11562        }
11563    };
11564
11565    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11566            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11567            final int[] userIds) {
11568        mHandler.post(new Runnable() {
11569            @Override
11570            public void run() {
11571                try {
11572                    final IActivityManager am = ActivityManager.getService();
11573                    if (am == null) return;
11574                    final int[] resolvedUserIds;
11575                    if (userIds == null) {
11576                        resolvedUserIds = am.getRunningUserIds();
11577                    } else {
11578                        resolvedUserIds = userIds;
11579                    }
11580                    for (int id : resolvedUserIds) {
11581                        final Intent intent = new Intent(action,
11582                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11583                        if (extras != null) {
11584                            intent.putExtras(extras);
11585                        }
11586                        if (targetPkg != null) {
11587                            intent.setPackage(targetPkg);
11588                        }
11589                        // Modify the UID when posting to other users
11590                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11591                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11592                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11593                            intent.putExtra(Intent.EXTRA_UID, uid);
11594                        }
11595                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11596                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11597                        if (DEBUG_BROADCASTS) {
11598                            RuntimeException here = new RuntimeException("here");
11599                            here.fillInStackTrace();
11600                            Slog.d(TAG, "Sending to user " + id + ": "
11601                                    + intent.toShortString(false, true, false, false)
11602                                    + " " + intent.getExtras(), here);
11603                        }
11604                        am.broadcastIntent(null, intent, null, finishedReceiver,
11605                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11606                                null, finishedReceiver != null, false, id);
11607                    }
11608                } catch (RemoteException ex) {
11609                }
11610            }
11611        });
11612    }
11613
11614    /**
11615     * Check if the external storage media is available. This is true if there
11616     * is a mounted external storage medium or if the external storage is
11617     * emulated.
11618     */
11619    private boolean isExternalMediaAvailable() {
11620        return mMediaMounted || Environment.isExternalStorageEmulated();
11621    }
11622
11623    @Override
11624    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11625        // writer
11626        synchronized (mPackages) {
11627            if (!isExternalMediaAvailable()) {
11628                // If the external storage is no longer mounted at this point,
11629                // the caller may not have been able to delete all of this
11630                // packages files and can not delete any more.  Bail.
11631                return null;
11632            }
11633            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11634            if (lastPackage != null) {
11635                pkgs.remove(lastPackage);
11636            }
11637            if (pkgs.size() > 0) {
11638                return pkgs.get(0);
11639            }
11640        }
11641        return null;
11642    }
11643
11644    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11645        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11646                userId, andCode ? 1 : 0, packageName);
11647        if (mSystemReady) {
11648            msg.sendToTarget();
11649        } else {
11650            if (mPostSystemReadyMessages == null) {
11651                mPostSystemReadyMessages = new ArrayList<>();
11652            }
11653            mPostSystemReadyMessages.add(msg);
11654        }
11655    }
11656
11657    void startCleaningPackages() {
11658        // reader
11659        if (!isExternalMediaAvailable()) {
11660            return;
11661        }
11662        synchronized (mPackages) {
11663            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11664                return;
11665            }
11666        }
11667        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11668        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11669        IActivityManager am = ActivityManager.getService();
11670        if (am != null) {
11671            try {
11672                am.startService(null, intent, null, mContext.getOpPackageName(),
11673                        UserHandle.USER_SYSTEM);
11674            } catch (RemoteException e) {
11675            }
11676        }
11677    }
11678
11679    @Override
11680    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11681            int installFlags, String installerPackageName, int userId) {
11682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11683
11684        final int callingUid = Binder.getCallingUid();
11685        enforceCrossUserPermission(callingUid, userId,
11686                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11687
11688        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11689            try {
11690                if (observer != null) {
11691                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11692                }
11693            } catch (RemoteException re) {
11694            }
11695            return;
11696        }
11697
11698        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11699            installFlags |= PackageManager.INSTALL_FROM_ADB;
11700
11701        } else {
11702            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11703            // about installerPackageName.
11704
11705            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11706            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11707        }
11708
11709        UserHandle user;
11710        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11711            user = UserHandle.ALL;
11712        } else {
11713            user = new UserHandle(userId);
11714        }
11715
11716        // Only system components can circumvent runtime permissions when installing.
11717        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11718                && mContext.checkCallingOrSelfPermission(Manifest.permission
11719                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11720            throw new SecurityException("You need the "
11721                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11722                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11723        }
11724
11725        final File originFile = new File(originPath);
11726        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11727
11728        final Message msg = mHandler.obtainMessage(INIT_COPY);
11729        final VerificationInfo verificationInfo = new VerificationInfo(
11730                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11731        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11732                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11733                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11734                null /*certificates*/);
11735        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11736        msg.obj = params;
11737
11738        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11739                System.identityHashCode(msg.obj));
11740        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11741                System.identityHashCode(msg.obj));
11742
11743        mHandler.sendMessage(msg);
11744    }
11745
11746    void installStage(String packageName, File stagedDir, String stagedCid,
11747            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11748            String installerPackageName, int installerUid, UserHandle user,
11749            Certificate[][] certificates) {
11750        if (DEBUG_EPHEMERAL) {
11751            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11752                Slog.d(TAG, "Ephemeral install of " + packageName);
11753            }
11754        }
11755        final VerificationInfo verificationInfo = new VerificationInfo(
11756                sessionParams.originatingUri, sessionParams.referrerUri,
11757                sessionParams.originatingUid, installerUid);
11758
11759        final OriginInfo origin;
11760        if (stagedDir != null) {
11761            origin = OriginInfo.fromStagedFile(stagedDir);
11762        } else {
11763            origin = OriginInfo.fromStagedContainer(stagedCid);
11764        }
11765
11766        final Message msg = mHandler.obtainMessage(INIT_COPY);
11767        final InstallParams params = new InstallParams(origin, null, observer,
11768                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11769                verificationInfo, user, sessionParams.abiOverride,
11770                sessionParams.grantedRuntimePermissions, certificates);
11771        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11772        msg.obj = params;
11773
11774        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11775                System.identityHashCode(msg.obj));
11776        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11777                System.identityHashCode(msg.obj));
11778
11779        mHandler.sendMessage(msg);
11780    }
11781
11782    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11783            int userId) {
11784        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11785        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
11786    }
11787
11788    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
11789            int appId, int... userIds) {
11790        if (ArrayUtils.isEmpty(userIds)) {
11791            return;
11792        }
11793        Bundle extras = new Bundle(1);
11794        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
11795        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
11796
11797        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11798                packageName, extras, 0, null, null, userIds);
11799        if (isSystem) {
11800            mHandler.post(() -> {
11801                        for (int userId : userIds) {
11802                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
11803                        }
11804                    }
11805            );
11806        }
11807    }
11808
11809    /**
11810     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
11811     * automatically without needing an explicit launch.
11812     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
11813     */
11814    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
11815        // If user is not running, the app didn't miss any broadcast
11816        if (!mUserManagerInternal.isUserRunning(userId)) {
11817            return;
11818        }
11819        final IActivityManager am = ActivityManager.getService();
11820        try {
11821            // Deliver LOCKED_BOOT_COMPLETED first
11822            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
11823                    .setPackage(packageName);
11824            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
11825            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
11826                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11827
11828            // Deliver BOOT_COMPLETED only if user is unlocked
11829            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
11830                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
11831                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
11832                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11833            }
11834        } catch (RemoteException e) {
11835            throw e.rethrowFromSystemServer();
11836        }
11837    }
11838
11839    @Override
11840    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11841            int userId) {
11842        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11843        PackageSetting pkgSetting;
11844        final int uid = Binder.getCallingUid();
11845        enforceCrossUserPermission(uid, userId,
11846                true /* requireFullPermission */, true /* checkShell */,
11847                "setApplicationHiddenSetting for user " + userId);
11848
11849        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11850            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11851            return false;
11852        }
11853
11854        long callingId = Binder.clearCallingIdentity();
11855        try {
11856            boolean sendAdded = false;
11857            boolean sendRemoved = false;
11858            // writer
11859            synchronized (mPackages) {
11860                pkgSetting = mSettings.mPackages.get(packageName);
11861                if (pkgSetting == null) {
11862                    return false;
11863                }
11864                // Do not allow "android" is being disabled
11865                if ("android".equals(packageName)) {
11866                    Slog.w(TAG, "Cannot hide package: android");
11867                    return false;
11868                }
11869                // Only allow protected packages to hide themselves.
11870                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11871                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11872                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11873                    return false;
11874                }
11875
11876                if (pkgSetting.getHidden(userId) != hidden) {
11877                    pkgSetting.setHidden(hidden, userId);
11878                    mSettings.writePackageRestrictionsLPr(userId);
11879                    if (hidden) {
11880                        sendRemoved = true;
11881                    } else {
11882                        sendAdded = true;
11883                    }
11884                }
11885            }
11886            if (sendAdded) {
11887                sendPackageAddedForUser(packageName, pkgSetting, userId);
11888                return true;
11889            }
11890            if (sendRemoved) {
11891                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11892                        "hiding pkg");
11893                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11894                return true;
11895            }
11896        } finally {
11897            Binder.restoreCallingIdentity(callingId);
11898        }
11899        return false;
11900    }
11901
11902    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11903            int userId) {
11904        final PackageRemovedInfo info = new PackageRemovedInfo();
11905        info.removedPackage = packageName;
11906        info.removedUsers = new int[] {userId};
11907        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11908        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11909    }
11910
11911    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11912        if (pkgList.length > 0) {
11913            Bundle extras = new Bundle(1);
11914            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11915
11916            sendPackageBroadcast(
11917                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11918                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11919                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11920                    new int[] {userId});
11921        }
11922    }
11923
11924    /**
11925     * Returns true if application is not found or there was an error. Otherwise it returns
11926     * the hidden state of the package for the given user.
11927     */
11928    @Override
11929    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11930        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11931        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11932                true /* requireFullPermission */, false /* checkShell */,
11933                "getApplicationHidden for user " + userId);
11934        PackageSetting pkgSetting;
11935        long callingId = Binder.clearCallingIdentity();
11936        try {
11937            // writer
11938            synchronized (mPackages) {
11939                pkgSetting = mSettings.mPackages.get(packageName);
11940                if (pkgSetting == null) {
11941                    return true;
11942                }
11943                return pkgSetting.getHidden(userId);
11944            }
11945        } finally {
11946            Binder.restoreCallingIdentity(callingId);
11947        }
11948    }
11949
11950    /**
11951     * @hide
11952     */
11953    @Override
11954    public int installExistingPackageAsUser(String packageName, int userId) {
11955        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11956                null);
11957        PackageSetting pkgSetting;
11958        final int uid = Binder.getCallingUid();
11959        enforceCrossUserPermission(uid, userId,
11960                true /* requireFullPermission */, true /* checkShell */,
11961                "installExistingPackage for user " + userId);
11962        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11963            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11964        }
11965
11966        long callingId = Binder.clearCallingIdentity();
11967        try {
11968            boolean installed = false;
11969
11970            // writer
11971            synchronized (mPackages) {
11972                pkgSetting = mSettings.mPackages.get(packageName);
11973                if (pkgSetting == null) {
11974                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11975                }
11976                if (!pkgSetting.getInstalled(userId)) {
11977                    pkgSetting.setInstalled(true, userId);
11978                    pkgSetting.setHidden(false, userId);
11979                    mSettings.writePackageRestrictionsLPr(userId);
11980                    installed = true;
11981                }
11982            }
11983
11984            if (installed) {
11985                if (pkgSetting.pkg != null) {
11986                    synchronized (mInstallLock) {
11987                        // We don't need to freeze for a brand new install
11988                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11989                    }
11990                }
11991                sendPackageAddedForUser(packageName, pkgSetting, userId);
11992            }
11993        } finally {
11994            Binder.restoreCallingIdentity(callingId);
11995        }
11996
11997        return PackageManager.INSTALL_SUCCEEDED;
11998    }
11999
12000    boolean isUserRestricted(int userId, String restrictionKey) {
12001        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12002        if (restrictions.getBoolean(restrictionKey, false)) {
12003            Log.w(TAG, "User is restricted: " + restrictionKey);
12004            return true;
12005        }
12006        return false;
12007    }
12008
12009    @Override
12010    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12011            int userId) {
12012        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12013        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12014                true /* requireFullPermission */, true /* checkShell */,
12015                "setPackagesSuspended for user " + userId);
12016
12017        if (ArrayUtils.isEmpty(packageNames)) {
12018            return packageNames;
12019        }
12020
12021        // List of package names for whom the suspended state has changed.
12022        List<String> changedPackages = new ArrayList<>(packageNames.length);
12023        // List of package names for whom the suspended state is not set as requested in this
12024        // method.
12025        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12026        long callingId = Binder.clearCallingIdentity();
12027        try {
12028            for (int i = 0; i < packageNames.length; i++) {
12029                String packageName = packageNames[i];
12030                boolean changed = false;
12031                final int appId;
12032                synchronized (mPackages) {
12033                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12034                    if (pkgSetting == null) {
12035                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12036                                + "\". Skipping suspending/un-suspending.");
12037                        unactionedPackages.add(packageName);
12038                        continue;
12039                    }
12040                    appId = pkgSetting.appId;
12041                    if (pkgSetting.getSuspended(userId) != suspended) {
12042                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12043                            unactionedPackages.add(packageName);
12044                            continue;
12045                        }
12046                        pkgSetting.setSuspended(suspended, userId);
12047                        mSettings.writePackageRestrictionsLPr(userId);
12048                        changed = true;
12049                        changedPackages.add(packageName);
12050                    }
12051                }
12052
12053                if (changed && suspended) {
12054                    killApplication(packageName, UserHandle.getUid(userId, appId),
12055                            "suspending package");
12056                }
12057            }
12058        } finally {
12059            Binder.restoreCallingIdentity(callingId);
12060        }
12061
12062        if (!changedPackages.isEmpty()) {
12063            sendPackagesSuspendedForUser(changedPackages.toArray(
12064                    new String[changedPackages.size()]), userId, suspended);
12065        }
12066
12067        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12068    }
12069
12070    @Override
12071    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12072        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12073                true /* requireFullPermission */, false /* checkShell */,
12074                "isPackageSuspendedForUser for user " + userId);
12075        synchronized (mPackages) {
12076            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12077            if (pkgSetting == null) {
12078                throw new IllegalArgumentException("Unknown target package: " + packageName);
12079            }
12080            return pkgSetting.getSuspended(userId);
12081        }
12082    }
12083
12084    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12085        if (isPackageDeviceAdmin(packageName, userId)) {
12086            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12087                    + "\": has an active device admin");
12088            return false;
12089        }
12090
12091        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12092        if (packageName.equals(activeLauncherPackageName)) {
12093            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12094                    + "\": contains the active launcher");
12095            return false;
12096        }
12097
12098        if (packageName.equals(mRequiredInstallerPackage)) {
12099            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12100                    + "\": required for package installation");
12101            return false;
12102        }
12103
12104        if (packageName.equals(mRequiredUninstallerPackage)) {
12105            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12106                    + "\": required for package uninstallation");
12107            return false;
12108        }
12109
12110        if (packageName.equals(mRequiredVerifierPackage)) {
12111            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12112                    + "\": required for package verification");
12113            return false;
12114        }
12115
12116        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12117            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12118                    + "\": is the default dialer");
12119            return false;
12120        }
12121
12122        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12123            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12124                    + "\": protected package");
12125            return false;
12126        }
12127
12128        return true;
12129    }
12130
12131    private String getActiveLauncherPackageName(int userId) {
12132        Intent intent = new Intent(Intent.ACTION_MAIN);
12133        intent.addCategory(Intent.CATEGORY_HOME);
12134        ResolveInfo resolveInfo = resolveIntent(
12135                intent,
12136                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12137                PackageManager.MATCH_DEFAULT_ONLY,
12138                userId);
12139
12140        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12141    }
12142
12143    private String getDefaultDialerPackageName(int userId) {
12144        synchronized (mPackages) {
12145            return mSettings.getDefaultDialerPackageNameLPw(userId);
12146        }
12147    }
12148
12149    @Override
12150    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12151        mContext.enforceCallingOrSelfPermission(
12152                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12153                "Only package verification agents can verify applications");
12154
12155        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12156        final PackageVerificationResponse response = new PackageVerificationResponse(
12157                verificationCode, Binder.getCallingUid());
12158        msg.arg1 = id;
12159        msg.obj = response;
12160        mHandler.sendMessage(msg);
12161    }
12162
12163    @Override
12164    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12165            long millisecondsToDelay) {
12166        mContext.enforceCallingOrSelfPermission(
12167                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12168                "Only package verification agents can extend verification timeouts");
12169
12170        final PackageVerificationState state = mPendingVerification.get(id);
12171        final PackageVerificationResponse response = new PackageVerificationResponse(
12172                verificationCodeAtTimeout, Binder.getCallingUid());
12173
12174        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12175            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12176        }
12177        if (millisecondsToDelay < 0) {
12178            millisecondsToDelay = 0;
12179        }
12180        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12181                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12182            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12183        }
12184
12185        if ((state != null) && !state.timeoutExtended()) {
12186            state.extendTimeout();
12187
12188            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12189            msg.arg1 = id;
12190            msg.obj = response;
12191            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12192        }
12193    }
12194
12195    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12196            int verificationCode, UserHandle user) {
12197        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12198        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12199        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12200        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12201        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12202
12203        mContext.sendBroadcastAsUser(intent, user,
12204                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12205    }
12206
12207    private ComponentName matchComponentForVerifier(String packageName,
12208            List<ResolveInfo> receivers) {
12209        ActivityInfo targetReceiver = null;
12210
12211        final int NR = receivers.size();
12212        for (int i = 0; i < NR; i++) {
12213            final ResolveInfo info = receivers.get(i);
12214            if (info.activityInfo == null) {
12215                continue;
12216            }
12217
12218            if (packageName.equals(info.activityInfo.packageName)) {
12219                targetReceiver = info.activityInfo;
12220                break;
12221            }
12222        }
12223
12224        if (targetReceiver == null) {
12225            return null;
12226        }
12227
12228        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12229    }
12230
12231    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12232            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12233        if (pkgInfo.verifiers.length == 0) {
12234            return null;
12235        }
12236
12237        final int N = pkgInfo.verifiers.length;
12238        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12239        for (int i = 0; i < N; i++) {
12240            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12241
12242            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12243                    receivers);
12244            if (comp == null) {
12245                continue;
12246            }
12247
12248            final int verifierUid = getUidForVerifier(verifierInfo);
12249            if (verifierUid == -1) {
12250                continue;
12251            }
12252
12253            if (DEBUG_VERIFY) {
12254                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12255                        + " with the correct signature");
12256            }
12257            sufficientVerifiers.add(comp);
12258            verificationState.addSufficientVerifier(verifierUid);
12259        }
12260
12261        return sufficientVerifiers;
12262    }
12263
12264    private int getUidForVerifier(VerifierInfo verifierInfo) {
12265        synchronized (mPackages) {
12266            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12267            if (pkg == null) {
12268                return -1;
12269            } else if (pkg.mSignatures.length != 1) {
12270                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12271                        + " has more than one signature; ignoring");
12272                return -1;
12273            }
12274
12275            /*
12276             * If the public key of the package's signature does not match
12277             * our expected public key, then this is a different package and
12278             * we should skip.
12279             */
12280
12281            final byte[] expectedPublicKey;
12282            try {
12283                final Signature verifierSig = pkg.mSignatures[0];
12284                final PublicKey publicKey = verifierSig.getPublicKey();
12285                expectedPublicKey = publicKey.getEncoded();
12286            } catch (CertificateException e) {
12287                return -1;
12288            }
12289
12290            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12291
12292            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12293                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12294                        + " does not have the expected public key; ignoring");
12295                return -1;
12296            }
12297
12298            return pkg.applicationInfo.uid;
12299        }
12300    }
12301
12302    @Override
12303    public void finishPackageInstall(int token, boolean didLaunch) {
12304        enforceSystemOrRoot("Only the system is allowed to finish installs");
12305
12306        if (DEBUG_INSTALL) {
12307            Slog.v(TAG, "BM finishing package install for " + token);
12308        }
12309        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12310
12311        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12312        mHandler.sendMessage(msg);
12313    }
12314
12315    /**
12316     * Get the verification agent timeout.
12317     *
12318     * @return verification timeout in milliseconds
12319     */
12320    private long getVerificationTimeout() {
12321        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12322                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12323                DEFAULT_VERIFICATION_TIMEOUT);
12324    }
12325
12326    /**
12327     * Get the default verification agent response code.
12328     *
12329     * @return default verification response code
12330     */
12331    private int getDefaultVerificationResponse() {
12332        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12333                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12334                DEFAULT_VERIFICATION_RESPONSE);
12335    }
12336
12337    /**
12338     * Check whether or not package verification has been enabled.
12339     *
12340     * @return true if verification should be performed
12341     */
12342    private boolean isVerificationEnabled(int userId, int installFlags) {
12343        if (!DEFAULT_VERIFY_ENABLE) {
12344            return false;
12345        }
12346        // Ephemeral apps don't get the full verification treatment
12347        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12348            if (DEBUG_EPHEMERAL) {
12349                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12350            }
12351            return false;
12352        }
12353
12354        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12355
12356        // Check if installing from ADB
12357        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12358            // Do not run verification in a test harness environment
12359            if (ActivityManager.isRunningInTestHarness()) {
12360                return false;
12361            }
12362            if (ensureVerifyAppsEnabled) {
12363                return true;
12364            }
12365            // Check if the developer does not want package verification for ADB installs
12366            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12367                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12368                return false;
12369            }
12370        }
12371
12372        if (ensureVerifyAppsEnabled) {
12373            return true;
12374        }
12375
12376        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12377                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12378    }
12379
12380    @Override
12381    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12382            throws RemoteException {
12383        mContext.enforceCallingOrSelfPermission(
12384                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12385                "Only intentfilter verification agents can verify applications");
12386
12387        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12388        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12389                Binder.getCallingUid(), verificationCode, failedDomains);
12390        msg.arg1 = id;
12391        msg.obj = response;
12392        mHandler.sendMessage(msg);
12393    }
12394
12395    @Override
12396    public int getIntentVerificationStatus(String packageName, int userId) {
12397        synchronized (mPackages) {
12398            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12399        }
12400    }
12401
12402    @Override
12403    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12404        mContext.enforceCallingOrSelfPermission(
12405                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12406
12407        boolean result = false;
12408        synchronized (mPackages) {
12409            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12410        }
12411        if (result) {
12412            scheduleWritePackageRestrictionsLocked(userId);
12413        }
12414        return result;
12415    }
12416
12417    @Override
12418    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12419            String packageName) {
12420        synchronized (mPackages) {
12421            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12422        }
12423    }
12424
12425    @Override
12426    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12427        if (TextUtils.isEmpty(packageName)) {
12428            return ParceledListSlice.emptyList();
12429        }
12430        synchronized (mPackages) {
12431            PackageParser.Package pkg = mPackages.get(packageName);
12432            if (pkg == null || pkg.activities == null) {
12433                return ParceledListSlice.emptyList();
12434            }
12435            final int count = pkg.activities.size();
12436            ArrayList<IntentFilter> result = new ArrayList<>();
12437            for (int n=0; n<count; n++) {
12438                PackageParser.Activity activity = pkg.activities.get(n);
12439                if (activity.intents != null && activity.intents.size() > 0) {
12440                    result.addAll(activity.intents);
12441                }
12442            }
12443            return new ParceledListSlice<>(result);
12444        }
12445    }
12446
12447    @Override
12448    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12449        mContext.enforceCallingOrSelfPermission(
12450                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12451
12452        synchronized (mPackages) {
12453            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12454            if (packageName != null) {
12455                result |= updateIntentVerificationStatus(packageName,
12456                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12457                        userId);
12458                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12459                        packageName, userId);
12460            }
12461            return result;
12462        }
12463    }
12464
12465    @Override
12466    public String getDefaultBrowserPackageName(int userId) {
12467        synchronized (mPackages) {
12468            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12469        }
12470    }
12471
12472    /**
12473     * Get the "allow unknown sources" setting.
12474     *
12475     * @return the current "allow unknown sources" setting
12476     */
12477    private int getUnknownSourcesSettings() {
12478        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12479                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12480                -1);
12481    }
12482
12483    @Override
12484    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12485        final int uid = Binder.getCallingUid();
12486        // writer
12487        synchronized (mPackages) {
12488            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12489            if (targetPackageSetting == null) {
12490                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12491            }
12492
12493            PackageSetting installerPackageSetting;
12494            if (installerPackageName != null) {
12495                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12496                if (installerPackageSetting == null) {
12497                    throw new IllegalArgumentException("Unknown installer package: "
12498                            + installerPackageName);
12499                }
12500            } else {
12501                installerPackageSetting = null;
12502            }
12503
12504            Signature[] callerSignature;
12505            Object obj = mSettings.getUserIdLPr(uid);
12506            if (obj != null) {
12507                if (obj instanceof SharedUserSetting) {
12508                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12509                } else if (obj instanceof PackageSetting) {
12510                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12511                } else {
12512                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12513                }
12514            } else {
12515                throw new SecurityException("Unknown calling UID: " + uid);
12516            }
12517
12518            // Verify: can't set installerPackageName to a package that is
12519            // not signed with the same cert as the caller.
12520            if (installerPackageSetting != null) {
12521                if (compareSignatures(callerSignature,
12522                        installerPackageSetting.signatures.mSignatures)
12523                        != PackageManager.SIGNATURE_MATCH) {
12524                    throw new SecurityException(
12525                            "Caller does not have same cert as new installer package "
12526                            + installerPackageName);
12527                }
12528            }
12529
12530            // Verify: if target already has an installer package, it must
12531            // be signed with the same cert as the caller.
12532            if (targetPackageSetting.installerPackageName != null) {
12533                PackageSetting setting = mSettings.mPackages.get(
12534                        targetPackageSetting.installerPackageName);
12535                // If the currently set package isn't valid, then it's always
12536                // okay to change it.
12537                if (setting != null) {
12538                    if (compareSignatures(callerSignature,
12539                            setting.signatures.mSignatures)
12540                            != PackageManager.SIGNATURE_MATCH) {
12541                        throw new SecurityException(
12542                                "Caller does not have same cert as old installer package "
12543                                + targetPackageSetting.installerPackageName);
12544                    }
12545                }
12546            }
12547
12548            // Okay!
12549            targetPackageSetting.installerPackageName = installerPackageName;
12550            if (installerPackageName != null) {
12551                mSettings.mInstallerPackages.add(installerPackageName);
12552            }
12553            scheduleWriteSettingsLocked();
12554        }
12555    }
12556
12557    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12558        // Queue up an async operation since the package installation may take a little while.
12559        mHandler.post(new Runnable() {
12560            public void run() {
12561                mHandler.removeCallbacks(this);
12562                 // Result object to be returned
12563                PackageInstalledInfo res = new PackageInstalledInfo();
12564                res.setReturnCode(currentStatus);
12565                res.uid = -1;
12566                res.pkg = null;
12567                res.removedInfo = null;
12568                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12569                    args.doPreInstall(res.returnCode);
12570                    synchronized (mInstallLock) {
12571                        installPackageTracedLI(args, res);
12572                    }
12573                    args.doPostInstall(res.returnCode, res.uid);
12574                }
12575
12576                // A restore should be performed at this point if (a) the install
12577                // succeeded, (b) the operation is not an update, and (c) the new
12578                // package has not opted out of backup participation.
12579                final boolean update = res.removedInfo != null
12580                        && res.removedInfo.removedPackage != null;
12581                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12582                boolean doRestore = !update
12583                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12584
12585                // Set up the post-install work request bookkeeping.  This will be used
12586                // and cleaned up by the post-install event handling regardless of whether
12587                // there's a restore pass performed.  Token values are >= 1.
12588                int token;
12589                if (mNextInstallToken < 0) mNextInstallToken = 1;
12590                token = mNextInstallToken++;
12591
12592                PostInstallData data = new PostInstallData(args, res);
12593                mRunningInstalls.put(token, data);
12594                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12595
12596                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12597                    // Pass responsibility to the Backup Manager.  It will perform a
12598                    // restore if appropriate, then pass responsibility back to the
12599                    // Package Manager to run the post-install observer callbacks
12600                    // and broadcasts.
12601                    IBackupManager bm = IBackupManager.Stub.asInterface(
12602                            ServiceManager.getService(Context.BACKUP_SERVICE));
12603                    if (bm != null) {
12604                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12605                                + " to BM for possible restore");
12606                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12607                        try {
12608                            // TODO: http://b/22388012
12609                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12610                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12611                            } else {
12612                                doRestore = false;
12613                            }
12614                        } catch (RemoteException e) {
12615                            // can't happen; the backup manager is local
12616                        } catch (Exception e) {
12617                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12618                            doRestore = false;
12619                        }
12620                    } else {
12621                        Slog.e(TAG, "Backup Manager not found!");
12622                        doRestore = false;
12623                    }
12624                }
12625
12626                if (!doRestore) {
12627                    // No restore possible, or the Backup Manager was mysteriously not
12628                    // available -- just fire the post-install work request directly.
12629                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12630
12631                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12632
12633                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12634                    mHandler.sendMessage(msg);
12635                }
12636            }
12637        });
12638    }
12639
12640    /**
12641     * Callback from PackageSettings whenever an app is first transitioned out of the
12642     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12643     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12644     * here whether the app is the target of an ongoing install, and only send the
12645     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12646     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12647     * handling.
12648     */
12649    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12650        // Serialize this with the rest of the install-process message chain.  In the
12651        // restore-at-install case, this Runnable will necessarily run before the
12652        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12653        // are coherent.  In the non-restore case, the app has already completed install
12654        // and been launched through some other means, so it is not in a problematic
12655        // state for observers to see the FIRST_LAUNCH signal.
12656        mHandler.post(new Runnable() {
12657            @Override
12658            public void run() {
12659                for (int i = 0; i < mRunningInstalls.size(); i++) {
12660                    final PostInstallData data = mRunningInstalls.valueAt(i);
12661                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12662                        continue;
12663                    }
12664                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12665                        // right package; but is it for the right user?
12666                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12667                            if (userId == data.res.newUsers[uIndex]) {
12668                                if (DEBUG_BACKUP) {
12669                                    Slog.i(TAG, "Package " + pkgName
12670                                            + " being restored so deferring FIRST_LAUNCH");
12671                                }
12672                                return;
12673                            }
12674                        }
12675                    }
12676                }
12677                // didn't find it, so not being restored
12678                if (DEBUG_BACKUP) {
12679                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12680                }
12681                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12682            }
12683        });
12684    }
12685
12686    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12687        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12688                installerPkg, null, userIds);
12689    }
12690
12691    private abstract class HandlerParams {
12692        private static final int MAX_RETRIES = 4;
12693
12694        /**
12695         * Number of times startCopy() has been attempted and had a non-fatal
12696         * error.
12697         */
12698        private int mRetries = 0;
12699
12700        /** User handle for the user requesting the information or installation. */
12701        private final UserHandle mUser;
12702        String traceMethod;
12703        int traceCookie;
12704
12705        HandlerParams(UserHandle user) {
12706            mUser = user;
12707        }
12708
12709        UserHandle getUser() {
12710            return mUser;
12711        }
12712
12713        HandlerParams setTraceMethod(String traceMethod) {
12714            this.traceMethod = traceMethod;
12715            return this;
12716        }
12717
12718        HandlerParams setTraceCookie(int traceCookie) {
12719            this.traceCookie = traceCookie;
12720            return this;
12721        }
12722
12723        final boolean startCopy() {
12724            boolean res;
12725            try {
12726                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12727
12728                if (++mRetries > MAX_RETRIES) {
12729                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12730                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12731                    handleServiceError();
12732                    return false;
12733                } else {
12734                    handleStartCopy();
12735                    res = true;
12736                }
12737            } catch (RemoteException e) {
12738                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12739                mHandler.sendEmptyMessage(MCS_RECONNECT);
12740                res = false;
12741            }
12742            handleReturnCode();
12743            return res;
12744        }
12745
12746        final void serviceError() {
12747            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12748            handleServiceError();
12749            handleReturnCode();
12750        }
12751
12752        abstract void handleStartCopy() throws RemoteException;
12753        abstract void handleServiceError();
12754        abstract void handleReturnCode();
12755    }
12756
12757    class MeasureParams extends HandlerParams {
12758        private final PackageStats mStats;
12759        private boolean mSuccess;
12760
12761        private final IPackageStatsObserver mObserver;
12762
12763        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12764            super(new UserHandle(stats.userHandle));
12765            mObserver = observer;
12766            mStats = stats;
12767        }
12768
12769        @Override
12770        public String toString() {
12771            return "MeasureParams{"
12772                + Integer.toHexString(System.identityHashCode(this))
12773                + " " + mStats.packageName + "}";
12774        }
12775
12776        @Override
12777        void handleStartCopy() throws RemoteException {
12778            synchronized (mInstallLock) {
12779                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12780            }
12781
12782            if (mSuccess) {
12783                boolean mounted = false;
12784                try {
12785                    final String status = Environment.getExternalStorageState();
12786                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12787                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12788                } catch (Exception e) {
12789                }
12790
12791                if (mounted) {
12792                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12793
12794                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12795                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12796
12797                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12798                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12799
12800                    // Always subtract cache size, since it's a subdirectory
12801                    mStats.externalDataSize -= mStats.externalCacheSize;
12802
12803                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12804                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12805
12806                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12807                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12808                }
12809            }
12810        }
12811
12812        @Override
12813        void handleReturnCode() {
12814            if (mObserver != null) {
12815                try {
12816                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12817                } catch (RemoteException e) {
12818                    Slog.i(TAG, "Observer no longer exists.");
12819                }
12820            }
12821        }
12822
12823        @Override
12824        void handleServiceError() {
12825            Slog.e(TAG, "Could not measure application " + mStats.packageName
12826                            + " external storage");
12827        }
12828    }
12829
12830    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12831            throws RemoteException {
12832        long result = 0;
12833        for (File path : paths) {
12834            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12835        }
12836        return result;
12837    }
12838
12839    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12840        for (File path : paths) {
12841            try {
12842                mcs.clearDirectory(path.getAbsolutePath());
12843            } catch (RemoteException e) {
12844            }
12845        }
12846    }
12847
12848    static class OriginInfo {
12849        /**
12850         * Location where install is coming from, before it has been
12851         * copied/renamed into place. This could be a single monolithic APK
12852         * file, or a cluster directory. This location may be untrusted.
12853         */
12854        final File file;
12855        final String cid;
12856
12857        /**
12858         * Flag indicating that {@link #file} or {@link #cid} has already been
12859         * staged, meaning downstream users don't need to defensively copy the
12860         * contents.
12861         */
12862        final boolean staged;
12863
12864        /**
12865         * Flag indicating that {@link #file} or {@link #cid} is an already
12866         * installed app that is being moved.
12867         */
12868        final boolean existing;
12869
12870        final String resolvedPath;
12871        final File resolvedFile;
12872
12873        static OriginInfo fromNothing() {
12874            return new OriginInfo(null, null, false, false);
12875        }
12876
12877        static OriginInfo fromUntrustedFile(File file) {
12878            return new OriginInfo(file, null, false, false);
12879        }
12880
12881        static OriginInfo fromExistingFile(File file) {
12882            return new OriginInfo(file, null, false, true);
12883        }
12884
12885        static OriginInfo fromStagedFile(File file) {
12886            return new OriginInfo(file, null, true, false);
12887        }
12888
12889        static OriginInfo fromStagedContainer(String cid) {
12890            return new OriginInfo(null, cid, true, false);
12891        }
12892
12893        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12894            this.file = file;
12895            this.cid = cid;
12896            this.staged = staged;
12897            this.existing = existing;
12898
12899            if (cid != null) {
12900                resolvedPath = PackageHelper.getSdDir(cid);
12901                resolvedFile = new File(resolvedPath);
12902            } else if (file != null) {
12903                resolvedPath = file.getAbsolutePath();
12904                resolvedFile = file;
12905            } else {
12906                resolvedPath = null;
12907                resolvedFile = null;
12908            }
12909        }
12910    }
12911
12912    static class MoveInfo {
12913        final int moveId;
12914        final String fromUuid;
12915        final String toUuid;
12916        final String packageName;
12917        final String dataAppName;
12918        final int appId;
12919        final String seinfo;
12920        final int targetSdkVersion;
12921
12922        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12923                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12924            this.moveId = moveId;
12925            this.fromUuid = fromUuid;
12926            this.toUuid = toUuid;
12927            this.packageName = packageName;
12928            this.dataAppName = dataAppName;
12929            this.appId = appId;
12930            this.seinfo = seinfo;
12931            this.targetSdkVersion = targetSdkVersion;
12932        }
12933    }
12934
12935    static class VerificationInfo {
12936        /** A constant used to indicate that a uid value is not present. */
12937        public static final int NO_UID = -1;
12938
12939        /** URI referencing where the package was downloaded from. */
12940        final Uri originatingUri;
12941
12942        /** HTTP referrer URI associated with the originatingURI. */
12943        final Uri referrer;
12944
12945        /** UID of the application that the install request originated from. */
12946        final int originatingUid;
12947
12948        /** UID of application requesting the install */
12949        final int installerUid;
12950
12951        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12952            this.originatingUri = originatingUri;
12953            this.referrer = referrer;
12954            this.originatingUid = originatingUid;
12955            this.installerUid = installerUid;
12956        }
12957    }
12958
12959    class InstallParams extends HandlerParams {
12960        final OriginInfo origin;
12961        final MoveInfo move;
12962        final IPackageInstallObserver2 observer;
12963        int installFlags;
12964        final String installerPackageName;
12965        final String volumeUuid;
12966        private InstallArgs mArgs;
12967        private int mRet;
12968        final String packageAbiOverride;
12969        final String[] grantedRuntimePermissions;
12970        final VerificationInfo verificationInfo;
12971        final Certificate[][] certificates;
12972
12973        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12974                int installFlags, String installerPackageName, String volumeUuid,
12975                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12976                String[] grantedPermissions, Certificate[][] certificates) {
12977            super(user);
12978            this.origin = origin;
12979            this.move = move;
12980            this.observer = observer;
12981            this.installFlags = installFlags;
12982            this.installerPackageName = installerPackageName;
12983            this.volumeUuid = volumeUuid;
12984            this.verificationInfo = verificationInfo;
12985            this.packageAbiOverride = packageAbiOverride;
12986            this.grantedRuntimePermissions = grantedPermissions;
12987            this.certificates = certificates;
12988        }
12989
12990        @Override
12991        public String toString() {
12992            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12993                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12994        }
12995
12996        private int installLocationPolicy(PackageInfoLite pkgLite) {
12997            String packageName = pkgLite.packageName;
12998            int installLocation = pkgLite.installLocation;
12999            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13000            // reader
13001            synchronized (mPackages) {
13002                // Currently installed package which the new package is attempting to replace or
13003                // null if no such package is installed.
13004                PackageParser.Package installedPkg = mPackages.get(packageName);
13005                // Package which currently owns the data which the new package will own if installed.
13006                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13007                // will be null whereas dataOwnerPkg will contain information about the package
13008                // which was uninstalled while keeping its data.
13009                PackageParser.Package dataOwnerPkg = installedPkg;
13010                if (dataOwnerPkg  == null) {
13011                    PackageSetting ps = mSettings.mPackages.get(packageName);
13012                    if (ps != null) {
13013                        dataOwnerPkg = ps.pkg;
13014                    }
13015                }
13016
13017                if (dataOwnerPkg != null) {
13018                    // If installed, the package will get access to data left on the device by its
13019                    // predecessor. As a security measure, this is permited only if this is not a
13020                    // version downgrade or if the predecessor package is marked as debuggable and
13021                    // a downgrade is explicitly requested.
13022                    //
13023                    // On debuggable platform builds, downgrades are permitted even for
13024                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13025                    // not offer security guarantees and thus it's OK to disable some security
13026                    // mechanisms to make debugging/testing easier on those builds. However, even on
13027                    // debuggable builds downgrades of packages are permitted only if requested via
13028                    // installFlags. This is because we aim to keep the behavior of debuggable
13029                    // platform builds as close as possible to the behavior of non-debuggable
13030                    // platform builds.
13031                    final boolean downgradeRequested =
13032                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13033                    final boolean packageDebuggable =
13034                                (dataOwnerPkg.applicationInfo.flags
13035                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13036                    final boolean downgradePermitted =
13037                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13038                    if (!downgradePermitted) {
13039                        try {
13040                            checkDowngrade(dataOwnerPkg, pkgLite);
13041                        } catch (PackageManagerException e) {
13042                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13043                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13044                        }
13045                    }
13046                }
13047
13048                if (installedPkg != null) {
13049                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13050                        // Check for updated system application.
13051                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13052                            if (onSd) {
13053                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13054                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13055                            }
13056                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13057                        } else {
13058                            if (onSd) {
13059                                // Install flag overrides everything.
13060                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13061                            }
13062                            // If current upgrade specifies particular preference
13063                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13064                                // Application explicitly specified internal.
13065                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13066                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13067                                // App explictly prefers external. Let policy decide
13068                            } else {
13069                                // Prefer previous location
13070                                if (isExternal(installedPkg)) {
13071                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13072                                }
13073                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13074                            }
13075                        }
13076                    } else {
13077                        // Invalid install. Return error code
13078                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13079                    }
13080                }
13081            }
13082            // All the special cases have been taken care of.
13083            // Return result based on recommended install location.
13084            if (onSd) {
13085                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13086            }
13087            return pkgLite.recommendedInstallLocation;
13088        }
13089
13090        /*
13091         * Invoke remote method to get package information and install
13092         * location values. Override install location based on default
13093         * policy if needed and then create install arguments based
13094         * on the install location.
13095         */
13096        public void handleStartCopy() throws RemoteException {
13097            int ret = PackageManager.INSTALL_SUCCEEDED;
13098
13099            // If we're already staged, we've firmly committed to an install location
13100            if (origin.staged) {
13101                if (origin.file != null) {
13102                    installFlags |= PackageManager.INSTALL_INTERNAL;
13103                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13104                } else if (origin.cid != null) {
13105                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13106                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13107                } else {
13108                    throw new IllegalStateException("Invalid stage location");
13109                }
13110            }
13111
13112            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13113            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13114            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13115            PackageInfoLite pkgLite = null;
13116
13117            if (onInt && onSd) {
13118                // Check if both bits are set.
13119                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13120                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13121            } else if (onSd && ephemeral) {
13122                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13123                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13124            } else {
13125                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13126                        packageAbiOverride);
13127
13128                if (DEBUG_EPHEMERAL && ephemeral) {
13129                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13130                }
13131
13132                /*
13133                 * If we have too little free space, try to free cache
13134                 * before giving up.
13135                 */
13136                if (!origin.staged && pkgLite.recommendedInstallLocation
13137                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13138                    // TODO: focus freeing disk space on the target device
13139                    final StorageManager storage = StorageManager.from(mContext);
13140                    final long lowThreshold = storage.getStorageLowBytes(
13141                            Environment.getDataDirectory());
13142
13143                    final long sizeBytes = mContainerService.calculateInstalledSize(
13144                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13145
13146                    try {
13147                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13148                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13149                                installFlags, packageAbiOverride);
13150                    } catch (InstallerException e) {
13151                        Slog.w(TAG, "Failed to free cache", e);
13152                    }
13153
13154                    /*
13155                     * The cache free must have deleted the file we
13156                     * downloaded to install.
13157                     *
13158                     * TODO: fix the "freeCache" call to not delete
13159                     *       the file we care about.
13160                     */
13161                    if (pkgLite.recommendedInstallLocation
13162                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13163                        pkgLite.recommendedInstallLocation
13164                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13165                    }
13166                }
13167            }
13168
13169            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13170                int loc = pkgLite.recommendedInstallLocation;
13171                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13172                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13173                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13174                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13175                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13176                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13177                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13178                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13179                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13180                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13181                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13182                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13183                } else {
13184                    // Override with defaults if needed.
13185                    loc = installLocationPolicy(pkgLite);
13186                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13187                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13188                    } else if (!onSd && !onInt) {
13189                        // Override install location with flags
13190                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13191                            // Set the flag to install on external media.
13192                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13193                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13194                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13195                            if (DEBUG_EPHEMERAL) {
13196                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13197                            }
13198                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13199                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13200                                    |PackageManager.INSTALL_INTERNAL);
13201                        } else {
13202                            // Make sure the flag for installing on external
13203                            // media is unset
13204                            installFlags |= PackageManager.INSTALL_INTERNAL;
13205                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13206                        }
13207                    }
13208                }
13209            }
13210
13211            final InstallArgs args = createInstallArgs(this);
13212            mArgs = args;
13213
13214            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13215                // TODO: http://b/22976637
13216                // Apps installed for "all" users use the device owner to verify the app
13217                UserHandle verifierUser = getUser();
13218                if (verifierUser == UserHandle.ALL) {
13219                    verifierUser = UserHandle.SYSTEM;
13220                }
13221
13222                /*
13223                 * Determine if we have any installed package verifiers. If we
13224                 * do, then we'll defer to them to verify the packages.
13225                 */
13226                final int requiredUid = mRequiredVerifierPackage == null ? -1
13227                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13228                                verifierUser.getIdentifier());
13229                if (!origin.existing && requiredUid != -1
13230                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13231                    final Intent verification = new Intent(
13232                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13233                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13234                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13235                            PACKAGE_MIME_TYPE);
13236                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13237
13238                    // Query all live verifiers based on current user state
13239                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13240                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13241
13242                    if (DEBUG_VERIFY) {
13243                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13244                                + verification.toString() + " with " + pkgLite.verifiers.length
13245                                + " optional verifiers");
13246                    }
13247
13248                    final int verificationId = mPendingVerificationToken++;
13249
13250                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13251
13252                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13253                            installerPackageName);
13254
13255                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13256                            installFlags);
13257
13258                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13259                            pkgLite.packageName);
13260
13261                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13262                            pkgLite.versionCode);
13263
13264                    if (verificationInfo != null) {
13265                        if (verificationInfo.originatingUri != null) {
13266                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13267                                    verificationInfo.originatingUri);
13268                        }
13269                        if (verificationInfo.referrer != null) {
13270                            verification.putExtra(Intent.EXTRA_REFERRER,
13271                                    verificationInfo.referrer);
13272                        }
13273                        if (verificationInfo.originatingUid >= 0) {
13274                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13275                                    verificationInfo.originatingUid);
13276                        }
13277                        if (verificationInfo.installerUid >= 0) {
13278                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13279                                    verificationInfo.installerUid);
13280                        }
13281                    }
13282
13283                    final PackageVerificationState verificationState = new PackageVerificationState(
13284                            requiredUid, args);
13285
13286                    mPendingVerification.append(verificationId, verificationState);
13287
13288                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13289                            receivers, verificationState);
13290
13291                    /*
13292                     * If any sufficient verifiers were listed in the package
13293                     * manifest, attempt to ask them.
13294                     */
13295                    if (sufficientVerifiers != null) {
13296                        final int N = sufficientVerifiers.size();
13297                        if (N == 0) {
13298                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13299                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13300                        } else {
13301                            for (int i = 0; i < N; i++) {
13302                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13303
13304                                final Intent sufficientIntent = new Intent(verification);
13305                                sufficientIntent.setComponent(verifierComponent);
13306                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13307                            }
13308                        }
13309                    }
13310
13311                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13312                            mRequiredVerifierPackage, receivers);
13313                    if (ret == PackageManager.INSTALL_SUCCEEDED
13314                            && mRequiredVerifierPackage != null) {
13315                        Trace.asyncTraceBegin(
13316                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13317                        /*
13318                         * Send the intent to the required verification agent,
13319                         * but only start the verification timeout after the
13320                         * target BroadcastReceivers have run.
13321                         */
13322                        verification.setComponent(requiredVerifierComponent);
13323                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13324                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13325                                new BroadcastReceiver() {
13326                                    @Override
13327                                    public void onReceive(Context context, Intent intent) {
13328                                        final Message msg = mHandler
13329                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13330                                        msg.arg1 = verificationId;
13331                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13332                                    }
13333                                }, null, 0, null, null);
13334
13335                        /*
13336                         * We don't want the copy to proceed until verification
13337                         * succeeds, so null out this field.
13338                         */
13339                        mArgs = null;
13340                    }
13341                } else {
13342                    /*
13343                     * No package verification is enabled, so immediately start
13344                     * the remote call to initiate copy using temporary file.
13345                     */
13346                    ret = args.copyApk(mContainerService, true);
13347                }
13348            }
13349
13350            mRet = ret;
13351        }
13352
13353        @Override
13354        void handleReturnCode() {
13355            // If mArgs is null, then MCS couldn't be reached. When it
13356            // reconnects, it will try again to install. At that point, this
13357            // will succeed.
13358            if (mArgs != null) {
13359                processPendingInstall(mArgs, mRet);
13360            }
13361        }
13362
13363        @Override
13364        void handleServiceError() {
13365            mArgs = createInstallArgs(this);
13366            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13367        }
13368
13369        public boolean isForwardLocked() {
13370            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13371        }
13372    }
13373
13374    /**
13375     * Used during creation of InstallArgs
13376     *
13377     * @param installFlags package installation flags
13378     * @return true if should be installed on external storage
13379     */
13380    private static boolean installOnExternalAsec(int installFlags) {
13381        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13382            return false;
13383        }
13384        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13385            return true;
13386        }
13387        return false;
13388    }
13389
13390    /**
13391     * Used during creation of InstallArgs
13392     *
13393     * @param installFlags package installation flags
13394     * @return true if should be installed as forward locked
13395     */
13396    private static boolean installForwardLocked(int installFlags) {
13397        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13398    }
13399
13400    private InstallArgs createInstallArgs(InstallParams params) {
13401        if (params.move != null) {
13402            return new MoveInstallArgs(params);
13403        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13404            return new AsecInstallArgs(params);
13405        } else {
13406            return new FileInstallArgs(params);
13407        }
13408    }
13409
13410    /**
13411     * Create args that describe an existing installed package. Typically used
13412     * when cleaning up old installs, or used as a move source.
13413     */
13414    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13415            String resourcePath, String[] instructionSets) {
13416        final boolean isInAsec;
13417        if (installOnExternalAsec(installFlags)) {
13418            /* Apps on SD card are always in ASEC containers. */
13419            isInAsec = true;
13420        } else if (installForwardLocked(installFlags)
13421                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13422            /*
13423             * Forward-locked apps are only in ASEC containers if they're the
13424             * new style
13425             */
13426            isInAsec = true;
13427        } else {
13428            isInAsec = false;
13429        }
13430
13431        if (isInAsec) {
13432            return new AsecInstallArgs(codePath, instructionSets,
13433                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13434        } else {
13435            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13436        }
13437    }
13438
13439    static abstract class InstallArgs {
13440        /** @see InstallParams#origin */
13441        final OriginInfo origin;
13442        /** @see InstallParams#move */
13443        final MoveInfo move;
13444
13445        final IPackageInstallObserver2 observer;
13446        // Always refers to PackageManager flags only
13447        final int installFlags;
13448        final String installerPackageName;
13449        final String volumeUuid;
13450        final UserHandle user;
13451        final String abiOverride;
13452        final String[] installGrantPermissions;
13453        /** If non-null, drop an async trace when the install completes */
13454        final String traceMethod;
13455        final int traceCookie;
13456        final Certificate[][] certificates;
13457
13458        // The list of instruction sets supported by this app. This is currently
13459        // only used during the rmdex() phase to clean up resources. We can get rid of this
13460        // if we move dex files under the common app path.
13461        /* nullable */ String[] instructionSets;
13462
13463        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13464                int installFlags, String installerPackageName, String volumeUuid,
13465                UserHandle user, String[] instructionSets,
13466                String abiOverride, String[] installGrantPermissions,
13467                String traceMethod, int traceCookie, Certificate[][] certificates) {
13468            this.origin = origin;
13469            this.move = move;
13470            this.installFlags = installFlags;
13471            this.observer = observer;
13472            this.installerPackageName = installerPackageName;
13473            this.volumeUuid = volumeUuid;
13474            this.user = user;
13475            this.instructionSets = instructionSets;
13476            this.abiOverride = abiOverride;
13477            this.installGrantPermissions = installGrantPermissions;
13478            this.traceMethod = traceMethod;
13479            this.traceCookie = traceCookie;
13480            this.certificates = certificates;
13481        }
13482
13483        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13484        abstract int doPreInstall(int status);
13485
13486        /**
13487         * Rename package into final resting place. All paths on the given
13488         * scanned package should be updated to reflect the rename.
13489         */
13490        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13491        abstract int doPostInstall(int status, int uid);
13492
13493        /** @see PackageSettingBase#codePathString */
13494        abstract String getCodePath();
13495        /** @see PackageSettingBase#resourcePathString */
13496        abstract String getResourcePath();
13497
13498        // Need installer lock especially for dex file removal.
13499        abstract void cleanUpResourcesLI();
13500        abstract boolean doPostDeleteLI(boolean delete);
13501
13502        /**
13503         * Called before the source arguments are copied. This is used mostly
13504         * for MoveParams when it needs to read the source file to put it in the
13505         * destination.
13506         */
13507        int doPreCopy() {
13508            return PackageManager.INSTALL_SUCCEEDED;
13509        }
13510
13511        /**
13512         * Called after the source arguments are copied. This is used mostly for
13513         * MoveParams when it needs to read the source file to put it in the
13514         * destination.
13515         */
13516        int doPostCopy(int uid) {
13517            return PackageManager.INSTALL_SUCCEEDED;
13518        }
13519
13520        protected boolean isFwdLocked() {
13521            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13522        }
13523
13524        protected boolean isExternalAsec() {
13525            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13526        }
13527
13528        protected boolean isEphemeral() {
13529            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13530        }
13531
13532        UserHandle getUser() {
13533            return user;
13534        }
13535    }
13536
13537    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13538        if (!allCodePaths.isEmpty()) {
13539            if (instructionSets == null) {
13540                throw new IllegalStateException("instructionSet == null");
13541            }
13542            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13543            for (String codePath : allCodePaths) {
13544                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13545                    try {
13546                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13547                    } catch (InstallerException ignored) {
13548                    }
13549                }
13550            }
13551        }
13552    }
13553
13554    /**
13555     * Logic to handle installation of non-ASEC applications, including copying
13556     * and renaming logic.
13557     */
13558    class FileInstallArgs extends InstallArgs {
13559        private File codeFile;
13560        private File resourceFile;
13561
13562        // Example topology:
13563        // /data/app/com.example/base.apk
13564        // /data/app/com.example/split_foo.apk
13565        // /data/app/com.example/lib/arm/libfoo.so
13566        // /data/app/com.example/lib/arm64/libfoo.so
13567        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13568
13569        /** New install */
13570        FileInstallArgs(InstallParams params) {
13571            super(params.origin, params.move, params.observer, params.installFlags,
13572                    params.installerPackageName, params.volumeUuid,
13573                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13574                    params.grantedRuntimePermissions,
13575                    params.traceMethod, params.traceCookie, params.certificates);
13576            if (isFwdLocked()) {
13577                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13578            }
13579        }
13580
13581        /** Existing install */
13582        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13583            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13584                    null, null, null, 0, null /*certificates*/);
13585            this.codeFile = (codePath != null) ? new File(codePath) : null;
13586            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13587        }
13588
13589        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13590            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13591            try {
13592                return doCopyApk(imcs, temp);
13593            } finally {
13594                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13595            }
13596        }
13597
13598        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13599            if (origin.staged) {
13600                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13601                codeFile = origin.file;
13602                resourceFile = origin.file;
13603                return PackageManager.INSTALL_SUCCEEDED;
13604            }
13605
13606            try {
13607                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13608                final File tempDir =
13609                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13610                codeFile = tempDir;
13611                resourceFile = tempDir;
13612            } catch (IOException e) {
13613                Slog.w(TAG, "Failed to create copy file: " + e);
13614                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13615            }
13616
13617            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13618                @Override
13619                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13620                    if (!FileUtils.isValidExtFilename(name)) {
13621                        throw new IllegalArgumentException("Invalid filename: " + name);
13622                    }
13623                    try {
13624                        final File file = new File(codeFile, name);
13625                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13626                                O_RDWR | O_CREAT, 0644);
13627                        Os.chmod(file.getAbsolutePath(), 0644);
13628                        return new ParcelFileDescriptor(fd);
13629                    } catch (ErrnoException e) {
13630                        throw new RemoteException("Failed to open: " + e.getMessage());
13631                    }
13632                }
13633            };
13634
13635            int ret = PackageManager.INSTALL_SUCCEEDED;
13636            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13637            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13638                Slog.e(TAG, "Failed to copy package");
13639                return ret;
13640            }
13641
13642            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13643            NativeLibraryHelper.Handle handle = null;
13644            try {
13645                handle = NativeLibraryHelper.Handle.create(codeFile);
13646                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13647                        abiOverride);
13648            } catch (IOException e) {
13649                Slog.e(TAG, "Copying native libraries failed", e);
13650                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13651            } finally {
13652                IoUtils.closeQuietly(handle);
13653            }
13654
13655            return ret;
13656        }
13657
13658        int doPreInstall(int status) {
13659            if (status != PackageManager.INSTALL_SUCCEEDED) {
13660                cleanUp();
13661            }
13662            return status;
13663        }
13664
13665        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13666            if (status != PackageManager.INSTALL_SUCCEEDED) {
13667                cleanUp();
13668                return false;
13669            }
13670
13671            final File targetDir = codeFile.getParentFile();
13672            final File beforeCodeFile = codeFile;
13673            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13674
13675            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13676            try {
13677                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13678            } catch (ErrnoException e) {
13679                Slog.w(TAG, "Failed to rename", e);
13680                return false;
13681            }
13682
13683            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13684                Slog.w(TAG, "Failed to restorecon");
13685                return false;
13686            }
13687
13688            // Reflect the rename internally
13689            codeFile = afterCodeFile;
13690            resourceFile = afterCodeFile;
13691
13692            // Reflect the rename in scanned details
13693            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13694            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13695                    afterCodeFile, pkg.baseCodePath));
13696            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13697                    afterCodeFile, pkg.splitCodePaths));
13698
13699            // Reflect the rename in app info
13700            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13701            pkg.setApplicationInfoCodePath(pkg.codePath);
13702            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13703            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13704            pkg.setApplicationInfoResourcePath(pkg.codePath);
13705            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13706            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13707
13708            return true;
13709        }
13710
13711        int doPostInstall(int status, int uid) {
13712            if (status != PackageManager.INSTALL_SUCCEEDED) {
13713                cleanUp();
13714            }
13715            return status;
13716        }
13717
13718        @Override
13719        String getCodePath() {
13720            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13721        }
13722
13723        @Override
13724        String getResourcePath() {
13725            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13726        }
13727
13728        private boolean cleanUp() {
13729            if (codeFile == null || !codeFile.exists()) {
13730                return false;
13731            }
13732
13733            removeCodePathLI(codeFile);
13734
13735            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13736                resourceFile.delete();
13737            }
13738
13739            return true;
13740        }
13741
13742        void cleanUpResourcesLI() {
13743            // Try enumerating all code paths before deleting
13744            List<String> allCodePaths = Collections.EMPTY_LIST;
13745            if (codeFile != null && codeFile.exists()) {
13746                try {
13747                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13748                    allCodePaths = pkg.getAllCodePaths();
13749                } catch (PackageParserException e) {
13750                    // Ignored; we tried our best
13751                }
13752            }
13753
13754            cleanUp();
13755            removeDexFiles(allCodePaths, instructionSets);
13756        }
13757
13758        boolean doPostDeleteLI(boolean delete) {
13759            // XXX err, shouldn't we respect the delete flag?
13760            cleanUpResourcesLI();
13761            return true;
13762        }
13763    }
13764
13765    private boolean isAsecExternal(String cid) {
13766        final String asecPath = PackageHelper.getSdFilesystem(cid);
13767        return !asecPath.startsWith(mAsecInternalPath);
13768    }
13769
13770    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13771            PackageManagerException {
13772        if (copyRet < 0) {
13773            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13774                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13775                throw new PackageManagerException(copyRet, message);
13776            }
13777        }
13778    }
13779
13780    /**
13781     * Extract the StorageManagerService "container ID" from the full code path of an
13782     * .apk.
13783     */
13784    static String cidFromCodePath(String fullCodePath) {
13785        int eidx = fullCodePath.lastIndexOf("/");
13786        String subStr1 = fullCodePath.substring(0, eidx);
13787        int sidx = subStr1.lastIndexOf("/");
13788        return subStr1.substring(sidx+1, eidx);
13789    }
13790
13791    /**
13792     * Logic to handle installation of ASEC applications, including copying and
13793     * renaming logic.
13794     */
13795    class AsecInstallArgs extends InstallArgs {
13796        static final String RES_FILE_NAME = "pkg.apk";
13797        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13798
13799        String cid;
13800        String packagePath;
13801        String resourcePath;
13802
13803        /** New install */
13804        AsecInstallArgs(InstallParams params) {
13805            super(params.origin, params.move, params.observer, params.installFlags,
13806                    params.installerPackageName, params.volumeUuid,
13807                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13808                    params.grantedRuntimePermissions,
13809                    params.traceMethod, params.traceCookie, params.certificates);
13810        }
13811
13812        /** Existing install */
13813        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13814                        boolean isExternal, boolean isForwardLocked) {
13815            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13816              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13817                    instructionSets, null, null, null, 0, null /*certificates*/);
13818            // Hackily pretend we're still looking at a full code path
13819            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13820                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13821            }
13822
13823            // Extract cid from fullCodePath
13824            int eidx = fullCodePath.lastIndexOf("/");
13825            String subStr1 = fullCodePath.substring(0, eidx);
13826            int sidx = subStr1.lastIndexOf("/");
13827            cid = subStr1.substring(sidx+1, eidx);
13828            setMountPath(subStr1);
13829        }
13830
13831        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13832            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13833              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13834                    instructionSets, null, null, null, 0, null /*certificates*/);
13835            this.cid = cid;
13836            setMountPath(PackageHelper.getSdDir(cid));
13837        }
13838
13839        void createCopyFile() {
13840            cid = mInstallerService.allocateExternalStageCidLegacy();
13841        }
13842
13843        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13844            if (origin.staged && origin.cid != null) {
13845                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13846                cid = origin.cid;
13847                setMountPath(PackageHelper.getSdDir(cid));
13848                return PackageManager.INSTALL_SUCCEEDED;
13849            }
13850
13851            if (temp) {
13852                createCopyFile();
13853            } else {
13854                /*
13855                 * Pre-emptively destroy the container since it's destroyed if
13856                 * copying fails due to it existing anyway.
13857                 */
13858                PackageHelper.destroySdDir(cid);
13859            }
13860
13861            final String newMountPath = imcs.copyPackageToContainer(
13862                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13863                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13864
13865            if (newMountPath != null) {
13866                setMountPath(newMountPath);
13867                return PackageManager.INSTALL_SUCCEEDED;
13868            } else {
13869                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13870            }
13871        }
13872
13873        @Override
13874        String getCodePath() {
13875            return packagePath;
13876        }
13877
13878        @Override
13879        String getResourcePath() {
13880            return resourcePath;
13881        }
13882
13883        int doPreInstall(int status) {
13884            if (status != PackageManager.INSTALL_SUCCEEDED) {
13885                // Destroy container
13886                PackageHelper.destroySdDir(cid);
13887            } else {
13888                boolean mounted = PackageHelper.isContainerMounted(cid);
13889                if (!mounted) {
13890                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13891                            Process.SYSTEM_UID);
13892                    if (newMountPath != null) {
13893                        setMountPath(newMountPath);
13894                    } else {
13895                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13896                    }
13897                }
13898            }
13899            return status;
13900        }
13901
13902        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13903            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13904            String newMountPath = null;
13905            if (PackageHelper.isContainerMounted(cid)) {
13906                // Unmount the container
13907                if (!PackageHelper.unMountSdDir(cid)) {
13908                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13909                    return false;
13910                }
13911            }
13912            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13913                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13914                        " which might be stale. Will try to clean up.");
13915                // Clean up the stale container and proceed to recreate.
13916                if (!PackageHelper.destroySdDir(newCacheId)) {
13917                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13918                    return false;
13919                }
13920                // Successfully cleaned up stale container. Try to rename again.
13921                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13922                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13923                            + " inspite of cleaning it up.");
13924                    return false;
13925                }
13926            }
13927            if (!PackageHelper.isContainerMounted(newCacheId)) {
13928                Slog.w(TAG, "Mounting container " + newCacheId);
13929                newMountPath = PackageHelper.mountSdDir(newCacheId,
13930                        getEncryptKey(), Process.SYSTEM_UID);
13931            } else {
13932                newMountPath = PackageHelper.getSdDir(newCacheId);
13933            }
13934            if (newMountPath == null) {
13935                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13936                return false;
13937            }
13938            Log.i(TAG, "Succesfully renamed " + cid +
13939                    " to " + newCacheId +
13940                    " at new path: " + newMountPath);
13941            cid = newCacheId;
13942
13943            final File beforeCodeFile = new File(packagePath);
13944            setMountPath(newMountPath);
13945            final File afterCodeFile = new File(packagePath);
13946
13947            // Reflect the rename in scanned details
13948            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13949            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13950                    afterCodeFile, pkg.baseCodePath));
13951            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13952                    afterCodeFile, pkg.splitCodePaths));
13953
13954            // Reflect the rename in app info
13955            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13956            pkg.setApplicationInfoCodePath(pkg.codePath);
13957            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13958            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13959            pkg.setApplicationInfoResourcePath(pkg.codePath);
13960            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13961            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13962
13963            return true;
13964        }
13965
13966        private void setMountPath(String mountPath) {
13967            final File mountFile = new File(mountPath);
13968
13969            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13970            if (monolithicFile.exists()) {
13971                packagePath = monolithicFile.getAbsolutePath();
13972                if (isFwdLocked()) {
13973                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13974                } else {
13975                    resourcePath = packagePath;
13976                }
13977            } else {
13978                packagePath = mountFile.getAbsolutePath();
13979                resourcePath = packagePath;
13980            }
13981        }
13982
13983        int doPostInstall(int status, int uid) {
13984            if (status != PackageManager.INSTALL_SUCCEEDED) {
13985                cleanUp();
13986            } else {
13987                final int groupOwner;
13988                final String protectedFile;
13989                if (isFwdLocked()) {
13990                    groupOwner = UserHandle.getSharedAppGid(uid);
13991                    protectedFile = RES_FILE_NAME;
13992                } else {
13993                    groupOwner = -1;
13994                    protectedFile = null;
13995                }
13996
13997                if (uid < Process.FIRST_APPLICATION_UID
13998                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13999                    Slog.e(TAG, "Failed to finalize " + cid);
14000                    PackageHelper.destroySdDir(cid);
14001                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14002                }
14003
14004                boolean mounted = PackageHelper.isContainerMounted(cid);
14005                if (!mounted) {
14006                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14007                }
14008            }
14009            return status;
14010        }
14011
14012        private void cleanUp() {
14013            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14014
14015            // Destroy secure container
14016            PackageHelper.destroySdDir(cid);
14017        }
14018
14019        private List<String> getAllCodePaths() {
14020            final File codeFile = new File(getCodePath());
14021            if (codeFile != null && codeFile.exists()) {
14022                try {
14023                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14024                    return pkg.getAllCodePaths();
14025                } catch (PackageParserException e) {
14026                    // Ignored; we tried our best
14027                }
14028            }
14029            return Collections.EMPTY_LIST;
14030        }
14031
14032        void cleanUpResourcesLI() {
14033            // Enumerate all code paths before deleting
14034            cleanUpResourcesLI(getAllCodePaths());
14035        }
14036
14037        private void cleanUpResourcesLI(List<String> allCodePaths) {
14038            cleanUp();
14039            removeDexFiles(allCodePaths, instructionSets);
14040        }
14041
14042        String getPackageName() {
14043            return getAsecPackageName(cid);
14044        }
14045
14046        boolean doPostDeleteLI(boolean delete) {
14047            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14048            final List<String> allCodePaths = getAllCodePaths();
14049            boolean mounted = PackageHelper.isContainerMounted(cid);
14050            if (mounted) {
14051                // Unmount first
14052                if (PackageHelper.unMountSdDir(cid)) {
14053                    mounted = false;
14054                }
14055            }
14056            if (!mounted && delete) {
14057                cleanUpResourcesLI(allCodePaths);
14058            }
14059            return !mounted;
14060        }
14061
14062        @Override
14063        int doPreCopy() {
14064            if (isFwdLocked()) {
14065                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14066                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14067                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14068                }
14069            }
14070
14071            return PackageManager.INSTALL_SUCCEEDED;
14072        }
14073
14074        @Override
14075        int doPostCopy(int uid) {
14076            if (isFwdLocked()) {
14077                if (uid < Process.FIRST_APPLICATION_UID
14078                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14079                                RES_FILE_NAME)) {
14080                    Slog.e(TAG, "Failed to finalize " + cid);
14081                    PackageHelper.destroySdDir(cid);
14082                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14083                }
14084            }
14085
14086            return PackageManager.INSTALL_SUCCEEDED;
14087        }
14088    }
14089
14090    /**
14091     * Logic to handle movement of existing installed applications.
14092     */
14093    class MoveInstallArgs extends InstallArgs {
14094        private File codeFile;
14095        private File resourceFile;
14096
14097        /** New install */
14098        MoveInstallArgs(InstallParams params) {
14099            super(params.origin, params.move, params.observer, params.installFlags,
14100                    params.installerPackageName, params.volumeUuid,
14101                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14102                    params.grantedRuntimePermissions,
14103                    params.traceMethod, params.traceCookie, params.certificates);
14104        }
14105
14106        int copyApk(IMediaContainerService imcs, boolean temp) {
14107            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14108                    + move.fromUuid + " to " + move.toUuid);
14109            synchronized (mInstaller) {
14110                try {
14111                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14112                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14113                } catch (InstallerException e) {
14114                    Slog.w(TAG, "Failed to move app", e);
14115                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14116                }
14117            }
14118
14119            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14120            resourceFile = codeFile;
14121            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14122
14123            return PackageManager.INSTALL_SUCCEEDED;
14124        }
14125
14126        int doPreInstall(int status) {
14127            if (status != PackageManager.INSTALL_SUCCEEDED) {
14128                cleanUp(move.toUuid);
14129            }
14130            return status;
14131        }
14132
14133        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14134            if (status != PackageManager.INSTALL_SUCCEEDED) {
14135                cleanUp(move.toUuid);
14136                return false;
14137            }
14138
14139            // Reflect the move in app info
14140            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14141            pkg.setApplicationInfoCodePath(pkg.codePath);
14142            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14143            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14144            pkg.setApplicationInfoResourcePath(pkg.codePath);
14145            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14146            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14147
14148            return true;
14149        }
14150
14151        int doPostInstall(int status, int uid) {
14152            if (status == PackageManager.INSTALL_SUCCEEDED) {
14153                cleanUp(move.fromUuid);
14154            } else {
14155                cleanUp(move.toUuid);
14156            }
14157            return status;
14158        }
14159
14160        @Override
14161        String getCodePath() {
14162            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14163        }
14164
14165        @Override
14166        String getResourcePath() {
14167            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14168        }
14169
14170        private boolean cleanUp(String volumeUuid) {
14171            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14172                    move.dataAppName);
14173            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14174            final int[] userIds = sUserManager.getUserIds();
14175            synchronized (mInstallLock) {
14176                // Clean up both app data and code
14177                // All package moves are frozen until finished
14178                for (int userId : userIds) {
14179                    try {
14180                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14181                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14182                    } catch (InstallerException e) {
14183                        Slog.w(TAG, String.valueOf(e));
14184                    }
14185                }
14186                removeCodePathLI(codeFile);
14187            }
14188            return true;
14189        }
14190
14191        void cleanUpResourcesLI() {
14192            throw new UnsupportedOperationException();
14193        }
14194
14195        boolean doPostDeleteLI(boolean delete) {
14196            throw new UnsupportedOperationException();
14197        }
14198    }
14199
14200    static String getAsecPackageName(String packageCid) {
14201        int idx = packageCid.lastIndexOf("-");
14202        if (idx == -1) {
14203            return packageCid;
14204        }
14205        return packageCid.substring(0, idx);
14206    }
14207
14208    // Utility method used to create code paths based on package name and available index.
14209    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14210        String idxStr = "";
14211        int idx = 1;
14212        // Fall back to default value of idx=1 if prefix is not
14213        // part of oldCodePath
14214        if (oldCodePath != null) {
14215            String subStr = oldCodePath;
14216            // Drop the suffix right away
14217            if (suffix != null && subStr.endsWith(suffix)) {
14218                subStr = subStr.substring(0, subStr.length() - suffix.length());
14219            }
14220            // If oldCodePath already contains prefix find out the
14221            // ending index to either increment or decrement.
14222            int sidx = subStr.lastIndexOf(prefix);
14223            if (sidx != -1) {
14224                subStr = subStr.substring(sidx + prefix.length());
14225                if (subStr != null) {
14226                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14227                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14228                    }
14229                    try {
14230                        idx = Integer.parseInt(subStr);
14231                        if (idx <= 1) {
14232                            idx++;
14233                        } else {
14234                            idx--;
14235                        }
14236                    } catch(NumberFormatException e) {
14237                    }
14238                }
14239            }
14240        }
14241        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14242        return prefix + idxStr;
14243    }
14244
14245    private File getNextCodePath(File targetDir, String packageName) {
14246        File result;
14247        SecureRandom random = new SecureRandom();
14248        byte[] bytes = new byte[16];
14249        do {
14250            random.nextBytes(bytes);
14251            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14252            result = new File(targetDir, packageName + "-" + suffix);
14253        } while (result.exists());
14254        return result;
14255    }
14256
14257    // Utility method that returns the relative package path with respect
14258    // to the installation directory. Like say for /data/data/com.test-1.apk
14259    // string com.test-1 is returned.
14260    static String deriveCodePathName(String codePath) {
14261        if (codePath == null) {
14262            return null;
14263        }
14264        final File codeFile = new File(codePath);
14265        final String name = codeFile.getName();
14266        if (codeFile.isDirectory()) {
14267            return name;
14268        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14269            final int lastDot = name.lastIndexOf('.');
14270            return name.substring(0, lastDot);
14271        } else {
14272            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14273            return null;
14274        }
14275    }
14276
14277    static class PackageInstalledInfo {
14278        String name;
14279        int uid;
14280        // The set of users that originally had this package installed.
14281        int[] origUsers;
14282        // The set of users that now have this package installed.
14283        int[] newUsers;
14284        PackageParser.Package pkg;
14285        int returnCode;
14286        String returnMsg;
14287        PackageRemovedInfo removedInfo;
14288        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14289
14290        public void setError(int code, String msg) {
14291            setReturnCode(code);
14292            setReturnMessage(msg);
14293            Slog.w(TAG, msg);
14294        }
14295
14296        public void setError(String msg, PackageParserException e) {
14297            setReturnCode(e.error);
14298            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14299            Slog.w(TAG, msg, e);
14300        }
14301
14302        public void setError(String msg, PackageManagerException e) {
14303            returnCode = e.error;
14304            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14305            Slog.w(TAG, msg, e);
14306        }
14307
14308        public void setReturnCode(int returnCode) {
14309            this.returnCode = returnCode;
14310            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14311            for (int i = 0; i < childCount; i++) {
14312                addedChildPackages.valueAt(i).returnCode = returnCode;
14313            }
14314        }
14315
14316        private void setReturnMessage(String returnMsg) {
14317            this.returnMsg = returnMsg;
14318            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14319            for (int i = 0; i < childCount; i++) {
14320                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14321            }
14322        }
14323
14324        // In some error cases we want to convey more info back to the observer
14325        String origPackage;
14326        String origPermission;
14327    }
14328
14329    /*
14330     * Install a non-existing package.
14331     */
14332    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14333            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14334            PackageInstalledInfo res) {
14335        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14336
14337        // Remember this for later, in case we need to rollback this install
14338        String pkgName = pkg.packageName;
14339
14340        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14341
14342        synchronized(mPackages) {
14343            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14344            if (renamedPackage != null) {
14345                // A package with the same name is already installed, though
14346                // it has been renamed to an older name.  The package we
14347                // are trying to install should be installed as an update to
14348                // the existing one, but that has not been requested, so bail.
14349                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14350                        + " without first uninstalling package running as "
14351                        + renamedPackage);
14352                return;
14353            }
14354            if (mPackages.containsKey(pkgName)) {
14355                // Don't allow installation over an existing package with the same name.
14356                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14357                        + " without first uninstalling.");
14358                return;
14359            }
14360        }
14361
14362        try {
14363            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14364                    System.currentTimeMillis(), user);
14365
14366            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14367
14368            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14369                prepareAppDataAfterInstallLIF(newPackage);
14370
14371            } else {
14372                // Remove package from internal structures, but keep around any
14373                // data that might have already existed
14374                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14375                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14376            }
14377        } catch (PackageManagerException e) {
14378            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14379        }
14380
14381        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14382    }
14383
14384    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14385        // Can't rotate keys during boot or if sharedUser.
14386        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14387                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14388            return false;
14389        }
14390        // app is using upgradeKeySets; make sure all are valid
14391        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14392        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14393        for (int i = 0; i < upgradeKeySets.length; i++) {
14394            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14395                Slog.wtf(TAG, "Package "
14396                         + (oldPs.name != null ? oldPs.name : "<null>")
14397                         + " contains upgrade-key-set reference to unknown key-set: "
14398                         + upgradeKeySets[i]
14399                         + " reverting to signatures check.");
14400                return false;
14401            }
14402        }
14403        return true;
14404    }
14405
14406    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14407        // Upgrade keysets are being used.  Determine if new package has a superset of the
14408        // required keys.
14409        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14410        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14411        for (int i = 0; i < upgradeKeySets.length; i++) {
14412            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14413            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14414                return true;
14415            }
14416        }
14417        return false;
14418    }
14419
14420    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14421        try (DigestInputStream digestStream =
14422                new DigestInputStream(new FileInputStream(file), digest)) {
14423            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14424        }
14425    }
14426
14427    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14428            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14429        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14430
14431        final PackageParser.Package oldPackage;
14432        final String pkgName = pkg.packageName;
14433        final int[] allUsers;
14434        final int[] installedUsers;
14435
14436        synchronized(mPackages) {
14437            oldPackage = mPackages.get(pkgName);
14438            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14439
14440            // don't allow upgrade to target a release SDK from a pre-release SDK
14441            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14442                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14443            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14444                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14445            if (oldTargetsPreRelease
14446                    && !newTargetsPreRelease
14447                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14448                Slog.w(TAG, "Can't install package targeting released sdk");
14449                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14450                return;
14451            }
14452
14453            // don't allow an upgrade from full to ephemeral
14454            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14455            if (isEphemeral && !oldIsEphemeral) {
14456                // can't downgrade from full to ephemeral
14457                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14458                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14459                return;
14460            }
14461
14462            // verify signatures are valid
14463            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14464            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14465                if (!checkUpgradeKeySetLP(ps, pkg)) {
14466                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14467                            "New package not signed by keys specified by upgrade-keysets: "
14468                                    + pkgName);
14469                    return;
14470                }
14471            } else {
14472                // default to original signature matching
14473                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14474                        != PackageManager.SIGNATURE_MATCH) {
14475                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14476                            "New package has a different signature: " + pkgName);
14477                    return;
14478                }
14479            }
14480
14481            // don't allow a system upgrade unless the upgrade hash matches
14482            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14483                byte[] digestBytes = null;
14484                try {
14485                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14486                    updateDigest(digest, new File(pkg.baseCodePath));
14487                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14488                        for (String path : pkg.splitCodePaths) {
14489                            updateDigest(digest, new File(path));
14490                        }
14491                    }
14492                    digestBytes = digest.digest();
14493                } catch (NoSuchAlgorithmException | IOException e) {
14494                    res.setError(INSTALL_FAILED_INVALID_APK,
14495                            "Could not compute hash: " + pkgName);
14496                    return;
14497                }
14498                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14499                    res.setError(INSTALL_FAILED_INVALID_APK,
14500                            "New package fails restrict-update check: " + pkgName);
14501                    return;
14502                }
14503                // retain upgrade restriction
14504                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14505            }
14506
14507            // Check for shared user id changes
14508            String invalidPackageName =
14509                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14510            if (invalidPackageName != null) {
14511                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14512                        "Package " + invalidPackageName + " tried to change user "
14513                                + oldPackage.mSharedUserId);
14514                return;
14515            }
14516
14517            // In case of rollback, remember per-user/profile install state
14518            allUsers = sUserManager.getUserIds();
14519            installedUsers = ps.queryInstalledUsers(allUsers, true);
14520        }
14521
14522        // Update what is removed
14523        res.removedInfo = new PackageRemovedInfo();
14524        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14525        res.removedInfo.removedPackage = oldPackage.packageName;
14526        res.removedInfo.isUpdate = true;
14527        res.removedInfo.origUsers = installedUsers;
14528        final int childCount = (oldPackage.childPackages != null)
14529                ? oldPackage.childPackages.size() : 0;
14530        for (int i = 0; i < childCount; i++) {
14531            boolean childPackageUpdated = false;
14532            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14533            if (res.addedChildPackages != null) {
14534                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14535                if (childRes != null) {
14536                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14537                    childRes.removedInfo.removedPackage = childPkg.packageName;
14538                    childRes.removedInfo.isUpdate = true;
14539                    childPackageUpdated = true;
14540                }
14541            }
14542            if (!childPackageUpdated) {
14543                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14544                childRemovedRes.removedPackage = childPkg.packageName;
14545                childRemovedRes.isUpdate = false;
14546                childRemovedRes.dataRemoved = true;
14547                synchronized (mPackages) {
14548                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14549                    if (childPs != null) {
14550                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14551                    }
14552                }
14553                if (res.removedInfo.removedChildPackages == null) {
14554                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14555                }
14556                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14557            }
14558        }
14559
14560        boolean sysPkg = (isSystemApp(oldPackage));
14561        if (sysPkg) {
14562            // Set the system/privileged flags as needed
14563            final boolean privileged =
14564                    (oldPackage.applicationInfo.privateFlags
14565                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14566            final int systemPolicyFlags = policyFlags
14567                    | PackageParser.PARSE_IS_SYSTEM
14568                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14569
14570            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14571                    user, allUsers, installerPackageName, res);
14572        } else {
14573            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14574                    user, allUsers, installerPackageName, res);
14575        }
14576    }
14577
14578    public List<String> getPreviousCodePaths(String packageName) {
14579        final PackageSetting ps = mSettings.mPackages.get(packageName);
14580        final List<String> result = new ArrayList<String>();
14581        if (ps != null && ps.oldCodePaths != null) {
14582            result.addAll(ps.oldCodePaths);
14583        }
14584        return result;
14585    }
14586
14587    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14588            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14589            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14590        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14591                + deletedPackage);
14592
14593        String pkgName = deletedPackage.packageName;
14594        boolean deletedPkg = true;
14595        boolean addedPkg = false;
14596        boolean updatedSettings = false;
14597        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14598        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14599                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14600
14601        final long origUpdateTime = (pkg.mExtras != null)
14602                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14603
14604        // First delete the existing package while retaining the data directory
14605        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14606                res.removedInfo, true, pkg)) {
14607            // If the existing package wasn't successfully deleted
14608            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14609            deletedPkg = false;
14610        } else {
14611            // Successfully deleted the old package; proceed with replace.
14612
14613            // If deleted package lived in a container, give users a chance to
14614            // relinquish resources before killing.
14615            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14616                if (DEBUG_INSTALL) {
14617                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14618                }
14619                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14620                final ArrayList<String> pkgList = new ArrayList<String>(1);
14621                pkgList.add(deletedPackage.applicationInfo.packageName);
14622                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14623            }
14624
14625            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14626                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14627            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14628
14629            try {
14630                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14631                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14632                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14633
14634                // Update the in-memory copy of the previous code paths.
14635                PackageSetting ps = mSettings.mPackages.get(pkgName);
14636                if (!killApp) {
14637                    if (ps.oldCodePaths == null) {
14638                        ps.oldCodePaths = new ArraySet<>();
14639                    }
14640                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14641                    if (deletedPackage.splitCodePaths != null) {
14642                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14643                    }
14644                } else {
14645                    ps.oldCodePaths = null;
14646                }
14647                if (ps.childPackageNames != null) {
14648                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14649                        final String childPkgName = ps.childPackageNames.get(i);
14650                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14651                        childPs.oldCodePaths = ps.oldCodePaths;
14652                    }
14653                }
14654                prepareAppDataAfterInstallLIF(newPackage);
14655                addedPkg = true;
14656            } catch (PackageManagerException e) {
14657                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14658            }
14659        }
14660
14661        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14662            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14663
14664            // Revert all internal state mutations and added folders for the failed install
14665            if (addedPkg) {
14666                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14667                        res.removedInfo, true, null);
14668            }
14669
14670            // Restore the old package
14671            if (deletedPkg) {
14672                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14673                File restoreFile = new File(deletedPackage.codePath);
14674                // Parse old package
14675                boolean oldExternal = isExternal(deletedPackage);
14676                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14677                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14678                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14679                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14680                try {
14681                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14682                            null);
14683                } catch (PackageManagerException e) {
14684                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14685                            + e.getMessage());
14686                    return;
14687                }
14688
14689                synchronized (mPackages) {
14690                    // Ensure the installer package name up to date
14691                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14692
14693                    // Update permissions for restored package
14694                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14695
14696                    mSettings.writeLPr();
14697                }
14698
14699                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14700            }
14701        } else {
14702            synchronized (mPackages) {
14703                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
14704                if (ps != null) {
14705                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14706                    if (res.removedInfo.removedChildPackages != null) {
14707                        final int childCount = res.removedInfo.removedChildPackages.size();
14708                        // Iterate in reverse as we may modify the collection
14709                        for (int i = childCount - 1; i >= 0; i--) {
14710                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14711                            if (res.addedChildPackages.containsKey(childPackageName)) {
14712                                res.removedInfo.removedChildPackages.removeAt(i);
14713                            } else {
14714                                PackageRemovedInfo childInfo = res.removedInfo
14715                                        .removedChildPackages.valueAt(i);
14716                                childInfo.removedForAllUsers = mPackages.get(
14717                                        childInfo.removedPackage) == null;
14718                            }
14719                        }
14720                    }
14721                }
14722            }
14723        }
14724    }
14725
14726    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14727            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14728            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14729        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14730                + ", old=" + deletedPackage);
14731
14732        final boolean disabledSystem;
14733
14734        // Remove existing system package
14735        removePackageLI(deletedPackage, true);
14736
14737        synchronized (mPackages) {
14738            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14739        }
14740        if (!disabledSystem) {
14741            // We didn't need to disable the .apk as a current system package,
14742            // which means we are replacing another update that is already
14743            // installed.  We need to make sure to delete the older one's .apk.
14744            res.removedInfo.args = createInstallArgsForExisting(0,
14745                    deletedPackage.applicationInfo.getCodePath(),
14746                    deletedPackage.applicationInfo.getResourcePath(),
14747                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14748        } else {
14749            res.removedInfo.args = null;
14750        }
14751
14752        // Successfully disabled the old package. Now proceed with re-installation
14753        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14754                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14755        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14756
14757        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14758        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14759                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14760
14761        PackageParser.Package newPackage = null;
14762        try {
14763            // Add the package to the internal data structures
14764            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14765
14766            // Set the update and install times
14767            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14768            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14769                    System.currentTimeMillis());
14770
14771            // Update the package dynamic state if succeeded
14772            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14773                // Now that the install succeeded make sure we remove data
14774                // directories for any child package the update removed.
14775                final int deletedChildCount = (deletedPackage.childPackages != null)
14776                        ? deletedPackage.childPackages.size() : 0;
14777                final int newChildCount = (newPackage.childPackages != null)
14778                        ? newPackage.childPackages.size() : 0;
14779                for (int i = 0; i < deletedChildCount; i++) {
14780                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14781                    boolean childPackageDeleted = true;
14782                    for (int j = 0; j < newChildCount; j++) {
14783                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14784                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14785                            childPackageDeleted = false;
14786                            break;
14787                        }
14788                    }
14789                    if (childPackageDeleted) {
14790                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14791                                deletedChildPkg.packageName);
14792                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14793                            PackageRemovedInfo removedChildRes = res.removedInfo
14794                                    .removedChildPackages.get(deletedChildPkg.packageName);
14795                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14796                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14797                        }
14798                    }
14799                }
14800
14801                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14802                prepareAppDataAfterInstallLIF(newPackage);
14803            }
14804        } catch (PackageManagerException e) {
14805            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14806            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14807        }
14808
14809        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14810            // Re installation failed. Restore old information
14811            // Remove new pkg information
14812            if (newPackage != null) {
14813                removeInstalledPackageLI(newPackage, true);
14814            }
14815            // Add back the old system package
14816            try {
14817                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14818            } catch (PackageManagerException e) {
14819                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14820            }
14821
14822            synchronized (mPackages) {
14823                if (disabledSystem) {
14824                    enableSystemPackageLPw(deletedPackage);
14825                }
14826
14827                // Ensure the installer package name up to date
14828                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14829
14830                // Update permissions for restored package
14831                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14832
14833                mSettings.writeLPr();
14834            }
14835
14836            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14837                    + " after failed upgrade");
14838        }
14839    }
14840
14841    /**
14842     * Checks whether the parent or any of the child packages have a change shared
14843     * user. For a package to be a valid update the shred users of the parent and
14844     * the children should match. We may later support changing child shared users.
14845     * @param oldPkg The updated package.
14846     * @param newPkg The update package.
14847     * @return The shared user that change between the versions.
14848     */
14849    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14850            PackageParser.Package newPkg) {
14851        // Check parent shared user
14852        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14853            return newPkg.packageName;
14854        }
14855        // Check child shared users
14856        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14857        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14858        for (int i = 0; i < newChildCount; i++) {
14859            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14860            // If this child was present, did it have the same shared user?
14861            for (int j = 0; j < oldChildCount; j++) {
14862                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14863                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14864                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14865                    return newChildPkg.packageName;
14866                }
14867            }
14868        }
14869        return null;
14870    }
14871
14872    private void removeNativeBinariesLI(PackageSetting ps) {
14873        // Remove the lib path for the parent package
14874        if (ps != null) {
14875            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14876            // Remove the lib path for the child packages
14877            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14878            for (int i = 0; i < childCount; i++) {
14879                PackageSetting childPs = null;
14880                synchronized (mPackages) {
14881                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
14882                }
14883                if (childPs != null) {
14884                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14885                            .legacyNativeLibraryPathString);
14886                }
14887            }
14888        }
14889    }
14890
14891    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14892        // Enable the parent package
14893        mSettings.enableSystemPackageLPw(pkg.packageName);
14894        // Enable the child packages
14895        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14896        for (int i = 0; i < childCount; i++) {
14897            PackageParser.Package childPkg = pkg.childPackages.get(i);
14898            mSettings.enableSystemPackageLPw(childPkg.packageName);
14899        }
14900    }
14901
14902    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14903            PackageParser.Package newPkg) {
14904        // Disable the parent package (parent always replaced)
14905        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14906        // Disable the child packages
14907        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14908        for (int i = 0; i < childCount; i++) {
14909            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14910            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14911            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14912        }
14913        return disabled;
14914    }
14915
14916    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14917            String installerPackageName) {
14918        // Enable the parent package
14919        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14920        // Enable the child packages
14921        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14922        for (int i = 0; i < childCount; i++) {
14923            PackageParser.Package childPkg = pkg.childPackages.get(i);
14924            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14925        }
14926    }
14927
14928    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14929        // Collect all used permissions in the UID
14930        ArraySet<String> usedPermissions = new ArraySet<>();
14931        final int packageCount = su.packages.size();
14932        for (int i = 0; i < packageCount; i++) {
14933            PackageSetting ps = su.packages.valueAt(i);
14934            if (ps.pkg == null) {
14935                continue;
14936            }
14937            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14938            for (int j = 0; j < requestedPermCount; j++) {
14939                String permission = ps.pkg.requestedPermissions.get(j);
14940                BasePermission bp = mSettings.mPermissions.get(permission);
14941                if (bp != null) {
14942                    usedPermissions.add(permission);
14943                }
14944            }
14945        }
14946
14947        PermissionsState permissionsState = su.getPermissionsState();
14948        // Prune install permissions
14949        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14950        final int installPermCount = installPermStates.size();
14951        for (int i = installPermCount - 1; i >= 0;  i--) {
14952            PermissionState permissionState = installPermStates.get(i);
14953            if (!usedPermissions.contains(permissionState.getName())) {
14954                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14955                if (bp != null) {
14956                    permissionsState.revokeInstallPermission(bp);
14957                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14958                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14959                }
14960            }
14961        }
14962
14963        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14964
14965        // Prune runtime permissions
14966        for (int userId : allUserIds) {
14967            List<PermissionState> runtimePermStates = permissionsState
14968                    .getRuntimePermissionStates(userId);
14969            final int runtimePermCount = runtimePermStates.size();
14970            for (int i = runtimePermCount - 1; i >= 0; i--) {
14971                PermissionState permissionState = runtimePermStates.get(i);
14972                if (!usedPermissions.contains(permissionState.getName())) {
14973                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14974                    if (bp != null) {
14975                        permissionsState.revokeRuntimePermission(bp, userId);
14976                        permissionsState.updatePermissionFlags(bp, userId,
14977                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14978                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14979                                runtimePermissionChangedUserIds, userId);
14980                    }
14981                }
14982            }
14983        }
14984
14985        return runtimePermissionChangedUserIds;
14986    }
14987
14988    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14989            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14990        // Update the parent package setting
14991        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14992                res, user);
14993        // Update the child packages setting
14994        final int childCount = (newPackage.childPackages != null)
14995                ? newPackage.childPackages.size() : 0;
14996        for (int i = 0; i < childCount; i++) {
14997            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14998            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14999            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15000                    childRes.origUsers, childRes, user);
15001        }
15002    }
15003
15004    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15005            String installerPackageName, int[] allUsers, int[] installedForUsers,
15006            PackageInstalledInfo res, UserHandle user) {
15007        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15008
15009        String pkgName = newPackage.packageName;
15010        synchronized (mPackages) {
15011            //write settings. the installStatus will be incomplete at this stage.
15012            //note that the new package setting would have already been
15013            //added to mPackages. It hasn't been persisted yet.
15014            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15015            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15016            mSettings.writeLPr();
15017            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15018        }
15019
15020        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15021        synchronized (mPackages) {
15022            updatePermissionsLPw(newPackage.packageName, newPackage,
15023                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15024                            ? UPDATE_PERMISSIONS_ALL : 0));
15025            // For system-bundled packages, we assume that installing an upgraded version
15026            // of the package implies that the user actually wants to run that new code,
15027            // so we enable the package.
15028            PackageSetting ps = mSettings.mPackages.get(pkgName);
15029            final int userId = user.getIdentifier();
15030            if (ps != null) {
15031                if (isSystemApp(newPackage)) {
15032                    if (DEBUG_INSTALL) {
15033                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15034                    }
15035                    // Enable system package for requested users
15036                    if (res.origUsers != null) {
15037                        for (int origUserId : res.origUsers) {
15038                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15039                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15040                                        origUserId, installerPackageName);
15041                            }
15042                        }
15043                    }
15044                    // Also convey the prior install/uninstall state
15045                    if (allUsers != null && installedForUsers != null) {
15046                        for (int currentUserId : allUsers) {
15047                            final boolean installed = ArrayUtils.contains(
15048                                    installedForUsers, currentUserId);
15049                            if (DEBUG_INSTALL) {
15050                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15051                            }
15052                            ps.setInstalled(installed, currentUserId);
15053                        }
15054                        // these install state changes will be persisted in the
15055                        // upcoming call to mSettings.writeLPr().
15056                    }
15057                }
15058                // It's implied that when a user requests installation, they want the app to be
15059                // installed and enabled.
15060                if (userId != UserHandle.USER_ALL) {
15061                    ps.setInstalled(true, userId);
15062                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15063                }
15064            }
15065            res.name = pkgName;
15066            res.uid = newPackage.applicationInfo.uid;
15067            res.pkg = newPackage;
15068            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15069            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15070            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15071            //to update install status
15072            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15073            mSettings.writeLPr();
15074            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15075        }
15076
15077        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15078    }
15079
15080    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15081        try {
15082            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15083            installPackageLI(args, res);
15084        } finally {
15085            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15086        }
15087    }
15088
15089    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15090        final int installFlags = args.installFlags;
15091        final String installerPackageName = args.installerPackageName;
15092        final String volumeUuid = args.volumeUuid;
15093        final File tmpPackageFile = new File(args.getCodePath());
15094        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15095        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15096                || (args.volumeUuid != null));
15097        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15098        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15099        boolean replace = false;
15100        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15101        if (args.move != null) {
15102            // moving a complete application; perform an initial scan on the new install location
15103            scanFlags |= SCAN_INITIAL;
15104        }
15105        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15106            scanFlags |= SCAN_DONT_KILL_APP;
15107        }
15108
15109        // Result object to be returned
15110        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15111
15112        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15113
15114        // Sanity check
15115        if (ephemeral && (forwardLocked || onExternal)) {
15116            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15117                    + " external=" + onExternal);
15118            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15119            return;
15120        }
15121
15122        // Retrieve PackageSettings and parse package
15123        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15124                | PackageParser.PARSE_ENFORCE_CODE
15125                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15126                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15127                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15128                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15129        PackageParser pp = new PackageParser();
15130        pp.setSeparateProcesses(mSeparateProcesses);
15131        pp.setDisplayMetrics(mMetrics);
15132
15133        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15134        final PackageParser.Package pkg;
15135        try {
15136            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15137        } catch (PackageParserException e) {
15138            res.setError("Failed parse during installPackageLI", e);
15139            return;
15140        } finally {
15141            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15142        }
15143
15144        // If we are installing a clustered package add results for the children
15145        if (pkg.childPackages != null) {
15146            synchronized (mPackages) {
15147                final int childCount = pkg.childPackages.size();
15148                for (int i = 0; i < childCount; i++) {
15149                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15150                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15151                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15152                    childRes.pkg = childPkg;
15153                    childRes.name = childPkg.packageName;
15154                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15155                    if (childPs != null) {
15156                        childRes.origUsers = childPs.queryInstalledUsers(
15157                                sUserManager.getUserIds(), true);
15158                    }
15159                    if ((mPackages.containsKey(childPkg.packageName))) {
15160                        childRes.removedInfo = new PackageRemovedInfo();
15161                        childRes.removedInfo.removedPackage = childPkg.packageName;
15162                    }
15163                    if (res.addedChildPackages == null) {
15164                        res.addedChildPackages = new ArrayMap<>();
15165                    }
15166                    res.addedChildPackages.put(childPkg.packageName, childRes);
15167                }
15168            }
15169        }
15170
15171        // If package doesn't declare API override, mark that we have an install
15172        // time CPU ABI override.
15173        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15174            pkg.cpuAbiOverride = args.abiOverride;
15175        }
15176
15177        String pkgName = res.name = pkg.packageName;
15178        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15179            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15180                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15181                return;
15182            }
15183        }
15184
15185        try {
15186            // either use what we've been given or parse directly from the APK
15187            if (args.certificates != null) {
15188                try {
15189                    PackageParser.populateCertificates(pkg, args.certificates);
15190                } catch (PackageParserException e) {
15191                    // there was something wrong with the certificates we were given;
15192                    // try to pull them from the APK
15193                    PackageParser.collectCertificates(pkg, parseFlags);
15194                }
15195            } else {
15196                PackageParser.collectCertificates(pkg, parseFlags);
15197            }
15198        } catch (PackageParserException e) {
15199            res.setError("Failed collect during installPackageLI", e);
15200            return;
15201        }
15202
15203        // Get rid of all references to package scan path via parser.
15204        pp = null;
15205        String oldCodePath = null;
15206        boolean systemApp = false;
15207        synchronized (mPackages) {
15208            // Check if installing already existing package
15209            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15210                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15211                if (pkg.mOriginalPackages != null
15212                        && pkg.mOriginalPackages.contains(oldName)
15213                        && mPackages.containsKey(oldName)) {
15214                    // This package is derived from an original package,
15215                    // and this device has been updating from that original
15216                    // name.  We must continue using the original name, so
15217                    // rename the new package here.
15218                    pkg.setPackageName(oldName);
15219                    pkgName = pkg.packageName;
15220                    replace = true;
15221                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15222                            + oldName + " pkgName=" + pkgName);
15223                } else if (mPackages.containsKey(pkgName)) {
15224                    // This package, under its official name, already exists
15225                    // on the device; we should replace it.
15226                    replace = true;
15227                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15228                }
15229
15230                // Child packages are installed through the parent package
15231                if (pkg.parentPackage != null) {
15232                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15233                            "Package " + pkg.packageName + " is child of package "
15234                                    + pkg.parentPackage.parentPackage + ". Child packages "
15235                                    + "can be updated only through the parent package.");
15236                    return;
15237                }
15238
15239                if (replace) {
15240                    // Prevent apps opting out from runtime permissions
15241                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15242                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15243                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15244                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15245                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15246                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15247                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15248                                        + " doesn't support runtime permissions but the old"
15249                                        + " target SDK " + oldTargetSdk + " does.");
15250                        return;
15251                    }
15252
15253                    // Prevent installing of child packages
15254                    if (oldPackage.parentPackage != null) {
15255                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15256                                "Package " + pkg.packageName + " is child of package "
15257                                        + oldPackage.parentPackage + ". Child packages "
15258                                        + "can be updated only through the parent package.");
15259                        return;
15260                    }
15261                }
15262            }
15263
15264            PackageSetting ps = mSettings.mPackages.get(pkgName);
15265            if (ps != null) {
15266                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15267
15268                // Quick sanity check that we're signed correctly if updating;
15269                // we'll check this again later when scanning, but we want to
15270                // bail early here before tripping over redefined permissions.
15271                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15272                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15273                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15274                                + pkg.packageName + " upgrade keys do not match the "
15275                                + "previously installed version");
15276                        return;
15277                    }
15278                } else {
15279                    try {
15280                        verifySignaturesLP(ps, pkg);
15281                    } catch (PackageManagerException e) {
15282                        res.setError(e.error, e.getMessage());
15283                        return;
15284                    }
15285                }
15286
15287                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15288                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15289                    systemApp = (ps.pkg.applicationInfo.flags &
15290                            ApplicationInfo.FLAG_SYSTEM) != 0;
15291                }
15292                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15293            }
15294
15295            // Check whether the newly-scanned package wants to define an already-defined perm
15296            int N = pkg.permissions.size();
15297            for (int i = N-1; i >= 0; i--) {
15298                PackageParser.Permission perm = pkg.permissions.get(i);
15299                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15300                if (bp != null) {
15301                    // If the defining package is signed with our cert, it's okay.  This
15302                    // also includes the "updating the same package" case, of course.
15303                    // "updating same package" could also involve key-rotation.
15304                    final boolean sigsOk;
15305                    if (bp.sourcePackage.equals(pkg.packageName)
15306                            && (bp.packageSetting instanceof PackageSetting)
15307                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15308                                    scanFlags))) {
15309                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15310                    } else {
15311                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15312                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15313                    }
15314                    if (!sigsOk) {
15315                        // If the owning package is the system itself, we log but allow
15316                        // install to proceed; we fail the install on all other permission
15317                        // redefinitions.
15318                        if (!bp.sourcePackage.equals("android")) {
15319                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15320                                    + pkg.packageName + " attempting to redeclare permission "
15321                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15322                            res.origPermission = perm.info.name;
15323                            res.origPackage = bp.sourcePackage;
15324                            return;
15325                        } else {
15326                            Slog.w(TAG, "Package " + pkg.packageName
15327                                    + " attempting to redeclare system permission "
15328                                    + perm.info.name + "; ignoring new declaration");
15329                            pkg.permissions.remove(i);
15330                        }
15331                    }
15332                }
15333            }
15334        }
15335
15336        if (systemApp) {
15337            if (onExternal) {
15338                // Abort update; system app can't be replaced with app on sdcard
15339                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15340                        "Cannot install updates to system apps on sdcard");
15341                return;
15342            } else if (ephemeral) {
15343                // Abort update; system app can't be replaced with an ephemeral app
15344                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15345                        "Cannot update a system app with an ephemeral app");
15346                return;
15347            }
15348        }
15349
15350        if (args.move != null) {
15351            // We did an in-place move, so dex is ready to roll
15352            scanFlags |= SCAN_NO_DEX;
15353            scanFlags |= SCAN_MOVE;
15354
15355            synchronized (mPackages) {
15356                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15357                if (ps == null) {
15358                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15359                            "Missing settings for moved package " + pkgName);
15360                }
15361
15362                // We moved the entire application as-is, so bring over the
15363                // previously derived ABI information.
15364                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15365                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15366            }
15367
15368        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15369            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15370            scanFlags |= SCAN_NO_DEX;
15371
15372            try {
15373                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15374                    args.abiOverride : pkg.cpuAbiOverride);
15375                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15376                        true /*extractLibs*/, mAppLib32InstallDir);
15377            } catch (PackageManagerException pme) {
15378                Slog.e(TAG, "Error deriving application ABI", pme);
15379                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15380                return;
15381            }
15382
15383            // Shared libraries for the package need to be updated.
15384            synchronized (mPackages) {
15385                try {
15386                    updateSharedLibrariesLPr(pkg, null);
15387                } catch (PackageManagerException e) {
15388                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15389                }
15390            }
15391            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15392            // Do not run PackageDexOptimizer through the local performDexOpt
15393            // method because `pkg` may not be in `mPackages` yet.
15394            //
15395            // Also, don't fail application installs if the dexopt step fails.
15396            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15397                    null /* instructionSets */, false /* checkProfiles */,
15398                    getCompilerFilterForReason(REASON_INSTALL),
15399                    getOrCreateCompilerPackageStats(pkg));
15400            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15401
15402            // Notify BackgroundDexOptService that the package has been changed.
15403            // If this is an update of a package which used to fail to compile,
15404            // BDOS will remove it from its blacklist.
15405            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15406        }
15407
15408        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15409            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15410            return;
15411        }
15412
15413        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15414
15415        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15416                "installPackageLI")) {
15417            if (replace) {
15418                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15419                        installerPackageName, res);
15420            } else {
15421                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15422                        args.user, installerPackageName, volumeUuid, res);
15423            }
15424        }
15425        synchronized (mPackages) {
15426            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15427            if (ps != null) {
15428                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15429            }
15430
15431            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15432            for (int i = 0; i < childCount; i++) {
15433                PackageParser.Package childPkg = pkg.childPackages.get(i);
15434                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15435                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15436                if (childPs != null) {
15437                    childRes.newUsers = childPs.queryInstalledUsers(
15438                            sUserManager.getUserIds(), true);
15439                }
15440            }
15441        }
15442    }
15443
15444    private void startIntentFilterVerifications(int userId, boolean replacing,
15445            PackageParser.Package pkg) {
15446        if (mIntentFilterVerifierComponent == null) {
15447            Slog.w(TAG, "No IntentFilter verification will not be done as "
15448                    + "there is no IntentFilterVerifier available!");
15449            return;
15450        }
15451
15452        final int verifierUid = getPackageUid(
15453                mIntentFilterVerifierComponent.getPackageName(),
15454                MATCH_DEBUG_TRIAGED_MISSING,
15455                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15456
15457        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15458        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15459        mHandler.sendMessage(msg);
15460
15461        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15462        for (int i = 0; i < childCount; i++) {
15463            PackageParser.Package childPkg = pkg.childPackages.get(i);
15464            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15465            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15466            mHandler.sendMessage(msg);
15467        }
15468    }
15469
15470    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15471            PackageParser.Package pkg) {
15472        int size = pkg.activities.size();
15473        if (size == 0) {
15474            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15475                    "No activity, so no need to verify any IntentFilter!");
15476            return;
15477        }
15478
15479        final boolean hasDomainURLs = hasDomainURLs(pkg);
15480        if (!hasDomainURLs) {
15481            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15482                    "No domain URLs, so no need to verify any IntentFilter!");
15483            return;
15484        }
15485
15486        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15487                + " if any IntentFilter from the " + size
15488                + " Activities needs verification ...");
15489
15490        int count = 0;
15491        final String packageName = pkg.packageName;
15492
15493        synchronized (mPackages) {
15494            // If this is a new install and we see that we've already run verification for this
15495            // package, we have nothing to do: it means the state was restored from backup.
15496            if (!replacing) {
15497                IntentFilterVerificationInfo ivi =
15498                        mSettings.getIntentFilterVerificationLPr(packageName);
15499                if (ivi != null) {
15500                    if (DEBUG_DOMAIN_VERIFICATION) {
15501                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15502                                + ivi.getStatusString());
15503                    }
15504                    return;
15505                }
15506            }
15507
15508            // If any filters need to be verified, then all need to be.
15509            boolean needToVerify = false;
15510            for (PackageParser.Activity a : pkg.activities) {
15511                for (ActivityIntentInfo filter : a.intents) {
15512                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15513                        if (DEBUG_DOMAIN_VERIFICATION) {
15514                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15515                        }
15516                        needToVerify = true;
15517                        break;
15518                    }
15519                }
15520            }
15521
15522            if (needToVerify) {
15523                final int verificationId = mIntentFilterVerificationToken++;
15524                for (PackageParser.Activity a : pkg.activities) {
15525                    for (ActivityIntentInfo filter : a.intents) {
15526                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15527                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15528                                    "Verification needed for IntentFilter:" + filter.toString());
15529                            mIntentFilterVerifier.addOneIntentFilterVerification(
15530                                    verifierUid, userId, verificationId, filter, packageName);
15531                            count++;
15532                        }
15533                    }
15534                }
15535            }
15536        }
15537
15538        if (count > 0) {
15539            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15540                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15541                    +  " for userId:" + userId);
15542            mIntentFilterVerifier.startVerifications(userId);
15543        } else {
15544            if (DEBUG_DOMAIN_VERIFICATION) {
15545                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15546            }
15547        }
15548    }
15549
15550    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15551        final ComponentName cn  = filter.activity.getComponentName();
15552        final String packageName = cn.getPackageName();
15553
15554        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15555                packageName);
15556        if (ivi == null) {
15557            return true;
15558        }
15559        int status = ivi.getStatus();
15560        switch (status) {
15561            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15562            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15563                return true;
15564
15565            default:
15566                // Nothing to do
15567                return false;
15568        }
15569    }
15570
15571    private static boolean isMultiArch(ApplicationInfo info) {
15572        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15573    }
15574
15575    private static boolean isExternal(PackageParser.Package pkg) {
15576        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15577    }
15578
15579    private static boolean isExternal(PackageSetting ps) {
15580        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15581    }
15582
15583    private static boolean isEphemeral(PackageParser.Package pkg) {
15584        return pkg.applicationInfo.isEphemeralApp();
15585    }
15586
15587    private static boolean isEphemeral(PackageSetting ps) {
15588        return ps.pkg != null && isEphemeral(ps.pkg);
15589    }
15590
15591    private static boolean isSystemApp(PackageParser.Package pkg) {
15592        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15593    }
15594
15595    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15596        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15597    }
15598
15599    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15600        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15601    }
15602
15603    private static boolean isSystemApp(PackageSetting ps) {
15604        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15605    }
15606
15607    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15608        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15609    }
15610
15611    private int packageFlagsToInstallFlags(PackageSetting ps) {
15612        int installFlags = 0;
15613        if (isEphemeral(ps)) {
15614            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15615        }
15616        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15617            // This existing package was an external ASEC install when we have
15618            // the external flag without a UUID
15619            installFlags |= PackageManager.INSTALL_EXTERNAL;
15620        }
15621        if (ps.isForwardLocked()) {
15622            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15623        }
15624        return installFlags;
15625    }
15626
15627    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15628        if (isExternal(pkg)) {
15629            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15630                return StorageManager.UUID_PRIMARY_PHYSICAL;
15631            } else {
15632                return pkg.volumeUuid;
15633            }
15634        } else {
15635            return StorageManager.UUID_PRIVATE_INTERNAL;
15636        }
15637    }
15638
15639    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15640        if (isExternal(pkg)) {
15641            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15642                return mSettings.getExternalVersion();
15643            } else {
15644                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15645            }
15646        } else {
15647            return mSettings.getInternalVersion();
15648        }
15649    }
15650
15651    private void deleteTempPackageFiles() {
15652        final FilenameFilter filter = new FilenameFilter() {
15653            public boolean accept(File dir, String name) {
15654                return name.startsWith("vmdl") && name.endsWith(".tmp");
15655            }
15656        };
15657        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15658            file.delete();
15659        }
15660    }
15661
15662    @Override
15663    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15664            int flags) {
15665        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15666                flags);
15667    }
15668
15669    @Override
15670    public void deletePackage(final String packageName,
15671            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15672        mContext.enforceCallingOrSelfPermission(
15673                android.Manifest.permission.DELETE_PACKAGES, null);
15674        Preconditions.checkNotNull(packageName);
15675        Preconditions.checkNotNull(observer);
15676        final int uid = Binder.getCallingUid();
15677        if (!isOrphaned(packageName)
15678                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15679            try {
15680                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15681                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15682                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15683                observer.onUserActionRequired(intent);
15684            } catch (RemoteException re) {
15685            }
15686            return;
15687        }
15688        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15689        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15690        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15691            mContext.enforceCallingOrSelfPermission(
15692                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15693                    "deletePackage for user " + userId);
15694        }
15695
15696        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15697            try {
15698                observer.onPackageDeleted(packageName,
15699                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15700            } catch (RemoteException re) {
15701            }
15702            return;
15703        }
15704
15705        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15706            try {
15707                observer.onPackageDeleted(packageName,
15708                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15709            } catch (RemoteException re) {
15710            }
15711            return;
15712        }
15713
15714        if (DEBUG_REMOVE) {
15715            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15716                    + " deleteAllUsers: " + deleteAllUsers );
15717        }
15718        // Queue up an async operation since the package deletion may take a little while.
15719        mHandler.post(new Runnable() {
15720            public void run() {
15721                mHandler.removeCallbacks(this);
15722                int returnCode;
15723                if (!deleteAllUsers) {
15724                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15725                } else {
15726                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15727                    // If nobody is blocking uninstall, proceed with delete for all users
15728                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15729                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15730                    } else {
15731                        // Otherwise uninstall individually for users with blockUninstalls=false
15732                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15733                        for (int userId : users) {
15734                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15735                                returnCode = deletePackageX(packageName, userId, userFlags);
15736                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15737                                    Slog.w(TAG, "Package delete failed for user " + userId
15738                                            + ", returnCode " + returnCode);
15739                                }
15740                            }
15741                        }
15742                        // The app has only been marked uninstalled for certain users.
15743                        // We still need to report that delete was blocked
15744                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15745                    }
15746                }
15747                try {
15748                    observer.onPackageDeleted(packageName, returnCode, null);
15749                } catch (RemoteException e) {
15750                    Log.i(TAG, "Observer no longer exists.");
15751                } //end catch
15752            } //end run
15753        });
15754    }
15755
15756    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15757        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15758              || callingUid == Process.SYSTEM_UID) {
15759            return true;
15760        }
15761        final int callingUserId = UserHandle.getUserId(callingUid);
15762        // If the caller installed the pkgName, then allow it to silently uninstall.
15763        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15764            return true;
15765        }
15766
15767        // Allow package verifier to silently uninstall.
15768        if (mRequiredVerifierPackage != null &&
15769                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15770            return true;
15771        }
15772
15773        // Allow package uninstaller to silently uninstall.
15774        if (mRequiredUninstallerPackage != null &&
15775                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15776            return true;
15777        }
15778
15779        // Allow storage manager to silently uninstall.
15780        if (mStorageManagerPackage != null &&
15781                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15782            return true;
15783        }
15784        return false;
15785    }
15786
15787    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15788        int[] result = EMPTY_INT_ARRAY;
15789        for (int userId : userIds) {
15790            if (getBlockUninstallForUser(packageName, userId)) {
15791                result = ArrayUtils.appendInt(result, userId);
15792            }
15793        }
15794        return result;
15795    }
15796
15797    @Override
15798    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15799        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15800    }
15801
15802    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15803        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15804                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15805        try {
15806            if (dpm != null) {
15807                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15808                        /* callingUserOnly =*/ false);
15809                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15810                        : deviceOwnerComponentName.getPackageName();
15811                // Does the package contains the device owner?
15812                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15813                // this check is probably not needed, since DO should be registered as a device
15814                // admin on some user too. (Original bug for this: b/17657954)
15815                if (packageName.equals(deviceOwnerPackageName)) {
15816                    return true;
15817                }
15818                // Does it contain a device admin for any user?
15819                int[] users;
15820                if (userId == UserHandle.USER_ALL) {
15821                    users = sUserManager.getUserIds();
15822                } else {
15823                    users = new int[]{userId};
15824                }
15825                for (int i = 0; i < users.length; ++i) {
15826                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15827                        return true;
15828                    }
15829                }
15830            }
15831        } catch (RemoteException e) {
15832        }
15833        return false;
15834    }
15835
15836    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15837        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15838    }
15839
15840    /**
15841     *  This method is an internal method that could be get invoked either
15842     *  to delete an installed package or to clean up a failed installation.
15843     *  After deleting an installed package, a broadcast is sent to notify any
15844     *  listeners that the package has been removed. For cleaning up a failed
15845     *  installation, the broadcast is not necessary since the package's
15846     *  installation wouldn't have sent the initial broadcast either
15847     *  The key steps in deleting a package are
15848     *  deleting the package information in internal structures like mPackages,
15849     *  deleting the packages base directories through installd
15850     *  updating mSettings to reflect current status
15851     *  persisting settings for later use
15852     *  sending a broadcast if necessary
15853     */
15854    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15855        final PackageRemovedInfo info = new PackageRemovedInfo();
15856        final boolean res;
15857
15858        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15859                ? UserHandle.USER_ALL : userId;
15860
15861        if (isPackageDeviceAdmin(packageName, removeUser)) {
15862            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15863            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15864        }
15865
15866        PackageSetting uninstalledPs = null;
15867
15868        // for the uninstall-updates case and restricted profiles, remember the per-
15869        // user handle installed state
15870        int[] allUsers;
15871        synchronized (mPackages) {
15872            uninstalledPs = mSettings.mPackages.get(packageName);
15873            if (uninstalledPs == null) {
15874                Slog.w(TAG, "Not removing non-existent package " + packageName);
15875                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15876            }
15877            allUsers = sUserManager.getUserIds();
15878            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15879        }
15880
15881        final int freezeUser;
15882        if (isUpdatedSystemApp(uninstalledPs)
15883                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15884            // We're downgrading a system app, which will apply to all users, so
15885            // freeze them all during the downgrade
15886            freezeUser = UserHandle.USER_ALL;
15887        } else {
15888            freezeUser = removeUser;
15889        }
15890
15891        synchronized (mInstallLock) {
15892            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15893            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15894                    deleteFlags, "deletePackageX")) {
15895                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15896                        deleteFlags | REMOVE_CHATTY, info, true, null);
15897            }
15898            synchronized (mPackages) {
15899                if (res) {
15900                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15901                }
15902            }
15903        }
15904
15905        if (res) {
15906            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15907            info.sendPackageRemovedBroadcasts(killApp);
15908            info.sendSystemPackageUpdatedBroadcasts();
15909            info.sendSystemPackageAppearedBroadcasts();
15910        }
15911        // Force a gc here.
15912        Runtime.getRuntime().gc();
15913        // Delete the resources here after sending the broadcast to let
15914        // other processes clean up before deleting resources.
15915        if (info.args != null) {
15916            synchronized (mInstallLock) {
15917                info.args.doPostDeleteLI(true);
15918            }
15919        }
15920
15921        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15922    }
15923
15924    class PackageRemovedInfo {
15925        String removedPackage;
15926        int uid = -1;
15927        int removedAppId = -1;
15928        int[] origUsers;
15929        int[] removedUsers = null;
15930        boolean isRemovedPackageSystemUpdate = false;
15931        boolean isUpdate;
15932        boolean dataRemoved;
15933        boolean removedForAllUsers;
15934        // Clean up resources deleted packages.
15935        InstallArgs args = null;
15936        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15937        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15938
15939        void sendPackageRemovedBroadcasts(boolean killApp) {
15940            sendPackageRemovedBroadcastInternal(killApp);
15941            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15942            for (int i = 0; i < childCount; i++) {
15943                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15944                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15945            }
15946        }
15947
15948        void sendSystemPackageUpdatedBroadcasts() {
15949            if (isRemovedPackageSystemUpdate) {
15950                sendSystemPackageUpdatedBroadcastsInternal();
15951                final int childCount = (removedChildPackages != null)
15952                        ? removedChildPackages.size() : 0;
15953                for (int i = 0; i < childCount; i++) {
15954                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15955                    if (childInfo.isRemovedPackageSystemUpdate) {
15956                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15957                    }
15958                }
15959            }
15960        }
15961
15962        void sendSystemPackageAppearedBroadcasts() {
15963            final int packageCount = (appearedChildPackages != null)
15964                    ? appearedChildPackages.size() : 0;
15965            for (int i = 0; i < packageCount; i++) {
15966                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15967                sendPackageAddedForNewUsers(installedInfo.name, true,
15968                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
15969            }
15970        }
15971
15972        private void sendSystemPackageUpdatedBroadcastsInternal() {
15973            Bundle extras = new Bundle(2);
15974            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15975            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15976            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15977                    extras, 0, null, null, null);
15978            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15979                    extras, 0, null, null, null);
15980            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15981                    null, 0, removedPackage, null, null);
15982        }
15983
15984        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15985            Bundle extras = new Bundle(2);
15986            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15987            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15988            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15989            if (isUpdate || isRemovedPackageSystemUpdate) {
15990                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15991            }
15992            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15993            if (removedPackage != null) {
15994                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15995                        extras, 0, null, null, removedUsers);
15996                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15997                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15998                            removedPackage, extras, 0, null, null, removedUsers);
15999                }
16000            }
16001            if (removedAppId >= 0) {
16002                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16003                        removedUsers);
16004            }
16005        }
16006    }
16007
16008    /*
16009     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16010     * flag is not set, the data directory is removed as well.
16011     * make sure this flag is set for partially installed apps. If not its meaningless to
16012     * delete a partially installed application.
16013     */
16014    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16015            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16016        String packageName = ps.name;
16017        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16018        // Retrieve object to delete permissions for shared user later on
16019        final PackageParser.Package deletedPkg;
16020        final PackageSetting deletedPs;
16021        // reader
16022        synchronized (mPackages) {
16023            deletedPkg = mPackages.get(packageName);
16024            deletedPs = mSettings.mPackages.get(packageName);
16025            if (outInfo != null) {
16026                outInfo.removedPackage = packageName;
16027                outInfo.removedUsers = deletedPs != null
16028                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16029                        : null;
16030            }
16031        }
16032
16033        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16034
16035        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16036            final PackageParser.Package resolvedPkg;
16037            if (deletedPkg != null) {
16038                resolvedPkg = deletedPkg;
16039            } else {
16040                // We don't have a parsed package when it lives on an ejected
16041                // adopted storage device, so fake something together
16042                resolvedPkg = new PackageParser.Package(ps.name);
16043                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16044            }
16045            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16046                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16047            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16048            if (outInfo != null) {
16049                outInfo.dataRemoved = true;
16050            }
16051            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16052        }
16053
16054        // writer
16055        synchronized (mPackages) {
16056            if (deletedPs != null) {
16057                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16058                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16059                    clearDefaultBrowserIfNeeded(packageName);
16060                    if (outInfo != null) {
16061                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16062                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16063                    }
16064                    updatePermissionsLPw(deletedPs.name, null, 0);
16065                    if (deletedPs.sharedUser != null) {
16066                        // Remove permissions associated with package. Since runtime
16067                        // permissions are per user we have to kill the removed package
16068                        // or packages running under the shared user of the removed
16069                        // package if revoking the permissions requested only by the removed
16070                        // package is successful and this causes a change in gids.
16071                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16072                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16073                                    userId);
16074                            if (userIdToKill == UserHandle.USER_ALL
16075                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16076                                // If gids changed for this user, kill all affected packages.
16077                                mHandler.post(new Runnable() {
16078                                    @Override
16079                                    public void run() {
16080                                        // This has to happen with no lock held.
16081                                        killApplication(deletedPs.name, deletedPs.appId,
16082                                                KILL_APP_REASON_GIDS_CHANGED);
16083                                    }
16084                                });
16085                                break;
16086                            }
16087                        }
16088                    }
16089                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16090                }
16091                // make sure to preserve per-user disabled state if this removal was just
16092                // a downgrade of a system app to the factory package
16093                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16094                    if (DEBUG_REMOVE) {
16095                        Slog.d(TAG, "Propagating install state across downgrade");
16096                    }
16097                    for (int userId : allUserHandles) {
16098                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16099                        if (DEBUG_REMOVE) {
16100                            Slog.d(TAG, "    user " + userId + " => " + installed);
16101                        }
16102                        ps.setInstalled(installed, userId);
16103                    }
16104                }
16105            }
16106            // can downgrade to reader
16107            if (writeSettings) {
16108                // Save settings now
16109                mSettings.writeLPr();
16110            }
16111        }
16112        if (outInfo != null) {
16113            // A user ID was deleted here. Go through all users and remove it
16114            // from KeyStore.
16115            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16116        }
16117    }
16118
16119    static boolean locationIsPrivileged(File path) {
16120        try {
16121            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16122                    .getCanonicalPath();
16123            return path.getCanonicalPath().startsWith(privilegedAppDir);
16124        } catch (IOException e) {
16125            Slog.e(TAG, "Unable to access code path " + path);
16126        }
16127        return false;
16128    }
16129
16130    /*
16131     * Tries to delete system package.
16132     */
16133    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16134            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16135            boolean writeSettings) {
16136        if (deletedPs.parentPackageName != null) {
16137            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16138            return false;
16139        }
16140
16141        final boolean applyUserRestrictions
16142                = (allUserHandles != null) && (outInfo.origUsers != null);
16143        final PackageSetting disabledPs;
16144        // Confirm if the system package has been updated
16145        // An updated system app can be deleted. This will also have to restore
16146        // the system pkg from system partition
16147        // reader
16148        synchronized (mPackages) {
16149            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16150        }
16151
16152        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16153                + " disabledPs=" + disabledPs);
16154
16155        if (disabledPs == null) {
16156            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16157            return false;
16158        } else if (DEBUG_REMOVE) {
16159            Slog.d(TAG, "Deleting system pkg from data partition");
16160        }
16161
16162        if (DEBUG_REMOVE) {
16163            if (applyUserRestrictions) {
16164                Slog.d(TAG, "Remembering install states:");
16165                for (int userId : allUserHandles) {
16166                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16167                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16168                }
16169            }
16170        }
16171
16172        // Delete the updated package
16173        outInfo.isRemovedPackageSystemUpdate = true;
16174        if (outInfo.removedChildPackages != null) {
16175            final int childCount = (deletedPs.childPackageNames != null)
16176                    ? deletedPs.childPackageNames.size() : 0;
16177            for (int i = 0; i < childCount; i++) {
16178                String childPackageName = deletedPs.childPackageNames.get(i);
16179                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16180                        .contains(childPackageName)) {
16181                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16182                            childPackageName);
16183                    if (childInfo != null) {
16184                        childInfo.isRemovedPackageSystemUpdate = true;
16185                    }
16186                }
16187            }
16188        }
16189
16190        if (disabledPs.versionCode < deletedPs.versionCode) {
16191            // Delete data for downgrades
16192            flags &= ~PackageManager.DELETE_KEEP_DATA;
16193        } else {
16194            // Preserve data by setting flag
16195            flags |= PackageManager.DELETE_KEEP_DATA;
16196        }
16197
16198        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16199                outInfo, writeSettings, disabledPs.pkg);
16200        if (!ret) {
16201            return false;
16202        }
16203
16204        // writer
16205        synchronized (mPackages) {
16206            // Reinstate the old system package
16207            enableSystemPackageLPw(disabledPs.pkg);
16208            // Remove any native libraries from the upgraded package.
16209            removeNativeBinariesLI(deletedPs);
16210        }
16211
16212        // Install the system package
16213        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16214        int parseFlags = mDefParseFlags
16215                | PackageParser.PARSE_MUST_BE_APK
16216                | PackageParser.PARSE_IS_SYSTEM
16217                | PackageParser.PARSE_IS_SYSTEM_DIR;
16218        if (locationIsPrivileged(disabledPs.codePath)) {
16219            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16220        }
16221
16222        final PackageParser.Package newPkg;
16223        try {
16224            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16225                0 /* currentTime */, null);
16226        } catch (PackageManagerException e) {
16227            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16228                    + e.getMessage());
16229            return false;
16230        }
16231        try {
16232            // update shared libraries for the newly re-installed system package
16233            updateSharedLibrariesLPr(newPkg, null);
16234        } catch (PackageManagerException e) {
16235            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16236        }
16237
16238        prepareAppDataAfterInstallLIF(newPkg);
16239
16240        // writer
16241        synchronized (mPackages) {
16242            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16243
16244            // Propagate the permissions state as we do not want to drop on the floor
16245            // runtime permissions. The update permissions method below will take
16246            // care of removing obsolete permissions and grant install permissions.
16247            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16248            updatePermissionsLPw(newPkg.packageName, newPkg,
16249                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16250
16251            if (applyUserRestrictions) {
16252                if (DEBUG_REMOVE) {
16253                    Slog.d(TAG, "Propagating install state across reinstall");
16254                }
16255                for (int userId : allUserHandles) {
16256                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16257                    if (DEBUG_REMOVE) {
16258                        Slog.d(TAG, "    user " + userId + " => " + installed);
16259                    }
16260                    ps.setInstalled(installed, userId);
16261
16262                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16263                }
16264                // Regardless of writeSettings we need to ensure that this restriction
16265                // state propagation is persisted
16266                mSettings.writeAllUsersPackageRestrictionsLPr();
16267            }
16268            // can downgrade to reader here
16269            if (writeSettings) {
16270                mSettings.writeLPr();
16271            }
16272        }
16273        return true;
16274    }
16275
16276    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16277            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16278            PackageRemovedInfo outInfo, boolean writeSettings,
16279            PackageParser.Package replacingPackage) {
16280        synchronized (mPackages) {
16281            if (outInfo != null) {
16282                outInfo.uid = ps.appId;
16283            }
16284
16285            if (outInfo != null && outInfo.removedChildPackages != null) {
16286                final int childCount = (ps.childPackageNames != null)
16287                        ? ps.childPackageNames.size() : 0;
16288                for (int i = 0; i < childCount; i++) {
16289                    String childPackageName = ps.childPackageNames.get(i);
16290                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16291                    if (childPs == null) {
16292                        return false;
16293                    }
16294                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16295                            childPackageName);
16296                    if (childInfo != null) {
16297                        childInfo.uid = childPs.appId;
16298                    }
16299                }
16300            }
16301        }
16302
16303        // Delete package data from internal structures and also remove data if flag is set
16304        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16305
16306        // Delete the child packages data
16307        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16308        for (int i = 0; i < childCount; i++) {
16309            PackageSetting childPs;
16310            synchronized (mPackages) {
16311                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16312            }
16313            if (childPs != null) {
16314                PackageRemovedInfo childOutInfo = (outInfo != null
16315                        && outInfo.removedChildPackages != null)
16316                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16317                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16318                        && (replacingPackage != null
16319                        && !replacingPackage.hasChildPackage(childPs.name))
16320                        ? flags & ~DELETE_KEEP_DATA : flags;
16321                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16322                        deleteFlags, writeSettings);
16323            }
16324        }
16325
16326        // Delete application code and resources only for parent packages
16327        if (ps.parentPackageName == null) {
16328            if (deleteCodeAndResources && (outInfo != null)) {
16329                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16330                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16331                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16332            }
16333        }
16334
16335        return true;
16336    }
16337
16338    @Override
16339    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16340            int userId) {
16341        mContext.enforceCallingOrSelfPermission(
16342                android.Manifest.permission.DELETE_PACKAGES, null);
16343        synchronized (mPackages) {
16344            PackageSetting ps = mSettings.mPackages.get(packageName);
16345            if (ps == null) {
16346                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16347                return false;
16348            }
16349            if (!ps.getInstalled(userId)) {
16350                // Can't block uninstall for an app that is not installed or enabled.
16351                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16352                return false;
16353            }
16354            ps.setBlockUninstall(blockUninstall, userId);
16355            mSettings.writePackageRestrictionsLPr(userId);
16356        }
16357        return true;
16358    }
16359
16360    @Override
16361    public boolean getBlockUninstallForUser(String packageName, int userId) {
16362        synchronized (mPackages) {
16363            PackageSetting ps = mSettings.mPackages.get(packageName);
16364            if (ps == null) {
16365                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16366                return false;
16367            }
16368            return ps.getBlockUninstall(userId);
16369        }
16370    }
16371
16372    @Override
16373    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16374        int callingUid = Binder.getCallingUid();
16375        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16376            throw new SecurityException(
16377                    "setRequiredForSystemUser can only be run by the system or root");
16378        }
16379        synchronized (mPackages) {
16380            PackageSetting ps = mSettings.mPackages.get(packageName);
16381            if (ps == null) {
16382                Log.w(TAG, "Package doesn't exist: " + packageName);
16383                return false;
16384            }
16385            if (systemUserApp) {
16386                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16387            } else {
16388                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16389            }
16390            mSettings.writeLPr();
16391        }
16392        return true;
16393    }
16394
16395    /*
16396     * This method handles package deletion in general
16397     */
16398    private boolean deletePackageLIF(String packageName, UserHandle user,
16399            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16400            PackageRemovedInfo outInfo, boolean writeSettings,
16401            PackageParser.Package replacingPackage) {
16402        if (packageName == null) {
16403            Slog.w(TAG, "Attempt to delete null packageName.");
16404            return false;
16405        }
16406
16407        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16408
16409        PackageSetting ps;
16410
16411        synchronized (mPackages) {
16412            ps = mSettings.mPackages.get(packageName);
16413            if (ps == null) {
16414                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16415                return false;
16416            }
16417
16418            if (ps.parentPackageName != null && (!isSystemApp(ps)
16419                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16420                if (DEBUG_REMOVE) {
16421                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16422                            + ((user == null) ? UserHandle.USER_ALL : user));
16423                }
16424                final int removedUserId = (user != null) ? user.getIdentifier()
16425                        : UserHandle.USER_ALL;
16426                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16427                    return false;
16428                }
16429                markPackageUninstalledForUserLPw(ps, user);
16430                scheduleWritePackageRestrictionsLocked(user);
16431                return true;
16432            }
16433        }
16434
16435        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16436                && user.getIdentifier() != UserHandle.USER_ALL)) {
16437            // The caller is asking that the package only be deleted for a single
16438            // user.  To do this, we just mark its uninstalled state and delete
16439            // its data. If this is a system app, we only allow this to happen if
16440            // they have set the special DELETE_SYSTEM_APP which requests different
16441            // semantics than normal for uninstalling system apps.
16442            markPackageUninstalledForUserLPw(ps, user);
16443
16444            if (!isSystemApp(ps)) {
16445                // Do not uninstall the APK if an app should be cached
16446                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16447                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16448                    // Other user still have this package installed, so all
16449                    // we need to do is clear this user's data and save that
16450                    // it is uninstalled.
16451                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16452                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16453                        return false;
16454                    }
16455                    scheduleWritePackageRestrictionsLocked(user);
16456                    return true;
16457                } else {
16458                    // We need to set it back to 'installed' so the uninstall
16459                    // broadcasts will be sent correctly.
16460                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16461                    ps.setInstalled(true, user.getIdentifier());
16462                }
16463            } else {
16464                // This is a system app, so we assume that the
16465                // other users still have this package installed, so all
16466                // we need to do is clear this user's data and save that
16467                // it is uninstalled.
16468                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16469                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16470                    return false;
16471                }
16472                scheduleWritePackageRestrictionsLocked(user);
16473                return true;
16474            }
16475        }
16476
16477        // If we are deleting a composite package for all users, keep track
16478        // of result for each child.
16479        if (ps.childPackageNames != null && outInfo != null) {
16480            synchronized (mPackages) {
16481                final int childCount = ps.childPackageNames.size();
16482                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16483                for (int i = 0; i < childCount; i++) {
16484                    String childPackageName = ps.childPackageNames.get(i);
16485                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16486                    childInfo.removedPackage = childPackageName;
16487                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16488                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16489                    if (childPs != null) {
16490                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16491                    }
16492                }
16493            }
16494        }
16495
16496        boolean ret = false;
16497        if (isSystemApp(ps)) {
16498            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16499            // When an updated system application is deleted we delete the existing resources
16500            // as well and fall back to existing code in system partition
16501            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16502        } else {
16503            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16504            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16505                    outInfo, writeSettings, replacingPackage);
16506        }
16507
16508        // Take a note whether we deleted the package for all users
16509        if (outInfo != null) {
16510            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16511            if (outInfo.removedChildPackages != null) {
16512                synchronized (mPackages) {
16513                    final int childCount = outInfo.removedChildPackages.size();
16514                    for (int i = 0; i < childCount; i++) {
16515                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16516                        if (childInfo != null) {
16517                            childInfo.removedForAllUsers = mPackages.get(
16518                                    childInfo.removedPackage) == null;
16519                        }
16520                    }
16521                }
16522            }
16523            // If we uninstalled an update to a system app there may be some
16524            // child packages that appeared as they are declared in the system
16525            // app but were not declared in the update.
16526            if (isSystemApp(ps)) {
16527                synchronized (mPackages) {
16528                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16529                    final int childCount = (updatedPs.childPackageNames != null)
16530                            ? updatedPs.childPackageNames.size() : 0;
16531                    for (int i = 0; i < childCount; i++) {
16532                        String childPackageName = updatedPs.childPackageNames.get(i);
16533                        if (outInfo.removedChildPackages == null
16534                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16535                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16536                            if (childPs == null) {
16537                                continue;
16538                            }
16539                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16540                            installRes.name = childPackageName;
16541                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16542                            installRes.pkg = mPackages.get(childPackageName);
16543                            installRes.uid = childPs.pkg.applicationInfo.uid;
16544                            if (outInfo.appearedChildPackages == null) {
16545                                outInfo.appearedChildPackages = new ArrayMap<>();
16546                            }
16547                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16548                        }
16549                    }
16550                }
16551            }
16552        }
16553
16554        return ret;
16555    }
16556
16557    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16558        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16559                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16560        for (int nextUserId : userIds) {
16561            if (DEBUG_REMOVE) {
16562                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16563            }
16564            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16565                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16566                    false /*hidden*/, false /*suspended*/, null, null, null,
16567                    false /*blockUninstall*/,
16568                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16569        }
16570    }
16571
16572    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16573            PackageRemovedInfo outInfo) {
16574        final PackageParser.Package pkg;
16575        synchronized (mPackages) {
16576            pkg = mPackages.get(ps.name);
16577        }
16578
16579        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16580                : new int[] {userId};
16581        for (int nextUserId : userIds) {
16582            if (DEBUG_REMOVE) {
16583                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16584                        + nextUserId);
16585            }
16586
16587            destroyAppDataLIF(pkg, userId,
16588                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16589            destroyAppProfilesLIF(pkg, userId);
16590            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16591            schedulePackageCleaning(ps.name, nextUserId, false);
16592            synchronized (mPackages) {
16593                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16594                    scheduleWritePackageRestrictionsLocked(nextUserId);
16595                }
16596                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16597            }
16598        }
16599
16600        if (outInfo != null) {
16601            outInfo.removedPackage = ps.name;
16602            outInfo.removedAppId = ps.appId;
16603            outInfo.removedUsers = userIds;
16604        }
16605
16606        return true;
16607    }
16608
16609    private final class ClearStorageConnection implements ServiceConnection {
16610        IMediaContainerService mContainerService;
16611
16612        @Override
16613        public void onServiceConnected(ComponentName name, IBinder service) {
16614            synchronized (this) {
16615                mContainerService = IMediaContainerService.Stub
16616                        .asInterface(Binder.allowBlocking(service));
16617                notifyAll();
16618            }
16619        }
16620
16621        @Override
16622        public void onServiceDisconnected(ComponentName name) {
16623        }
16624    }
16625
16626    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16627        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16628
16629        final boolean mounted;
16630        if (Environment.isExternalStorageEmulated()) {
16631            mounted = true;
16632        } else {
16633            final String status = Environment.getExternalStorageState();
16634
16635            mounted = status.equals(Environment.MEDIA_MOUNTED)
16636                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16637        }
16638
16639        if (!mounted) {
16640            return;
16641        }
16642
16643        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16644        int[] users;
16645        if (userId == UserHandle.USER_ALL) {
16646            users = sUserManager.getUserIds();
16647        } else {
16648            users = new int[] { userId };
16649        }
16650        final ClearStorageConnection conn = new ClearStorageConnection();
16651        if (mContext.bindServiceAsUser(
16652                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16653            try {
16654                for (int curUser : users) {
16655                    long timeout = SystemClock.uptimeMillis() + 5000;
16656                    synchronized (conn) {
16657                        long now;
16658                        while (conn.mContainerService == null &&
16659                                (now = SystemClock.uptimeMillis()) < timeout) {
16660                            try {
16661                                conn.wait(timeout - now);
16662                            } catch (InterruptedException e) {
16663                            }
16664                        }
16665                    }
16666                    if (conn.mContainerService == null) {
16667                        return;
16668                    }
16669
16670                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16671                    clearDirectory(conn.mContainerService,
16672                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16673                    if (allData) {
16674                        clearDirectory(conn.mContainerService,
16675                                userEnv.buildExternalStorageAppDataDirs(packageName));
16676                        clearDirectory(conn.mContainerService,
16677                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16678                    }
16679                }
16680            } finally {
16681                mContext.unbindService(conn);
16682            }
16683        }
16684    }
16685
16686    @Override
16687    public void clearApplicationProfileData(String packageName) {
16688        enforceSystemOrRoot("Only the system can clear all profile data");
16689
16690        final PackageParser.Package pkg;
16691        synchronized (mPackages) {
16692            pkg = mPackages.get(packageName);
16693        }
16694
16695        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16696            synchronized (mInstallLock) {
16697                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16698                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16699                        true /* removeBaseMarker */);
16700            }
16701        }
16702    }
16703
16704    @Override
16705    public void clearApplicationUserData(final String packageName,
16706            final IPackageDataObserver observer, final int userId) {
16707        mContext.enforceCallingOrSelfPermission(
16708                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16709
16710        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16711                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16712
16713        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16714            throw new SecurityException("Cannot clear data for a protected package: "
16715                    + packageName);
16716        }
16717        // Queue up an async operation since the package deletion may take a little while.
16718        mHandler.post(new Runnable() {
16719            public void run() {
16720                mHandler.removeCallbacks(this);
16721                final boolean succeeded;
16722                try (PackageFreezer freezer = freezePackage(packageName,
16723                        "clearApplicationUserData")) {
16724                    synchronized (mInstallLock) {
16725                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16726                    }
16727                    clearExternalStorageDataSync(packageName, userId, true);
16728                }
16729                if (succeeded) {
16730                    // invoke DeviceStorageMonitor's update method to clear any notifications
16731                    DeviceStorageMonitorInternal dsm = LocalServices
16732                            .getService(DeviceStorageMonitorInternal.class);
16733                    if (dsm != null) {
16734                        dsm.checkMemory();
16735                    }
16736                }
16737                if(observer != null) {
16738                    try {
16739                        observer.onRemoveCompleted(packageName, succeeded);
16740                    } catch (RemoteException e) {
16741                        Log.i(TAG, "Observer no longer exists.");
16742                    }
16743                } //end if observer
16744            } //end run
16745        });
16746    }
16747
16748    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16749        if (packageName == null) {
16750            Slog.w(TAG, "Attempt to delete null packageName.");
16751            return false;
16752        }
16753
16754        // Try finding details about the requested package
16755        PackageParser.Package pkg;
16756        synchronized (mPackages) {
16757            pkg = mPackages.get(packageName);
16758            if (pkg == null) {
16759                final PackageSetting ps = mSettings.mPackages.get(packageName);
16760                if (ps != null) {
16761                    pkg = ps.pkg;
16762                }
16763            }
16764
16765            if (pkg == null) {
16766                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16767                return false;
16768            }
16769
16770            PackageSetting ps = (PackageSetting) pkg.mExtras;
16771            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16772        }
16773
16774        clearAppDataLIF(pkg, userId,
16775                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16776
16777        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16778        removeKeystoreDataIfNeeded(userId, appId);
16779
16780        UserManagerInternal umInternal = getUserManagerInternal();
16781        final int flags;
16782        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16783            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16784        } else if (umInternal.isUserRunning(userId)) {
16785            flags = StorageManager.FLAG_STORAGE_DE;
16786        } else {
16787            flags = 0;
16788        }
16789        prepareAppDataContentsLIF(pkg, userId, flags);
16790
16791        return true;
16792    }
16793
16794    /**
16795     * Reverts user permission state changes (permissions and flags) in
16796     * all packages for a given user.
16797     *
16798     * @param userId The device user for which to do a reset.
16799     */
16800    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16801        final int packageCount = mPackages.size();
16802        for (int i = 0; i < packageCount; i++) {
16803            PackageParser.Package pkg = mPackages.valueAt(i);
16804            PackageSetting ps = (PackageSetting) pkg.mExtras;
16805            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16806        }
16807    }
16808
16809    private void resetNetworkPolicies(int userId) {
16810        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16811    }
16812
16813    /**
16814     * Reverts user permission state changes (permissions and flags).
16815     *
16816     * @param ps The package for which to reset.
16817     * @param userId The device user for which to do a reset.
16818     */
16819    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16820            final PackageSetting ps, final int userId) {
16821        if (ps.pkg == null) {
16822            return;
16823        }
16824
16825        // These are flags that can change base on user actions.
16826        final int userSettableMask = FLAG_PERMISSION_USER_SET
16827                | FLAG_PERMISSION_USER_FIXED
16828                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16829                | FLAG_PERMISSION_REVIEW_REQUIRED;
16830
16831        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16832                | FLAG_PERMISSION_POLICY_FIXED;
16833
16834        boolean writeInstallPermissions = false;
16835        boolean writeRuntimePermissions = false;
16836
16837        final int permissionCount = ps.pkg.requestedPermissions.size();
16838        for (int i = 0; i < permissionCount; i++) {
16839            String permission = ps.pkg.requestedPermissions.get(i);
16840
16841            BasePermission bp = mSettings.mPermissions.get(permission);
16842            if (bp == null) {
16843                continue;
16844            }
16845
16846            // If shared user we just reset the state to which only this app contributed.
16847            if (ps.sharedUser != null) {
16848                boolean used = false;
16849                final int packageCount = ps.sharedUser.packages.size();
16850                for (int j = 0; j < packageCount; j++) {
16851                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16852                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16853                            && pkg.pkg.requestedPermissions.contains(permission)) {
16854                        used = true;
16855                        break;
16856                    }
16857                }
16858                if (used) {
16859                    continue;
16860                }
16861            }
16862
16863            PermissionsState permissionsState = ps.getPermissionsState();
16864
16865            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16866
16867            // Always clear the user settable flags.
16868            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16869                    bp.name) != null;
16870            // If permission review is enabled and this is a legacy app, mark the
16871            // permission as requiring a review as this is the initial state.
16872            int flags = 0;
16873            if (mPermissionReviewRequired
16874                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16875                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16876            }
16877            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16878                if (hasInstallState) {
16879                    writeInstallPermissions = true;
16880                } else {
16881                    writeRuntimePermissions = true;
16882                }
16883            }
16884
16885            // Below is only runtime permission handling.
16886            if (!bp.isRuntime()) {
16887                continue;
16888            }
16889
16890            // Never clobber system or policy.
16891            if ((oldFlags & policyOrSystemFlags) != 0) {
16892                continue;
16893            }
16894
16895            // If this permission was granted by default, make sure it is.
16896            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16897                if (permissionsState.grantRuntimePermission(bp, userId)
16898                        != PERMISSION_OPERATION_FAILURE) {
16899                    writeRuntimePermissions = true;
16900                }
16901            // If permission review is enabled the permissions for a legacy apps
16902            // are represented as constantly granted runtime ones, so don't revoke.
16903            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16904                // Otherwise, reset the permission.
16905                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16906                switch (revokeResult) {
16907                    case PERMISSION_OPERATION_SUCCESS:
16908                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16909                        writeRuntimePermissions = true;
16910                        final int appId = ps.appId;
16911                        mHandler.post(new Runnable() {
16912                            @Override
16913                            public void run() {
16914                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16915                            }
16916                        });
16917                    } break;
16918                }
16919            }
16920        }
16921
16922        // Synchronously write as we are taking permissions away.
16923        if (writeRuntimePermissions) {
16924            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16925        }
16926
16927        // Synchronously write as we are taking permissions away.
16928        if (writeInstallPermissions) {
16929            mSettings.writeLPr();
16930        }
16931    }
16932
16933    /**
16934     * Remove entries from the keystore daemon. Will only remove it if the
16935     * {@code appId} is valid.
16936     */
16937    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16938        if (appId < 0) {
16939            return;
16940        }
16941
16942        final KeyStore keyStore = KeyStore.getInstance();
16943        if (keyStore != null) {
16944            if (userId == UserHandle.USER_ALL) {
16945                for (final int individual : sUserManager.getUserIds()) {
16946                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16947                }
16948            } else {
16949                keyStore.clearUid(UserHandle.getUid(userId, appId));
16950            }
16951        } else {
16952            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16953        }
16954    }
16955
16956    @Override
16957    public void deleteApplicationCacheFiles(final String packageName,
16958            final IPackageDataObserver observer) {
16959        final int userId = UserHandle.getCallingUserId();
16960        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16961    }
16962
16963    @Override
16964    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16965            final IPackageDataObserver observer) {
16966        mContext.enforceCallingOrSelfPermission(
16967                android.Manifest.permission.DELETE_CACHE_FILES, null);
16968        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16969                /* requireFullPermission= */ true, /* checkShell= */ false,
16970                "delete application cache files");
16971
16972        final PackageParser.Package pkg;
16973        synchronized (mPackages) {
16974            pkg = mPackages.get(packageName);
16975        }
16976
16977        // Queue up an async operation since the package deletion may take a little while.
16978        mHandler.post(new Runnable() {
16979            public void run() {
16980                synchronized (mInstallLock) {
16981                    final int flags = StorageManager.FLAG_STORAGE_DE
16982                            | StorageManager.FLAG_STORAGE_CE;
16983                    // We're only clearing cache files, so we don't care if the
16984                    // app is unfrozen and still able to run
16985                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16986                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16987                }
16988                clearExternalStorageDataSync(packageName, userId, false);
16989                if (observer != null) {
16990                    try {
16991                        observer.onRemoveCompleted(packageName, true);
16992                    } catch (RemoteException e) {
16993                        Log.i(TAG, "Observer no longer exists.");
16994                    }
16995                }
16996            }
16997        });
16998    }
16999
17000    @Override
17001    public void getPackageSizeInfo(final String packageName, int userHandle,
17002            final IPackageStatsObserver observer) {
17003        mContext.enforceCallingOrSelfPermission(
17004                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17005        if (packageName == null) {
17006            throw new IllegalArgumentException("Attempt to get size of null packageName");
17007        }
17008
17009        PackageStats stats = new PackageStats(packageName, userHandle);
17010
17011        /*
17012         * Queue up an async operation since the package measurement may take a
17013         * little while.
17014         */
17015        Message msg = mHandler.obtainMessage(INIT_COPY);
17016        msg.obj = new MeasureParams(stats, observer);
17017        mHandler.sendMessage(msg);
17018    }
17019
17020    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17021        final PackageSetting ps;
17022        synchronized (mPackages) {
17023            ps = mSettings.mPackages.get(packageName);
17024            if (ps == null) {
17025                Slog.w(TAG, "Failed to find settings for " + packageName);
17026                return false;
17027            }
17028        }
17029        try {
17030            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17031                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17032                    ps.getCeDataInode(userId), ps.codePathString, stats);
17033        } catch (InstallerException e) {
17034            Slog.w(TAG, String.valueOf(e));
17035            return false;
17036        }
17037
17038        // For now, ignore code size of packages on system partition
17039        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17040            stats.codeSize = 0;
17041        }
17042
17043        return true;
17044    }
17045
17046    private int getUidTargetSdkVersionLockedLPr(int uid) {
17047        Object obj = mSettings.getUserIdLPr(uid);
17048        if (obj instanceof SharedUserSetting) {
17049            final SharedUserSetting sus = (SharedUserSetting) obj;
17050            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17051            final Iterator<PackageSetting> it = sus.packages.iterator();
17052            while (it.hasNext()) {
17053                final PackageSetting ps = it.next();
17054                if (ps.pkg != null) {
17055                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17056                    if (v < vers) vers = v;
17057                }
17058            }
17059            return vers;
17060        } else if (obj instanceof PackageSetting) {
17061            final PackageSetting ps = (PackageSetting) obj;
17062            if (ps.pkg != null) {
17063                return ps.pkg.applicationInfo.targetSdkVersion;
17064            }
17065        }
17066        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17067    }
17068
17069    @Override
17070    public void addPreferredActivity(IntentFilter filter, int match,
17071            ComponentName[] set, ComponentName activity, int userId) {
17072        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17073                "Adding preferred");
17074    }
17075
17076    private void addPreferredActivityInternal(IntentFilter filter, int match,
17077            ComponentName[] set, ComponentName activity, boolean always, int userId,
17078            String opname) {
17079        // writer
17080        int callingUid = Binder.getCallingUid();
17081        enforceCrossUserPermission(callingUid, userId,
17082                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17083        if (filter.countActions() == 0) {
17084            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17085            return;
17086        }
17087        synchronized (mPackages) {
17088            if (mContext.checkCallingOrSelfPermission(
17089                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17090                    != PackageManager.PERMISSION_GRANTED) {
17091                if (getUidTargetSdkVersionLockedLPr(callingUid)
17092                        < Build.VERSION_CODES.FROYO) {
17093                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17094                            + callingUid);
17095                    return;
17096                }
17097                mContext.enforceCallingOrSelfPermission(
17098                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17099            }
17100
17101            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17102            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17103                    + userId + ":");
17104            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17105            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17106            scheduleWritePackageRestrictionsLocked(userId);
17107            postPreferredActivityChangedBroadcast(userId);
17108        }
17109    }
17110
17111    private void postPreferredActivityChangedBroadcast(int userId) {
17112        mHandler.post(() -> {
17113            final IActivityManager am = ActivityManager.getService();
17114            if (am == null) {
17115                return;
17116            }
17117
17118            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17119            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17120            try {
17121                am.broadcastIntent(null, intent, null, null,
17122                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17123                        null, false, false, userId);
17124            } catch (RemoteException e) {
17125            }
17126        });
17127    }
17128
17129    @Override
17130    public void replacePreferredActivity(IntentFilter filter, int match,
17131            ComponentName[] set, ComponentName activity, int userId) {
17132        if (filter.countActions() != 1) {
17133            throw new IllegalArgumentException(
17134                    "replacePreferredActivity expects filter to have only 1 action.");
17135        }
17136        if (filter.countDataAuthorities() != 0
17137                || filter.countDataPaths() != 0
17138                || filter.countDataSchemes() > 1
17139                || filter.countDataTypes() != 0) {
17140            throw new IllegalArgumentException(
17141                    "replacePreferredActivity expects filter to have no data authorities, " +
17142                    "paths, or types; and at most one scheme.");
17143        }
17144
17145        final int callingUid = Binder.getCallingUid();
17146        enforceCrossUserPermission(callingUid, userId,
17147                true /* requireFullPermission */, false /* checkShell */,
17148                "replace preferred activity");
17149        synchronized (mPackages) {
17150            if (mContext.checkCallingOrSelfPermission(
17151                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17152                    != PackageManager.PERMISSION_GRANTED) {
17153                if (getUidTargetSdkVersionLockedLPr(callingUid)
17154                        < Build.VERSION_CODES.FROYO) {
17155                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17156                            + Binder.getCallingUid());
17157                    return;
17158                }
17159                mContext.enforceCallingOrSelfPermission(
17160                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17161            }
17162
17163            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17164            if (pir != null) {
17165                // Get all of the existing entries that exactly match this filter.
17166                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17167                if (existing != null && existing.size() == 1) {
17168                    PreferredActivity cur = existing.get(0);
17169                    if (DEBUG_PREFERRED) {
17170                        Slog.i(TAG, "Checking replace of preferred:");
17171                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17172                        if (!cur.mPref.mAlways) {
17173                            Slog.i(TAG, "  -- CUR; not mAlways!");
17174                        } else {
17175                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17176                            Slog.i(TAG, "  -- CUR: mSet="
17177                                    + Arrays.toString(cur.mPref.mSetComponents));
17178                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17179                            Slog.i(TAG, "  -- NEW: mMatch="
17180                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17181                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17182                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17183                        }
17184                    }
17185                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17186                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17187                            && cur.mPref.sameSet(set)) {
17188                        // Setting the preferred activity to what it happens to be already
17189                        if (DEBUG_PREFERRED) {
17190                            Slog.i(TAG, "Replacing with same preferred activity "
17191                                    + cur.mPref.mShortComponent + " for user "
17192                                    + userId + ":");
17193                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17194                        }
17195                        return;
17196                    }
17197                }
17198
17199                if (existing != null) {
17200                    if (DEBUG_PREFERRED) {
17201                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17202                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17203                    }
17204                    for (int i = 0; i < existing.size(); i++) {
17205                        PreferredActivity pa = existing.get(i);
17206                        if (DEBUG_PREFERRED) {
17207                            Slog.i(TAG, "Removing existing preferred activity "
17208                                    + pa.mPref.mComponent + ":");
17209                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17210                        }
17211                        pir.removeFilter(pa);
17212                    }
17213                }
17214            }
17215            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17216                    "Replacing preferred");
17217        }
17218    }
17219
17220    @Override
17221    public void clearPackagePreferredActivities(String packageName) {
17222        final int uid = Binder.getCallingUid();
17223        // writer
17224        synchronized (mPackages) {
17225            PackageParser.Package pkg = mPackages.get(packageName);
17226            if (pkg == null || pkg.applicationInfo.uid != uid) {
17227                if (mContext.checkCallingOrSelfPermission(
17228                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17229                        != PackageManager.PERMISSION_GRANTED) {
17230                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17231                            < Build.VERSION_CODES.FROYO) {
17232                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17233                                + Binder.getCallingUid());
17234                        return;
17235                    }
17236                    mContext.enforceCallingOrSelfPermission(
17237                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17238                }
17239            }
17240
17241            int user = UserHandle.getCallingUserId();
17242            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17243                scheduleWritePackageRestrictionsLocked(user);
17244            }
17245        }
17246    }
17247
17248    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17249    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17250        ArrayList<PreferredActivity> removed = null;
17251        boolean changed = false;
17252        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17253            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17254            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17255            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17256                continue;
17257            }
17258            Iterator<PreferredActivity> it = pir.filterIterator();
17259            while (it.hasNext()) {
17260                PreferredActivity pa = it.next();
17261                // Mark entry for removal only if it matches the package name
17262                // and the entry is of type "always".
17263                if (packageName == null ||
17264                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17265                                && pa.mPref.mAlways)) {
17266                    if (removed == null) {
17267                        removed = new ArrayList<PreferredActivity>();
17268                    }
17269                    removed.add(pa);
17270                }
17271            }
17272            if (removed != null) {
17273                for (int j=0; j<removed.size(); j++) {
17274                    PreferredActivity pa = removed.get(j);
17275                    pir.removeFilter(pa);
17276                }
17277                changed = true;
17278            }
17279        }
17280        if (changed) {
17281            postPreferredActivityChangedBroadcast(userId);
17282        }
17283        return changed;
17284    }
17285
17286    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17287    private void clearIntentFilterVerificationsLPw(int userId) {
17288        final int packageCount = mPackages.size();
17289        for (int i = 0; i < packageCount; i++) {
17290            PackageParser.Package pkg = mPackages.valueAt(i);
17291            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17292        }
17293    }
17294
17295    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17296    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17297        if (userId == UserHandle.USER_ALL) {
17298            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17299                    sUserManager.getUserIds())) {
17300                for (int oneUserId : sUserManager.getUserIds()) {
17301                    scheduleWritePackageRestrictionsLocked(oneUserId);
17302                }
17303            }
17304        } else {
17305            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17306                scheduleWritePackageRestrictionsLocked(userId);
17307            }
17308        }
17309    }
17310
17311    void clearDefaultBrowserIfNeeded(String packageName) {
17312        for (int oneUserId : sUserManager.getUserIds()) {
17313            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17314            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17315            if (packageName.equals(defaultBrowserPackageName)) {
17316                setDefaultBrowserPackageName(null, oneUserId);
17317            }
17318        }
17319    }
17320
17321    @Override
17322    public void resetApplicationPreferences(int userId) {
17323        mContext.enforceCallingOrSelfPermission(
17324                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17325        final long identity = Binder.clearCallingIdentity();
17326        // writer
17327        try {
17328            synchronized (mPackages) {
17329                clearPackagePreferredActivitiesLPw(null, userId);
17330                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17331                // TODO: We have to reset the default SMS and Phone. This requires
17332                // significant refactoring to keep all default apps in the package
17333                // manager (cleaner but more work) or have the services provide
17334                // callbacks to the package manager to request a default app reset.
17335                applyFactoryDefaultBrowserLPw(userId);
17336                clearIntentFilterVerificationsLPw(userId);
17337                primeDomainVerificationsLPw(userId);
17338                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17339                scheduleWritePackageRestrictionsLocked(userId);
17340            }
17341            resetNetworkPolicies(userId);
17342        } finally {
17343            Binder.restoreCallingIdentity(identity);
17344        }
17345    }
17346
17347    @Override
17348    public int getPreferredActivities(List<IntentFilter> outFilters,
17349            List<ComponentName> outActivities, String packageName) {
17350
17351        int num = 0;
17352        final int userId = UserHandle.getCallingUserId();
17353        // reader
17354        synchronized (mPackages) {
17355            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17356            if (pir != null) {
17357                final Iterator<PreferredActivity> it = pir.filterIterator();
17358                while (it.hasNext()) {
17359                    final PreferredActivity pa = it.next();
17360                    if (packageName == null
17361                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17362                                    && pa.mPref.mAlways)) {
17363                        if (outFilters != null) {
17364                            outFilters.add(new IntentFilter(pa));
17365                        }
17366                        if (outActivities != null) {
17367                            outActivities.add(pa.mPref.mComponent);
17368                        }
17369                    }
17370                }
17371            }
17372        }
17373
17374        return num;
17375    }
17376
17377    @Override
17378    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17379            int userId) {
17380        int callingUid = Binder.getCallingUid();
17381        if (callingUid != Process.SYSTEM_UID) {
17382            throw new SecurityException(
17383                    "addPersistentPreferredActivity can only be run by the system");
17384        }
17385        if (filter.countActions() == 0) {
17386            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17387            return;
17388        }
17389        synchronized (mPackages) {
17390            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17391                    ":");
17392            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17393            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17394                    new PersistentPreferredActivity(filter, activity));
17395            scheduleWritePackageRestrictionsLocked(userId);
17396            postPreferredActivityChangedBroadcast(userId);
17397        }
17398    }
17399
17400    @Override
17401    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17402        int callingUid = Binder.getCallingUid();
17403        if (callingUid != Process.SYSTEM_UID) {
17404            throw new SecurityException(
17405                    "clearPackagePersistentPreferredActivities can only be run by the system");
17406        }
17407        ArrayList<PersistentPreferredActivity> removed = null;
17408        boolean changed = false;
17409        synchronized (mPackages) {
17410            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17411                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17412                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17413                        .valueAt(i);
17414                if (userId != thisUserId) {
17415                    continue;
17416                }
17417                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17418                while (it.hasNext()) {
17419                    PersistentPreferredActivity ppa = it.next();
17420                    // Mark entry for removal only if it matches the package name.
17421                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17422                        if (removed == null) {
17423                            removed = new ArrayList<PersistentPreferredActivity>();
17424                        }
17425                        removed.add(ppa);
17426                    }
17427                }
17428                if (removed != null) {
17429                    for (int j=0; j<removed.size(); j++) {
17430                        PersistentPreferredActivity ppa = removed.get(j);
17431                        ppir.removeFilter(ppa);
17432                    }
17433                    changed = true;
17434                }
17435            }
17436
17437            if (changed) {
17438                scheduleWritePackageRestrictionsLocked(userId);
17439                postPreferredActivityChangedBroadcast(userId);
17440            }
17441        }
17442    }
17443
17444    /**
17445     * Common machinery for picking apart a restored XML blob and passing
17446     * it to a caller-supplied functor to be applied to the running system.
17447     */
17448    private void restoreFromXml(XmlPullParser parser, int userId,
17449            String expectedStartTag, BlobXmlRestorer functor)
17450            throws IOException, XmlPullParserException {
17451        int type;
17452        while ((type = parser.next()) != XmlPullParser.START_TAG
17453                && type != XmlPullParser.END_DOCUMENT) {
17454        }
17455        if (type != XmlPullParser.START_TAG) {
17456            // oops didn't find a start tag?!
17457            if (DEBUG_BACKUP) {
17458                Slog.e(TAG, "Didn't find start tag during restore");
17459            }
17460            return;
17461        }
17462Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17463        // this is supposed to be TAG_PREFERRED_BACKUP
17464        if (!expectedStartTag.equals(parser.getName())) {
17465            if (DEBUG_BACKUP) {
17466                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17467            }
17468            return;
17469        }
17470
17471        // skip interfering stuff, then we're aligned with the backing implementation
17472        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17473Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17474        functor.apply(parser, userId);
17475    }
17476
17477    private interface BlobXmlRestorer {
17478        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17479    }
17480
17481    /**
17482     * Non-Binder method, support for the backup/restore mechanism: write the
17483     * full set of preferred activities in its canonical XML format.  Returns the
17484     * XML output as a byte array, or null if there is none.
17485     */
17486    @Override
17487    public byte[] getPreferredActivityBackup(int userId) {
17488        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17489            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17490        }
17491
17492        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17493        try {
17494            final XmlSerializer serializer = new FastXmlSerializer();
17495            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17496            serializer.startDocument(null, true);
17497            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17498
17499            synchronized (mPackages) {
17500                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17501            }
17502
17503            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17504            serializer.endDocument();
17505            serializer.flush();
17506        } catch (Exception e) {
17507            if (DEBUG_BACKUP) {
17508                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17509            }
17510            return null;
17511        }
17512
17513        return dataStream.toByteArray();
17514    }
17515
17516    @Override
17517    public void restorePreferredActivities(byte[] backup, int userId) {
17518        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17519            throw new SecurityException("Only the system may call restorePreferredActivities()");
17520        }
17521
17522        try {
17523            final XmlPullParser parser = Xml.newPullParser();
17524            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17525            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17526                    new BlobXmlRestorer() {
17527                        @Override
17528                        public void apply(XmlPullParser parser, int userId)
17529                                throws XmlPullParserException, IOException {
17530                            synchronized (mPackages) {
17531                                mSettings.readPreferredActivitiesLPw(parser, userId);
17532                            }
17533                        }
17534                    } );
17535        } catch (Exception e) {
17536            if (DEBUG_BACKUP) {
17537                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17538            }
17539        }
17540    }
17541
17542    /**
17543     * Non-Binder method, support for the backup/restore mechanism: write the
17544     * default browser (etc) settings in its canonical XML format.  Returns the default
17545     * browser XML representation as a byte array, or null if there is none.
17546     */
17547    @Override
17548    public byte[] getDefaultAppsBackup(int userId) {
17549        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17550            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17551        }
17552
17553        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17554        try {
17555            final XmlSerializer serializer = new FastXmlSerializer();
17556            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17557            serializer.startDocument(null, true);
17558            serializer.startTag(null, TAG_DEFAULT_APPS);
17559
17560            synchronized (mPackages) {
17561                mSettings.writeDefaultAppsLPr(serializer, userId);
17562            }
17563
17564            serializer.endTag(null, TAG_DEFAULT_APPS);
17565            serializer.endDocument();
17566            serializer.flush();
17567        } catch (Exception e) {
17568            if (DEBUG_BACKUP) {
17569                Slog.e(TAG, "Unable to write default apps for backup", e);
17570            }
17571            return null;
17572        }
17573
17574        return dataStream.toByteArray();
17575    }
17576
17577    @Override
17578    public void restoreDefaultApps(byte[] backup, int userId) {
17579        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17580            throw new SecurityException("Only the system may call restoreDefaultApps()");
17581        }
17582
17583        try {
17584            final XmlPullParser parser = Xml.newPullParser();
17585            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17586            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17587                    new BlobXmlRestorer() {
17588                        @Override
17589                        public void apply(XmlPullParser parser, int userId)
17590                                throws XmlPullParserException, IOException {
17591                            synchronized (mPackages) {
17592                                mSettings.readDefaultAppsLPw(parser, userId);
17593                            }
17594                        }
17595                    } );
17596        } catch (Exception e) {
17597            if (DEBUG_BACKUP) {
17598                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17599            }
17600        }
17601    }
17602
17603    @Override
17604    public byte[] getIntentFilterVerificationBackup(int userId) {
17605        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17606            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17607        }
17608
17609        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17610        try {
17611            final XmlSerializer serializer = new FastXmlSerializer();
17612            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17613            serializer.startDocument(null, true);
17614            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17615
17616            synchronized (mPackages) {
17617                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17618            }
17619
17620            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17621            serializer.endDocument();
17622            serializer.flush();
17623        } catch (Exception e) {
17624            if (DEBUG_BACKUP) {
17625                Slog.e(TAG, "Unable to write default apps for backup", e);
17626            }
17627            return null;
17628        }
17629
17630        return dataStream.toByteArray();
17631    }
17632
17633    @Override
17634    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17635        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17636            throw new SecurityException("Only the system may call restorePreferredActivities()");
17637        }
17638
17639        try {
17640            final XmlPullParser parser = Xml.newPullParser();
17641            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17642            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17643                    new BlobXmlRestorer() {
17644                        @Override
17645                        public void apply(XmlPullParser parser, int userId)
17646                                throws XmlPullParserException, IOException {
17647                            synchronized (mPackages) {
17648                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17649                                mSettings.writeLPr();
17650                            }
17651                        }
17652                    } );
17653        } catch (Exception e) {
17654            if (DEBUG_BACKUP) {
17655                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17656            }
17657        }
17658    }
17659
17660    @Override
17661    public byte[] getPermissionGrantBackup(int userId) {
17662        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17663            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17664        }
17665
17666        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17667        try {
17668            final XmlSerializer serializer = new FastXmlSerializer();
17669            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17670            serializer.startDocument(null, true);
17671            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17672
17673            synchronized (mPackages) {
17674                serializeRuntimePermissionGrantsLPr(serializer, userId);
17675            }
17676
17677            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17678            serializer.endDocument();
17679            serializer.flush();
17680        } catch (Exception e) {
17681            if (DEBUG_BACKUP) {
17682                Slog.e(TAG, "Unable to write default apps for backup", e);
17683            }
17684            return null;
17685        }
17686
17687        return dataStream.toByteArray();
17688    }
17689
17690    @Override
17691    public void restorePermissionGrants(byte[] backup, int userId) {
17692        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17693            throw new SecurityException("Only the system may call restorePermissionGrants()");
17694        }
17695
17696        try {
17697            final XmlPullParser parser = Xml.newPullParser();
17698            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17699            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17700                    new BlobXmlRestorer() {
17701                        @Override
17702                        public void apply(XmlPullParser parser, int userId)
17703                                throws XmlPullParserException, IOException {
17704                            synchronized (mPackages) {
17705                                processRestoredPermissionGrantsLPr(parser, userId);
17706                            }
17707                        }
17708                    } );
17709        } catch (Exception e) {
17710            if (DEBUG_BACKUP) {
17711                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17712            }
17713        }
17714    }
17715
17716    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17717            throws IOException {
17718        serializer.startTag(null, TAG_ALL_GRANTS);
17719
17720        final int N = mSettings.mPackages.size();
17721        for (int i = 0; i < N; i++) {
17722            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17723            boolean pkgGrantsKnown = false;
17724
17725            PermissionsState packagePerms = ps.getPermissionsState();
17726
17727            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17728                final int grantFlags = state.getFlags();
17729                // only look at grants that are not system/policy fixed
17730                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17731                    final boolean isGranted = state.isGranted();
17732                    // And only back up the user-twiddled state bits
17733                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17734                        final String packageName = mSettings.mPackages.keyAt(i);
17735                        if (!pkgGrantsKnown) {
17736                            serializer.startTag(null, TAG_GRANT);
17737                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17738                            pkgGrantsKnown = true;
17739                        }
17740
17741                        final boolean userSet =
17742                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17743                        final boolean userFixed =
17744                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17745                        final boolean revoke =
17746                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17747
17748                        serializer.startTag(null, TAG_PERMISSION);
17749                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17750                        if (isGranted) {
17751                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17752                        }
17753                        if (userSet) {
17754                            serializer.attribute(null, ATTR_USER_SET, "true");
17755                        }
17756                        if (userFixed) {
17757                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17758                        }
17759                        if (revoke) {
17760                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17761                        }
17762                        serializer.endTag(null, TAG_PERMISSION);
17763                    }
17764                }
17765            }
17766
17767            if (pkgGrantsKnown) {
17768                serializer.endTag(null, TAG_GRANT);
17769            }
17770        }
17771
17772        serializer.endTag(null, TAG_ALL_GRANTS);
17773    }
17774
17775    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17776            throws XmlPullParserException, IOException {
17777        String pkgName = null;
17778        int outerDepth = parser.getDepth();
17779        int type;
17780        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17781                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17782            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17783                continue;
17784            }
17785
17786            final String tagName = parser.getName();
17787            if (tagName.equals(TAG_GRANT)) {
17788                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17789                if (DEBUG_BACKUP) {
17790                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17791                }
17792            } else if (tagName.equals(TAG_PERMISSION)) {
17793
17794                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17795                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17796
17797                int newFlagSet = 0;
17798                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17799                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17800                }
17801                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17802                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17803                }
17804                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17805                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17806                }
17807                if (DEBUG_BACKUP) {
17808                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17809                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17810                }
17811                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17812                if (ps != null) {
17813                    // Already installed so we apply the grant immediately
17814                    if (DEBUG_BACKUP) {
17815                        Slog.v(TAG, "        + already installed; applying");
17816                    }
17817                    PermissionsState perms = ps.getPermissionsState();
17818                    BasePermission bp = mSettings.mPermissions.get(permName);
17819                    if (bp != null) {
17820                        if (isGranted) {
17821                            perms.grantRuntimePermission(bp, userId);
17822                        }
17823                        if (newFlagSet != 0) {
17824                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17825                        }
17826                    }
17827                } else {
17828                    // Need to wait for post-restore install to apply the grant
17829                    if (DEBUG_BACKUP) {
17830                        Slog.v(TAG, "        - not yet installed; saving for later");
17831                    }
17832                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17833                            isGranted, newFlagSet, userId);
17834                }
17835            } else {
17836                PackageManagerService.reportSettingsProblem(Log.WARN,
17837                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17838                XmlUtils.skipCurrentTag(parser);
17839            }
17840        }
17841
17842        scheduleWriteSettingsLocked();
17843        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17844    }
17845
17846    @Override
17847    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17848            int sourceUserId, int targetUserId, int flags) {
17849        mContext.enforceCallingOrSelfPermission(
17850                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17851        int callingUid = Binder.getCallingUid();
17852        enforceOwnerRights(ownerPackage, callingUid);
17853        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17854        if (intentFilter.countActions() == 0) {
17855            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17856            return;
17857        }
17858        synchronized (mPackages) {
17859            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17860                    ownerPackage, targetUserId, flags);
17861            CrossProfileIntentResolver resolver =
17862                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17863            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17864            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17865            if (existing != null) {
17866                int size = existing.size();
17867                for (int i = 0; i < size; i++) {
17868                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17869                        return;
17870                    }
17871                }
17872            }
17873            resolver.addFilter(newFilter);
17874            scheduleWritePackageRestrictionsLocked(sourceUserId);
17875        }
17876    }
17877
17878    @Override
17879    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17880        mContext.enforceCallingOrSelfPermission(
17881                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17882        int callingUid = Binder.getCallingUid();
17883        enforceOwnerRights(ownerPackage, callingUid);
17884        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17885        synchronized (mPackages) {
17886            CrossProfileIntentResolver resolver =
17887                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17888            ArraySet<CrossProfileIntentFilter> set =
17889                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17890            for (CrossProfileIntentFilter filter : set) {
17891                if (filter.getOwnerPackage().equals(ownerPackage)) {
17892                    resolver.removeFilter(filter);
17893                }
17894            }
17895            scheduleWritePackageRestrictionsLocked(sourceUserId);
17896        }
17897    }
17898
17899    // Enforcing that callingUid is owning pkg on userId
17900    private void enforceOwnerRights(String pkg, int callingUid) {
17901        // The system owns everything.
17902        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17903            return;
17904        }
17905        int callingUserId = UserHandle.getUserId(callingUid);
17906        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17907        if (pi == null) {
17908            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17909                    + callingUserId);
17910        }
17911        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17912            throw new SecurityException("Calling uid " + callingUid
17913                    + " does not own package " + pkg);
17914        }
17915    }
17916
17917    @Override
17918    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17919        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17920    }
17921
17922    private Intent getHomeIntent() {
17923        Intent intent = new Intent(Intent.ACTION_MAIN);
17924        intent.addCategory(Intent.CATEGORY_HOME);
17925        intent.addCategory(Intent.CATEGORY_DEFAULT);
17926        return intent;
17927    }
17928
17929    private IntentFilter getHomeFilter() {
17930        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17931        filter.addCategory(Intent.CATEGORY_HOME);
17932        filter.addCategory(Intent.CATEGORY_DEFAULT);
17933        return filter;
17934    }
17935
17936    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17937            int userId) {
17938        Intent intent  = getHomeIntent();
17939        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17940                PackageManager.GET_META_DATA, userId);
17941        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17942                true, false, false, userId);
17943
17944        allHomeCandidates.clear();
17945        if (list != null) {
17946            for (ResolveInfo ri : list) {
17947                allHomeCandidates.add(ri);
17948            }
17949        }
17950        return (preferred == null || preferred.activityInfo == null)
17951                ? null
17952                : new ComponentName(preferred.activityInfo.packageName,
17953                        preferred.activityInfo.name);
17954    }
17955
17956    @Override
17957    public void setHomeActivity(ComponentName comp, int userId) {
17958        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17959        getHomeActivitiesAsUser(homeActivities, userId);
17960
17961        boolean found = false;
17962
17963        final int size = homeActivities.size();
17964        final ComponentName[] set = new ComponentName[size];
17965        for (int i = 0; i < size; i++) {
17966            final ResolveInfo candidate = homeActivities.get(i);
17967            final ActivityInfo info = candidate.activityInfo;
17968            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17969            set[i] = activityName;
17970            if (!found && activityName.equals(comp)) {
17971                found = true;
17972            }
17973        }
17974        if (!found) {
17975            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17976                    + userId);
17977        }
17978        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17979                set, comp, userId);
17980    }
17981
17982    private @Nullable String getSetupWizardPackageName() {
17983        final Intent intent = new Intent(Intent.ACTION_MAIN);
17984        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17985
17986        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17987                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17988                        | MATCH_DISABLED_COMPONENTS,
17989                UserHandle.myUserId());
17990        if (matches.size() == 1) {
17991            return matches.get(0).getComponentInfo().packageName;
17992        } else {
17993            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17994                    + ": matches=" + matches);
17995            return null;
17996        }
17997    }
17998
17999    private @Nullable String getStorageManagerPackageName() {
18000        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18001
18002        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18003                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18004                        | MATCH_DISABLED_COMPONENTS,
18005                UserHandle.myUserId());
18006        if (matches.size() == 1) {
18007            return matches.get(0).getComponentInfo().packageName;
18008        } else {
18009            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18010                    + matches.size() + ": matches=" + matches);
18011            return null;
18012        }
18013    }
18014
18015    @Override
18016    public void setApplicationEnabledSetting(String appPackageName,
18017            int newState, int flags, int userId, String callingPackage) {
18018        if (!sUserManager.exists(userId)) return;
18019        if (callingPackage == null) {
18020            callingPackage = Integer.toString(Binder.getCallingUid());
18021        }
18022        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18023    }
18024
18025    @Override
18026    public void setComponentEnabledSetting(ComponentName componentName,
18027            int newState, int flags, int userId) {
18028        if (!sUserManager.exists(userId)) return;
18029        setEnabledSetting(componentName.getPackageName(),
18030                componentName.getClassName(), newState, flags, userId, null);
18031    }
18032
18033    private void setEnabledSetting(final String packageName, String className, int newState,
18034            final int flags, int userId, String callingPackage) {
18035        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18036              || newState == COMPONENT_ENABLED_STATE_ENABLED
18037              || newState == COMPONENT_ENABLED_STATE_DISABLED
18038              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18039              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18040            throw new IllegalArgumentException("Invalid new component state: "
18041                    + newState);
18042        }
18043        PackageSetting pkgSetting;
18044        final int uid = Binder.getCallingUid();
18045        final int permission;
18046        if (uid == Process.SYSTEM_UID) {
18047            permission = PackageManager.PERMISSION_GRANTED;
18048        } else {
18049            permission = mContext.checkCallingOrSelfPermission(
18050                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18051        }
18052        enforceCrossUserPermission(uid, userId,
18053                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18054        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18055        boolean sendNow = false;
18056        boolean isApp = (className == null);
18057        String componentName = isApp ? packageName : className;
18058        int packageUid = -1;
18059        ArrayList<String> components;
18060
18061        // writer
18062        synchronized (mPackages) {
18063            pkgSetting = mSettings.mPackages.get(packageName);
18064            if (pkgSetting == null) {
18065                if (className == null) {
18066                    throw new IllegalArgumentException("Unknown package: " + packageName);
18067                }
18068                throw new IllegalArgumentException(
18069                        "Unknown component: " + packageName + "/" + className);
18070            }
18071        }
18072
18073        // Limit who can change which apps
18074        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18075            // Don't allow apps that don't have permission to modify other apps
18076            if (!allowedByPermission) {
18077                throw new SecurityException(
18078                        "Permission Denial: attempt to change component state from pid="
18079                        + Binder.getCallingPid()
18080                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18081            }
18082            // Don't allow changing protected packages.
18083            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18084                throw new SecurityException("Cannot disable a protected package: " + packageName);
18085            }
18086        }
18087
18088        synchronized (mPackages) {
18089            if (uid == Process.SHELL_UID
18090                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18091                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18092                // unless it is a test package.
18093                int oldState = pkgSetting.getEnabled(userId);
18094                if (className == null
18095                    &&
18096                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18097                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18098                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18099                    &&
18100                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18101                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18102                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18103                    // ok
18104                } else {
18105                    throw new SecurityException(
18106                            "Shell cannot change component state for " + packageName + "/"
18107                            + className + " to " + newState);
18108                }
18109            }
18110            if (className == null) {
18111                // We're dealing with an application/package level state change
18112                if (pkgSetting.getEnabled(userId) == newState) {
18113                    // Nothing to do
18114                    return;
18115                }
18116                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18117                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18118                    // Don't care about who enables an app.
18119                    callingPackage = null;
18120                }
18121                pkgSetting.setEnabled(newState, userId, callingPackage);
18122                // pkgSetting.pkg.mSetEnabled = newState;
18123            } else {
18124                // We're dealing with a component level state change
18125                // First, verify that this is a valid class name.
18126                PackageParser.Package pkg = pkgSetting.pkg;
18127                if (pkg == null || !pkg.hasComponentClassName(className)) {
18128                    if (pkg != null &&
18129                            pkg.applicationInfo.targetSdkVersion >=
18130                                    Build.VERSION_CODES.JELLY_BEAN) {
18131                        throw new IllegalArgumentException("Component class " + className
18132                                + " does not exist in " + packageName);
18133                    } else {
18134                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18135                                + className + " does not exist in " + packageName);
18136                    }
18137                }
18138                switch (newState) {
18139                case COMPONENT_ENABLED_STATE_ENABLED:
18140                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18141                        return;
18142                    }
18143                    break;
18144                case COMPONENT_ENABLED_STATE_DISABLED:
18145                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18146                        return;
18147                    }
18148                    break;
18149                case COMPONENT_ENABLED_STATE_DEFAULT:
18150                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18151                        return;
18152                    }
18153                    break;
18154                default:
18155                    Slog.e(TAG, "Invalid new component state: " + newState);
18156                    return;
18157                }
18158            }
18159            scheduleWritePackageRestrictionsLocked(userId);
18160            components = mPendingBroadcasts.get(userId, packageName);
18161            final boolean newPackage = components == null;
18162            if (newPackage) {
18163                components = new ArrayList<String>();
18164            }
18165            if (!components.contains(componentName)) {
18166                components.add(componentName);
18167            }
18168            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18169                sendNow = true;
18170                // Purge entry from pending broadcast list if another one exists already
18171                // since we are sending one right away.
18172                mPendingBroadcasts.remove(userId, packageName);
18173            } else {
18174                if (newPackage) {
18175                    mPendingBroadcasts.put(userId, packageName, components);
18176                }
18177                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18178                    // Schedule a message
18179                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18180                }
18181            }
18182        }
18183
18184        long callingId = Binder.clearCallingIdentity();
18185        try {
18186            if (sendNow) {
18187                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18188                sendPackageChangedBroadcast(packageName,
18189                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18190            }
18191        } finally {
18192            Binder.restoreCallingIdentity(callingId);
18193        }
18194    }
18195
18196    @Override
18197    public void flushPackageRestrictionsAsUser(int userId) {
18198        if (!sUserManager.exists(userId)) {
18199            return;
18200        }
18201        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18202                false /* checkShell */, "flushPackageRestrictions");
18203        synchronized (mPackages) {
18204            mSettings.writePackageRestrictionsLPr(userId);
18205            mDirtyUsers.remove(userId);
18206            if (mDirtyUsers.isEmpty()) {
18207                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18208            }
18209        }
18210    }
18211
18212    private void sendPackageChangedBroadcast(String packageName,
18213            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18214        if (DEBUG_INSTALL)
18215            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18216                    + componentNames);
18217        Bundle extras = new Bundle(4);
18218        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18219        String nameList[] = new String[componentNames.size()];
18220        componentNames.toArray(nameList);
18221        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18222        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18223        extras.putInt(Intent.EXTRA_UID, packageUid);
18224        // If this is not reporting a change of the overall package, then only send it
18225        // to registered receivers.  We don't want to launch a swath of apps for every
18226        // little component state change.
18227        final int flags = !componentNames.contains(packageName)
18228                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18229        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18230                new int[] {UserHandle.getUserId(packageUid)});
18231    }
18232
18233    @Override
18234    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18235        if (!sUserManager.exists(userId)) return;
18236        final int uid = Binder.getCallingUid();
18237        final int permission = mContext.checkCallingOrSelfPermission(
18238                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18239        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18240        enforceCrossUserPermission(uid, userId,
18241                true /* requireFullPermission */, true /* checkShell */, "stop package");
18242        // writer
18243        synchronized (mPackages) {
18244            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18245                    allowedByPermission, uid, userId)) {
18246                scheduleWritePackageRestrictionsLocked(userId);
18247            }
18248        }
18249    }
18250
18251    @Override
18252    public String getInstallerPackageName(String packageName) {
18253        // reader
18254        synchronized (mPackages) {
18255            return mSettings.getInstallerPackageNameLPr(packageName);
18256        }
18257    }
18258
18259    public boolean isOrphaned(String packageName) {
18260        // reader
18261        synchronized (mPackages) {
18262            return mSettings.isOrphaned(packageName);
18263        }
18264    }
18265
18266    @Override
18267    public int getApplicationEnabledSetting(String packageName, int userId) {
18268        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18269        int uid = Binder.getCallingUid();
18270        enforceCrossUserPermission(uid, userId,
18271                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18272        // reader
18273        synchronized (mPackages) {
18274            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18275        }
18276    }
18277
18278    @Override
18279    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18280        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18281        int uid = Binder.getCallingUid();
18282        enforceCrossUserPermission(uid, userId,
18283                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18284        // reader
18285        synchronized (mPackages) {
18286            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18287        }
18288    }
18289
18290    @Override
18291    public void enterSafeMode() {
18292        enforceSystemOrRoot("Only the system can request entering safe mode");
18293
18294        if (!mSystemReady) {
18295            mSafeMode = true;
18296        }
18297    }
18298
18299    @Override
18300    public void systemReady() {
18301        mSystemReady = true;
18302
18303        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18304        // disabled after already being started.
18305        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18306                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18307
18308        // Read the compatibilty setting when the system is ready.
18309        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18310                mContext.getContentResolver(),
18311                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18312        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18313        if (DEBUG_SETTINGS) {
18314            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18315        }
18316
18317        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18318
18319        synchronized (mPackages) {
18320            // Verify that all of the preferred activity components actually
18321            // exist.  It is possible for applications to be updated and at
18322            // that point remove a previously declared activity component that
18323            // had been set as a preferred activity.  We try to clean this up
18324            // the next time we encounter that preferred activity, but it is
18325            // possible for the user flow to never be able to return to that
18326            // situation so here we do a sanity check to make sure we haven't
18327            // left any junk around.
18328            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18329            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18330                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18331                removed.clear();
18332                for (PreferredActivity pa : pir.filterSet()) {
18333                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18334                        removed.add(pa);
18335                    }
18336                }
18337                if (removed.size() > 0) {
18338                    for (int r=0; r<removed.size(); r++) {
18339                        PreferredActivity pa = removed.get(r);
18340                        Slog.w(TAG, "Removing dangling preferred activity: "
18341                                + pa.mPref.mComponent);
18342                        pir.removeFilter(pa);
18343                    }
18344                    mSettings.writePackageRestrictionsLPr(
18345                            mSettings.mPreferredActivities.keyAt(i));
18346                }
18347            }
18348
18349            for (int userId : UserManagerService.getInstance().getUserIds()) {
18350                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18351                    grantPermissionsUserIds = ArrayUtils.appendInt(
18352                            grantPermissionsUserIds, userId);
18353                }
18354            }
18355        }
18356        sUserManager.systemReady();
18357
18358        // If we upgraded grant all default permissions before kicking off.
18359        for (int userId : grantPermissionsUserIds) {
18360            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18361        }
18362
18363        // If we did not grant default permissions, we preload from this the
18364        // default permission exceptions lazily to ensure we don't hit the
18365        // disk on a new user creation.
18366        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18367            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18368        }
18369
18370        // Kick off any messages waiting for system ready
18371        if (mPostSystemReadyMessages != null) {
18372            for (Message msg : mPostSystemReadyMessages) {
18373                msg.sendToTarget();
18374            }
18375            mPostSystemReadyMessages = null;
18376        }
18377
18378        // Watch for external volumes that come and go over time
18379        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18380        storage.registerListener(mStorageListener);
18381
18382        mInstallerService.systemReady();
18383        mPackageDexOptimizer.systemReady();
18384
18385        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18386                StorageManagerInternal.class);
18387        StorageManagerInternal.addExternalStoragePolicy(
18388                new StorageManagerInternal.ExternalStorageMountPolicy() {
18389            @Override
18390            public int getMountMode(int uid, String packageName) {
18391                if (Process.isIsolated(uid)) {
18392                    return Zygote.MOUNT_EXTERNAL_NONE;
18393                }
18394                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18395                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18396                }
18397                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18398                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18399                }
18400                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18401                    return Zygote.MOUNT_EXTERNAL_READ;
18402                }
18403                return Zygote.MOUNT_EXTERNAL_WRITE;
18404            }
18405
18406            @Override
18407            public boolean hasExternalStorage(int uid, String packageName) {
18408                return true;
18409            }
18410        });
18411
18412        // Now that we're mostly running, clean up stale users and apps
18413        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18414        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18415    }
18416
18417    @Override
18418    public boolean isSafeMode() {
18419        return mSafeMode;
18420    }
18421
18422    @Override
18423    public boolean hasSystemUidErrors() {
18424        return mHasSystemUidErrors;
18425    }
18426
18427    static String arrayToString(int[] array) {
18428        StringBuffer buf = new StringBuffer(128);
18429        buf.append('[');
18430        if (array != null) {
18431            for (int i=0; i<array.length; i++) {
18432                if (i > 0) buf.append(", ");
18433                buf.append(array[i]);
18434            }
18435        }
18436        buf.append(']');
18437        return buf.toString();
18438    }
18439
18440    static class DumpState {
18441        public static final int DUMP_LIBS = 1 << 0;
18442        public static final int DUMP_FEATURES = 1 << 1;
18443        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18444        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18445        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18446        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18447        public static final int DUMP_PERMISSIONS = 1 << 6;
18448        public static final int DUMP_PACKAGES = 1 << 7;
18449        public static final int DUMP_SHARED_USERS = 1 << 8;
18450        public static final int DUMP_MESSAGES = 1 << 9;
18451        public static final int DUMP_PROVIDERS = 1 << 10;
18452        public static final int DUMP_VERIFIERS = 1 << 11;
18453        public static final int DUMP_PREFERRED = 1 << 12;
18454        public static final int DUMP_PREFERRED_XML = 1 << 13;
18455        public static final int DUMP_KEYSETS = 1 << 14;
18456        public static final int DUMP_VERSION = 1 << 15;
18457        public static final int DUMP_INSTALLS = 1 << 16;
18458        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18459        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18460        public static final int DUMP_FROZEN = 1 << 19;
18461        public static final int DUMP_DEXOPT = 1 << 20;
18462        public static final int DUMP_COMPILER_STATS = 1 << 21;
18463
18464        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18465
18466        private int mTypes;
18467
18468        private int mOptions;
18469
18470        private boolean mTitlePrinted;
18471
18472        private SharedUserSetting mSharedUser;
18473
18474        public boolean isDumping(int type) {
18475            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18476                return true;
18477            }
18478
18479            return (mTypes & type) != 0;
18480        }
18481
18482        public void setDump(int type) {
18483            mTypes |= type;
18484        }
18485
18486        public boolean isOptionEnabled(int option) {
18487            return (mOptions & option) != 0;
18488        }
18489
18490        public void setOptionEnabled(int option) {
18491            mOptions |= option;
18492        }
18493
18494        public boolean onTitlePrinted() {
18495            final boolean printed = mTitlePrinted;
18496            mTitlePrinted = true;
18497            return printed;
18498        }
18499
18500        public boolean getTitlePrinted() {
18501            return mTitlePrinted;
18502        }
18503
18504        public void setTitlePrinted(boolean enabled) {
18505            mTitlePrinted = enabled;
18506        }
18507
18508        public SharedUserSetting getSharedUser() {
18509            return mSharedUser;
18510        }
18511
18512        public void setSharedUser(SharedUserSetting user) {
18513            mSharedUser = user;
18514        }
18515    }
18516
18517    @Override
18518    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18519            FileDescriptor err, String[] args, ShellCallback callback,
18520            ResultReceiver resultReceiver) {
18521        (new PackageManagerShellCommand(this)).exec(
18522                this, in, out, err, args, callback, resultReceiver);
18523    }
18524
18525    @Override
18526    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18527        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18528                != PackageManager.PERMISSION_GRANTED) {
18529            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18530                    + Binder.getCallingPid()
18531                    + ", uid=" + Binder.getCallingUid()
18532                    + " without permission "
18533                    + android.Manifest.permission.DUMP);
18534            return;
18535        }
18536
18537        DumpState dumpState = new DumpState();
18538        boolean fullPreferred = false;
18539        boolean checkin = false;
18540
18541        String packageName = null;
18542        ArraySet<String> permissionNames = null;
18543
18544        int opti = 0;
18545        while (opti < args.length) {
18546            String opt = args[opti];
18547            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18548                break;
18549            }
18550            opti++;
18551
18552            if ("-a".equals(opt)) {
18553                // Right now we only know how to print all.
18554            } else if ("-h".equals(opt)) {
18555                pw.println("Package manager dump options:");
18556                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18557                pw.println("    --checkin: dump for a checkin");
18558                pw.println("    -f: print details of intent filters");
18559                pw.println("    -h: print this help");
18560                pw.println("  cmd may be one of:");
18561                pw.println("    l[ibraries]: list known shared libraries");
18562                pw.println("    f[eatures]: list device features");
18563                pw.println("    k[eysets]: print known keysets");
18564                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18565                pw.println("    perm[issions]: dump permissions");
18566                pw.println("    permission [name ...]: dump declaration and use of given permission");
18567                pw.println("    pref[erred]: print preferred package settings");
18568                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18569                pw.println("    prov[iders]: dump content providers");
18570                pw.println("    p[ackages]: dump installed packages");
18571                pw.println("    s[hared-users]: dump shared user IDs");
18572                pw.println("    m[essages]: print collected runtime messages");
18573                pw.println("    v[erifiers]: print package verifier info");
18574                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18575                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18576                pw.println("    version: print database version info");
18577                pw.println("    write: write current settings now");
18578                pw.println("    installs: details about install sessions");
18579                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18580                pw.println("    dexopt: dump dexopt state");
18581                pw.println("    compiler-stats: dump compiler statistics");
18582                pw.println("    <package.name>: info about given package");
18583                return;
18584            } else if ("--checkin".equals(opt)) {
18585                checkin = true;
18586            } else if ("-f".equals(opt)) {
18587                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18588            } else {
18589                pw.println("Unknown argument: " + opt + "; use -h for help");
18590            }
18591        }
18592
18593        // Is the caller requesting to dump a particular piece of data?
18594        if (opti < args.length) {
18595            String cmd = args[opti];
18596            opti++;
18597            // Is this a package name?
18598            if ("android".equals(cmd) || cmd.contains(".")) {
18599                packageName = cmd;
18600                // When dumping a single package, we always dump all of its
18601                // filter information since the amount of data will be reasonable.
18602                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18603            } else if ("check-permission".equals(cmd)) {
18604                if (opti >= args.length) {
18605                    pw.println("Error: check-permission missing permission argument");
18606                    return;
18607                }
18608                String perm = args[opti];
18609                opti++;
18610                if (opti >= args.length) {
18611                    pw.println("Error: check-permission missing package argument");
18612                    return;
18613                }
18614                String pkg = args[opti];
18615                opti++;
18616                int user = UserHandle.getUserId(Binder.getCallingUid());
18617                if (opti < args.length) {
18618                    try {
18619                        user = Integer.parseInt(args[opti]);
18620                    } catch (NumberFormatException e) {
18621                        pw.println("Error: check-permission user argument is not a number: "
18622                                + args[opti]);
18623                        return;
18624                    }
18625                }
18626                pw.println(checkPermission(perm, pkg, user));
18627                return;
18628            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18629                dumpState.setDump(DumpState.DUMP_LIBS);
18630            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18631                dumpState.setDump(DumpState.DUMP_FEATURES);
18632            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18633                if (opti >= args.length) {
18634                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18635                            | DumpState.DUMP_SERVICE_RESOLVERS
18636                            | DumpState.DUMP_RECEIVER_RESOLVERS
18637                            | DumpState.DUMP_CONTENT_RESOLVERS);
18638                } else {
18639                    while (opti < args.length) {
18640                        String name = args[opti];
18641                        if ("a".equals(name) || "activity".equals(name)) {
18642                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18643                        } else if ("s".equals(name) || "service".equals(name)) {
18644                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18645                        } else if ("r".equals(name) || "receiver".equals(name)) {
18646                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18647                        } else if ("c".equals(name) || "content".equals(name)) {
18648                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18649                        } else {
18650                            pw.println("Error: unknown resolver table type: " + name);
18651                            return;
18652                        }
18653                        opti++;
18654                    }
18655                }
18656            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18657                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18658            } else if ("permission".equals(cmd)) {
18659                if (opti >= args.length) {
18660                    pw.println("Error: permission requires permission name");
18661                    return;
18662                }
18663                permissionNames = new ArraySet<>();
18664                while (opti < args.length) {
18665                    permissionNames.add(args[opti]);
18666                    opti++;
18667                }
18668                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18669                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18670            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18671                dumpState.setDump(DumpState.DUMP_PREFERRED);
18672            } else if ("preferred-xml".equals(cmd)) {
18673                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18674                if (opti < args.length && "--full".equals(args[opti])) {
18675                    fullPreferred = true;
18676                    opti++;
18677                }
18678            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18679                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18680            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18681                dumpState.setDump(DumpState.DUMP_PACKAGES);
18682            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18683                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18684            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18685                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18686            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18687                dumpState.setDump(DumpState.DUMP_MESSAGES);
18688            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18689                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18690            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18691                    || "intent-filter-verifiers".equals(cmd)) {
18692                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18693            } else if ("version".equals(cmd)) {
18694                dumpState.setDump(DumpState.DUMP_VERSION);
18695            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18696                dumpState.setDump(DumpState.DUMP_KEYSETS);
18697            } else if ("installs".equals(cmd)) {
18698                dumpState.setDump(DumpState.DUMP_INSTALLS);
18699            } else if ("frozen".equals(cmd)) {
18700                dumpState.setDump(DumpState.DUMP_FROZEN);
18701            } else if ("dexopt".equals(cmd)) {
18702                dumpState.setDump(DumpState.DUMP_DEXOPT);
18703            } else if ("compiler-stats".equals(cmd)) {
18704                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18705            } else if ("write".equals(cmd)) {
18706                synchronized (mPackages) {
18707                    mSettings.writeLPr();
18708                    pw.println("Settings written.");
18709                    return;
18710                }
18711            }
18712        }
18713
18714        if (checkin) {
18715            pw.println("vers,1");
18716        }
18717
18718        // reader
18719        synchronized (mPackages) {
18720            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18721                if (!checkin) {
18722                    if (dumpState.onTitlePrinted())
18723                        pw.println();
18724                    pw.println("Database versions:");
18725                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18726                }
18727            }
18728
18729            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18730                if (!checkin) {
18731                    if (dumpState.onTitlePrinted())
18732                        pw.println();
18733                    pw.println("Verifiers:");
18734                    pw.print("  Required: ");
18735                    pw.print(mRequiredVerifierPackage);
18736                    pw.print(" (uid=");
18737                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18738                            UserHandle.USER_SYSTEM));
18739                    pw.println(")");
18740                } else if (mRequiredVerifierPackage != null) {
18741                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18742                    pw.print(",");
18743                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18744                            UserHandle.USER_SYSTEM));
18745                }
18746            }
18747
18748            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18749                    packageName == null) {
18750                if (mIntentFilterVerifierComponent != null) {
18751                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18752                    if (!checkin) {
18753                        if (dumpState.onTitlePrinted())
18754                            pw.println();
18755                        pw.println("Intent Filter Verifier:");
18756                        pw.print("  Using: ");
18757                        pw.print(verifierPackageName);
18758                        pw.print(" (uid=");
18759                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18760                                UserHandle.USER_SYSTEM));
18761                        pw.println(")");
18762                    } else if (verifierPackageName != null) {
18763                        pw.print("ifv,"); pw.print(verifierPackageName);
18764                        pw.print(",");
18765                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18766                                UserHandle.USER_SYSTEM));
18767                    }
18768                } else {
18769                    pw.println();
18770                    pw.println("No Intent Filter Verifier available!");
18771                }
18772            }
18773
18774            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18775                boolean printedHeader = false;
18776                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18777                while (it.hasNext()) {
18778                    String name = it.next();
18779                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18780                    if (!checkin) {
18781                        if (!printedHeader) {
18782                            if (dumpState.onTitlePrinted())
18783                                pw.println();
18784                            pw.println("Libraries:");
18785                            printedHeader = true;
18786                        }
18787                        pw.print("  ");
18788                    } else {
18789                        pw.print("lib,");
18790                    }
18791                    pw.print(name);
18792                    if (!checkin) {
18793                        pw.print(" -> ");
18794                    }
18795                    if (ent.path != null) {
18796                        if (!checkin) {
18797                            pw.print("(jar) ");
18798                            pw.print(ent.path);
18799                        } else {
18800                            pw.print(",jar,");
18801                            pw.print(ent.path);
18802                        }
18803                    } else {
18804                        if (!checkin) {
18805                            pw.print("(apk) ");
18806                            pw.print(ent.apk);
18807                        } else {
18808                            pw.print(",apk,");
18809                            pw.print(ent.apk);
18810                        }
18811                    }
18812                    pw.println();
18813                }
18814            }
18815
18816            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18817                if (dumpState.onTitlePrinted())
18818                    pw.println();
18819                if (!checkin) {
18820                    pw.println("Features:");
18821                }
18822
18823                for (FeatureInfo feat : mAvailableFeatures.values()) {
18824                    if (checkin) {
18825                        pw.print("feat,");
18826                        pw.print(feat.name);
18827                        pw.print(",");
18828                        pw.println(feat.version);
18829                    } else {
18830                        pw.print("  ");
18831                        pw.print(feat.name);
18832                        if (feat.version > 0) {
18833                            pw.print(" version=");
18834                            pw.print(feat.version);
18835                        }
18836                        pw.println();
18837                    }
18838                }
18839            }
18840
18841            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18842                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18843                        : "Activity Resolver Table:", "  ", packageName,
18844                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18845                    dumpState.setTitlePrinted(true);
18846                }
18847            }
18848            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18849                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18850                        : "Receiver Resolver Table:", "  ", packageName,
18851                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18852                    dumpState.setTitlePrinted(true);
18853                }
18854            }
18855            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18856                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18857                        : "Service Resolver Table:", "  ", packageName,
18858                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18859                    dumpState.setTitlePrinted(true);
18860                }
18861            }
18862            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18863                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18864                        : "Provider Resolver Table:", "  ", packageName,
18865                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18866                    dumpState.setTitlePrinted(true);
18867                }
18868            }
18869
18870            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18871                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18872                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18873                    int user = mSettings.mPreferredActivities.keyAt(i);
18874                    if (pir.dump(pw,
18875                            dumpState.getTitlePrinted()
18876                                ? "\nPreferred Activities User " + user + ":"
18877                                : "Preferred Activities User " + user + ":", "  ",
18878                            packageName, true, false)) {
18879                        dumpState.setTitlePrinted(true);
18880                    }
18881                }
18882            }
18883
18884            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18885                pw.flush();
18886                FileOutputStream fout = new FileOutputStream(fd);
18887                BufferedOutputStream str = new BufferedOutputStream(fout);
18888                XmlSerializer serializer = new FastXmlSerializer();
18889                try {
18890                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18891                    serializer.startDocument(null, true);
18892                    serializer.setFeature(
18893                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18894                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18895                    serializer.endDocument();
18896                    serializer.flush();
18897                } catch (IllegalArgumentException e) {
18898                    pw.println("Failed writing: " + e);
18899                } catch (IllegalStateException e) {
18900                    pw.println("Failed writing: " + e);
18901                } catch (IOException e) {
18902                    pw.println("Failed writing: " + e);
18903                }
18904            }
18905
18906            if (!checkin
18907                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18908                    && packageName == null) {
18909                pw.println();
18910                int count = mSettings.mPackages.size();
18911                if (count == 0) {
18912                    pw.println("No applications!");
18913                    pw.println();
18914                } else {
18915                    final String prefix = "  ";
18916                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18917                    if (allPackageSettings.size() == 0) {
18918                        pw.println("No domain preferred apps!");
18919                        pw.println();
18920                    } else {
18921                        pw.println("App verification status:");
18922                        pw.println();
18923                        count = 0;
18924                        for (PackageSetting ps : allPackageSettings) {
18925                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18926                            if (ivi == null || ivi.getPackageName() == null) continue;
18927                            pw.println(prefix + "Package: " + ivi.getPackageName());
18928                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18929                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18930                            pw.println();
18931                            count++;
18932                        }
18933                        if (count == 0) {
18934                            pw.println(prefix + "No app verification established.");
18935                            pw.println();
18936                        }
18937                        for (int userId : sUserManager.getUserIds()) {
18938                            pw.println("App linkages for user " + userId + ":");
18939                            pw.println();
18940                            count = 0;
18941                            for (PackageSetting ps : allPackageSettings) {
18942                                final long status = ps.getDomainVerificationStatusForUser(userId);
18943                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18944                                    continue;
18945                                }
18946                                pw.println(prefix + "Package: " + ps.name);
18947                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18948                                String statusStr = IntentFilterVerificationInfo.
18949                                        getStatusStringFromValue(status);
18950                                pw.println(prefix + "Status:  " + statusStr);
18951                                pw.println();
18952                                count++;
18953                            }
18954                            if (count == 0) {
18955                                pw.println(prefix + "No configured app linkages.");
18956                                pw.println();
18957                            }
18958                        }
18959                    }
18960                }
18961            }
18962
18963            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18964                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18965                if (packageName == null && permissionNames == null) {
18966                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18967                        if (iperm == 0) {
18968                            if (dumpState.onTitlePrinted())
18969                                pw.println();
18970                            pw.println("AppOp Permissions:");
18971                        }
18972                        pw.print("  AppOp Permission ");
18973                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18974                        pw.println(":");
18975                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18976                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18977                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18978                        }
18979                    }
18980                }
18981            }
18982
18983            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18984                boolean printedSomething = false;
18985                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18986                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18987                        continue;
18988                    }
18989                    if (!printedSomething) {
18990                        if (dumpState.onTitlePrinted())
18991                            pw.println();
18992                        pw.println("Registered ContentProviders:");
18993                        printedSomething = true;
18994                    }
18995                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18996                    pw.print("    "); pw.println(p.toString());
18997                }
18998                printedSomething = false;
18999                for (Map.Entry<String, PackageParser.Provider> entry :
19000                        mProvidersByAuthority.entrySet()) {
19001                    PackageParser.Provider p = entry.getValue();
19002                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19003                        continue;
19004                    }
19005                    if (!printedSomething) {
19006                        if (dumpState.onTitlePrinted())
19007                            pw.println();
19008                        pw.println("ContentProvider Authorities:");
19009                        printedSomething = true;
19010                    }
19011                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19012                    pw.print("    "); pw.println(p.toString());
19013                    if (p.info != null && p.info.applicationInfo != null) {
19014                        final String appInfo = p.info.applicationInfo.toString();
19015                        pw.print("      applicationInfo="); pw.println(appInfo);
19016                    }
19017                }
19018            }
19019
19020            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19021                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19022            }
19023
19024            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19025                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19026            }
19027
19028            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19029                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19030            }
19031
19032            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19033                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19034            }
19035
19036            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19037                // XXX should handle packageName != null by dumping only install data that
19038                // the given package is involved with.
19039                if (dumpState.onTitlePrinted()) pw.println();
19040                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19041            }
19042
19043            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19044                // XXX should handle packageName != null by dumping only install data that
19045                // the given package is involved with.
19046                if (dumpState.onTitlePrinted()) pw.println();
19047
19048                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19049                ipw.println();
19050                ipw.println("Frozen packages:");
19051                ipw.increaseIndent();
19052                if (mFrozenPackages.size() == 0) {
19053                    ipw.println("(none)");
19054                } else {
19055                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19056                        ipw.println(mFrozenPackages.valueAt(i));
19057                    }
19058                }
19059                ipw.decreaseIndent();
19060            }
19061
19062            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19063                if (dumpState.onTitlePrinted()) pw.println();
19064                dumpDexoptStateLPr(pw, packageName);
19065            }
19066
19067            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19068                if (dumpState.onTitlePrinted()) pw.println();
19069                dumpCompilerStatsLPr(pw, packageName);
19070            }
19071
19072            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19073                if (dumpState.onTitlePrinted()) pw.println();
19074                mSettings.dumpReadMessagesLPr(pw, dumpState);
19075
19076                pw.println();
19077                pw.println("Package warning messages:");
19078                BufferedReader in = null;
19079                String line = null;
19080                try {
19081                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19082                    while ((line = in.readLine()) != null) {
19083                        if (line.contains("ignored: updated version")) continue;
19084                        pw.println(line);
19085                    }
19086                } catch (IOException ignored) {
19087                } finally {
19088                    IoUtils.closeQuietly(in);
19089                }
19090            }
19091
19092            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19093                BufferedReader in = null;
19094                String line = null;
19095                try {
19096                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19097                    while ((line = in.readLine()) != null) {
19098                        if (line.contains("ignored: updated version")) continue;
19099                        pw.print("msg,");
19100                        pw.println(line);
19101                    }
19102                } catch (IOException ignored) {
19103                } finally {
19104                    IoUtils.closeQuietly(in);
19105                }
19106            }
19107        }
19108    }
19109
19110    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19111        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19112        ipw.println();
19113        ipw.println("Dexopt state:");
19114        ipw.increaseIndent();
19115        Collection<PackageParser.Package> packages = null;
19116        if (packageName != null) {
19117            PackageParser.Package targetPackage = mPackages.get(packageName);
19118            if (targetPackage != null) {
19119                packages = Collections.singletonList(targetPackage);
19120            } else {
19121                ipw.println("Unable to find package: " + packageName);
19122                return;
19123            }
19124        } else {
19125            packages = mPackages.values();
19126        }
19127
19128        for (PackageParser.Package pkg : packages) {
19129            ipw.println("[" + pkg.packageName + "]");
19130            ipw.increaseIndent();
19131            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19132            ipw.decreaseIndent();
19133        }
19134    }
19135
19136    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19137        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19138        ipw.println();
19139        ipw.println("Compiler stats:");
19140        ipw.increaseIndent();
19141        Collection<PackageParser.Package> packages = null;
19142        if (packageName != null) {
19143            PackageParser.Package targetPackage = mPackages.get(packageName);
19144            if (targetPackage != null) {
19145                packages = Collections.singletonList(targetPackage);
19146            } else {
19147                ipw.println("Unable to find package: " + packageName);
19148                return;
19149            }
19150        } else {
19151            packages = mPackages.values();
19152        }
19153
19154        for (PackageParser.Package pkg : packages) {
19155            ipw.println("[" + pkg.packageName + "]");
19156            ipw.increaseIndent();
19157
19158            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19159            if (stats == null) {
19160                ipw.println("(No recorded stats)");
19161            } else {
19162                stats.dump(ipw);
19163            }
19164            ipw.decreaseIndent();
19165        }
19166    }
19167
19168    private String dumpDomainString(String packageName) {
19169        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19170                .getList();
19171        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19172
19173        ArraySet<String> result = new ArraySet<>();
19174        if (iviList.size() > 0) {
19175            for (IntentFilterVerificationInfo ivi : iviList) {
19176                for (String host : ivi.getDomains()) {
19177                    result.add(host);
19178                }
19179            }
19180        }
19181        if (filters != null && filters.size() > 0) {
19182            for (IntentFilter filter : filters) {
19183                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19184                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19185                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19186                    result.addAll(filter.getHostsList());
19187                }
19188            }
19189        }
19190
19191        StringBuilder sb = new StringBuilder(result.size() * 16);
19192        for (String domain : result) {
19193            if (sb.length() > 0) sb.append(" ");
19194            sb.append(domain);
19195        }
19196        return sb.toString();
19197    }
19198
19199    // ------- apps on sdcard specific code -------
19200    static final boolean DEBUG_SD_INSTALL = false;
19201
19202    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19203
19204    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19205
19206    private boolean mMediaMounted = false;
19207
19208    static String getEncryptKey() {
19209        try {
19210            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19211                    SD_ENCRYPTION_KEYSTORE_NAME);
19212            if (sdEncKey == null) {
19213                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19214                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19215                if (sdEncKey == null) {
19216                    Slog.e(TAG, "Failed to create encryption keys");
19217                    return null;
19218                }
19219            }
19220            return sdEncKey;
19221        } catch (NoSuchAlgorithmException nsae) {
19222            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19223            return null;
19224        } catch (IOException ioe) {
19225            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19226            return null;
19227        }
19228    }
19229
19230    /*
19231     * Update media status on PackageManager.
19232     */
19233    @Override
19234    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19235        int callingUid = Binder.getCallingUid();
19236        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19237            throw new SecurityException("Media status can only be updated by the system");
19238        }
19239        // reader; this apparently protects mMediaMounted, but should probably
19240        // be a different lock in that case.
19241        synchronized (mPackages) {
19242            Log.i(TAG, "Updating external media status from "
19243                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19244                    + (mediaStatus ? "mounted" : "unmounted"));
19245            if (DEBUG_SD_INSTALL)
19246                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19247                        + ", mMediaMounted=" + mMediaMounted);
19248            if (mediaStatus == mMediaMounted) {
19249                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19250                        : 0, -1);
19251                mHandler.sendMessage(msg);
19252                return;
19253            }
19254            mMediaMounted = mediaStatus;
19255        }
19256        // Queue up an async operation since the package installation may take a
19257        // little while.
19258        mHandler.post(new Runnable() {
19259            public void run() {
19260                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19261            }
19262        });
19263    }
19264
19265    /**
19266     * Called by StorageManagerService when the initial ASECs to scan are available.
19267     * Should block until all the ASEC containers are finished being scanned.
19268     */
19269    public void scanAvailableAsecs() {
19270        updateExternalMediaStatusInner(true, false, false);
19271    }
19272
19273    /*
19274     * Collect information of applications on external media, map them against
19275     * existing containers and update information based on current mount status.
19276     * Please note that we always have to report status if reportStatus has been
19277     * set to true especially when unloading packages.
19278     */
19279    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19280            boolean externalStorage) {
19281        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19282        int[] uidArr = EmptyArray.INT;
19283
19284        final String[] list = PackageHelper.getSecureContainerList();
19285        if (ArrayUtils.isEmpty(list)) {
19286            Log.i(TAG, "No secure containers found");
19287        } else {
19288            // Process list of secure containers and categorize them
19289            // as active or stale based on their package internal state.
19290
19291            // reader
19292            synchronized (mPackages) {
19293                for (String cid : list) {
19294                    // Leave stages untouched for now; installer service owns them
19295                    if (PackageInstallerService.isStageName(cid)) continue;
19296
19297                    if (DEBUG_SD_INSTALL)
19298                        Log.i(TAG, "Processing container " + cid);
19299                    String pkgName = getAsecPackageName(cid);
19300                    if (pkgName == null) {
19301                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19302                        continue;
19303                    }
19304                    if (DEBUG_SD_INSTALL)
19305                        Log.i(TAG, "Looking for pkg : " + pkgName);
19306
19307                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19308                    if (ps == null) {
19309                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19310                        continue;
19311                    }
19312
19313                    /*
19314                     * Skip packages that are not external if we're unmounting
19315                     * external storage.
19316                     */
19317                    if (externalStorage && !isMounted && !isExternal(ps)) {
19318                        continue;
19319                    }
19320
19321                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19322                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19323                    // The package status is changed only if the code path
19324                    // matches between settings and the container id.
19325                    if (ps.codePathString != null
19326                            && ps.codePathString.startsWith(args.getCodePath())) {
19327                        if (DEBUG_SD_INSTALL) {
19328                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19329                                    + " at code path: " + ps.codePathString);
19330                        }
19331
19332                        // We do have a valid package installed on sdcard
19333                        processCids.put(args, ps.codePathString);
19334                        final int uid = ps.appId;
19335                        if (uid != -1) {
19336                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19337                        }
19338                    } else {
19339                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19340                                + ps.codePathString);
19341                    }
19342                }
19343            }
19344
19345            Arrays.sort(uidArr);
19346        }
19347
19348        // Process packages with valid entries.
19349        if (isMounted) {
19350            if (DEBUG_SD_INSTALL)
19351                Log.i(TAG, "Loading packages");
19352            loadMediaPackages(processCids, uidArr, externalStorage);
19353            startCleaningPackages();
19354            mInstallerService.onSecureContainersAvailable();
19355        } else {
19356            if (DEBUG_SD_INSTALL)
19357                Log.i(TAG, "Unloading packages");
19358            unloadMediaPackages(processCids, uidArr, reportStatus);
19359        }
19360    }
19361
19362    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19363            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19364        final int size = infos.size();
19365        final String[] packageNames = new String[size];
19366        final int[] packageUids = new int[size];
19367        for (int i = 0; i < size; i++) {
19368            final ApplicationInfo info = infos.get(i);
19369            packageNames[i] = info.packageName;
19370            packageUids[i] = info.uid;
19371        }
19372        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19373                finishedReceiver);
19374    }
19375
19376    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19377            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19378        sendResourcesChangedBroadcast(mediaStatus, replacing,
19379                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19380    }
19381
19382    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19383            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19384        int size = pkgList.length;
19385        if (size > 0) {
19386            // Send broadcasts here
19387            Bundle extras = new Bundle();
19388            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19389            if (uidArr != null) {
19390                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19391            }
19392            if (replacing) {
19393                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19394            }
19395            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19396                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19397            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19398        }
19399    }
19400
19401   /*
19402     * Look at potentially valid container ids from processCids If package
19403     * information doesn't match the one on record or package scanning fails,
19404     * the cid is added to list of removeCids. We currently don't delete stale
19405     * containers.
19406     */
19407    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19408            boolean externalStorage) {
19409        ArrayList<String> pkgList = new ArrayList<String>();
19410        Set<AsecInstallArgs> keys = processCids.keySet();
19411
19412        for (AsecInstallArgs args : keys) {
19413            String codePath = processCids.get(args);
19414            if (DEBUG_SD_INSTALL)
19415                Log.i(TAG, "Loading container : " + args.cid);
19416            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19417            try {
19418                // Make sure there are no container errors first.
19419                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19420                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19421                            + " when installing from sdcard");
19422                    continue;
19423                }
19424                // Check code path here.
19425                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19426                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19427                            + " does not match one in settings " + codePath);
19428                    continue;
19429                }
19430                // Parse package
19431                int parseFlags = mDefParseFlags;
19432                if (args.isExternalAsec()) {
19433                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19434                }
19435                if (args.isFwdLocked()) {
19436                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19437                }
19438
19439                synchronized (mInstallLock) {
19440                    PackageParser.Package pkg = null;
19441                    try {
19442                        // Sadly we don't know the package name yet to freeze it
19443                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19444                                SCAN_IGNORE_FROZEN, 0, null);
19445                    } catch (PackageManagerException e) {
19446                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19447                    }
19448                    // Scan the package
19449                    if (pkg != null) {
19450                        /*
19451                         * TODO why is the lock being held? doPostInstall is
19452                         * called in other places without the lock. This needs
19453                         * to be straightened out.
19454                         */
19455                        // writer
19456                        synchronized (mPackages) {
19457                            retCode = PackageManager.INSTALL_SUCCEEDED;
19458                            pkgList.add(pkg.packageName);
19459                            // Post process args
19460                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19461                                    pkg.applicationInfo.uid);
19462                        }
19463                    } else {
19464                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19465                    }
19466                }
19467
19468            } finally {
19469                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19470                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19471                }
19472            }
19473        }
19474        // writer
19475        synchronized (mPackages) {
19476            // If the platform SDK has changed since the last time we booted,
19477            // we need to re-grant app permission to catch any new ones that
19478            // appear. This is really a hack, and means that apps can in some
19479            // cases get permissions that the user didn't initially explicitly
19480            // allow... it would be nice to have some better way to handle
19481            // this situation.
19482            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19483                    : mSettings.getInternalVersion();
19484            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19485                    : StorageManager.UUID_PRIVATE_INTERNAL;
19486
19487            int updateFlags = UPDATE_PERMISSIONS_ALL;
19488            if (ver.sdkVersion != mSdkVersion) {
19489                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19490                        + mSdkVersion + "; regranting permissions for external");
19491                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19492            }
19493            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19494
19495            // Yay, everything is now upgraded
19496            ver.forceCurrent();
19497
19498            // can downgrade to reader
19499            // Persist settings
19500            mSettings.writeLPr();
19501        }
19502        // Send a broadcast to let everyone know we are done processing
19503        if (pkgList.size() > 0) {
19504            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19505        }
19506    }
19507
19508   /*
19509     * Utility method to unload a list of specified containers
19510     */
19511    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19512        // Just unmount all valid containers.
19513        for (AsecInstallArgs arg : cidArgs) {
19514            synchronized (mInstallLock) {
19515                arg.doPostDeleteLI(false);
19516           }
19517       }
19518   }
19519
19520    /*
19521     * Unload packages mounted on external media. This involves deleting package
19522     * data from internal structures, sending broadcasts about disabled packages,
19523     * gc'ing to free up references, unmounting all secure containers
19524     * corresponding to packages on external media, and posting a
19525     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19526     * that we always have to post this message if status has been requested no
19527     * matter what.
19528     */
19529    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19530            final boolean reportStatus) {
19531        if (DEBUG_SD_INSTALL)
19532            Log.i(TAG, "unloading media packages");
19533        ArrayList<String> pkgList = new ArrayList<String>();
19534        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19535        final Set<AsecInstallArgs> keys = processCids.keySet();
19536        for (AsecInstallArgs args : keys) {
19537            String pkgName = args.getPackageName();
19538            if (DEBUG_SD_INSTALL)
19539                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19540            // Delete package internally
19541            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19542            synchronized (mInstallLock) {
19543                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19544                final boolean res;
19545                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19546                        "unloadMediaPackages")) {
19547                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19548                            null);
19549                }
19550                if (res) {
19551                    pkgList.add(pkgName);
19552                } else {
19553                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19554                    failedList.add(args);
19555                }
19556            }
19557        }
19558
19559        // reader
19560        synchronized (mPackages) {
19561            // We didn't update the settings after removing each package;
19562            // write them now for all packages.
19563            mSettings.writeLPr();
19564        }
19565
19566        // We have to absolutely send UPDATED_MEDIA_STATUS only
19567        // after confirming that all the receivers processed the ordered
19568        // broadcast when packages get disabled, force a gc to clean things up.
19569        // and unload all the containers.
19570        if (pkgList.size() > 0) {
19571            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19572                    new IIntentReceiver.Stub() {
19573                public void performReceive(Intent intent, int resultCode, String data,
19574                        Bundle extras, boolean ordered, boolean sticky,
19575                        int sendingUser) throws RemoteException {
19576                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19577                            reportStatus ? 1 : 0, 1, keys);
19578                    mHandler.sendMessage(msg);
19579                }
19580            });
19581        } else {
19582            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19583                    keys);
19584            mHandler.sendMessage(msg);
19585        }
19586    }
19587
19588    private void loadPrivatePackages(final VolumeInfo vol) {
19589        mHandler.post(new Runnable() {
19590            @Override
19591            public void run() {
19592                loadPrivatePackagesInner(vol);
19593            }
19594        });
19595    }
19596
19597    private void loadPrivatePackagesInner(VolumeInfo vol) {
19598        final String volumeUuid = vol.fsUuid;
19599        if (TextUtils.isEmpty(volumeUuid)) {
19600            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19601            return;
19602        }
19603
19604        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19605        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19606        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19607
19608        final VersionInfo ver;
19609        final List<PackageSetting> packages;
19610        synchronized (mPackages) {
19611            ver = mSettings.findOrCreateVersion(volumeUuid);
19612            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19613        }
19614
19615        for (PackageSetting ps : packages) {
19616            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19617            synchronized (mInstallLock) {
19618                final PackageParser.Package pkg;
19619                try {
19620                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19621                    loaded.add(pkg.applicationInfo);
19622
19623                } catch (PackageManagerException e) {
19624                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19625                }
19626
19627                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19628                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19629                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19630                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19631                }
19632            }
19633        }
19634
19635        // Reconcile app data for all started/unlocked users
19636        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19637        final UserManager um = mContext.getSystemService(UserManager.class);
19638        UserManagerInternal umInternal = getUserManagerInternal();
19639        for (UserInfo user : um.getUsers()) {
19640            final int flags;
19641            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19642                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19643            } else if (umInternal.isUserRunning(user.id)) {
19644                flags = StorageManager.FLAG_STORAGE_DE;
19645            } else {
19646                continue;
19647            }
19648
19649            try {
19650                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19651                synchronized (mInstallLock) {
19652                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19653                }
19654            } catch (IllegalStateException e) {
19655                // Device was probably ejected, and we'll process that event momentarily
19656                Slog.w(TAG, "Failed to prepare storage: " + e);
19657            }
19658        }
19659
19660        synchronized (mPackages) {
19661            int updateFlags = UPDATE_PERMISSIONS_ALL;
19662            if (ver.sdkVersion != mSdkVersion) {
19663                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19664                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19665                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19666            }
19667            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19668
19669            // Yay, everything is now upgraded
19670            ver.forceCurrent();
19671
19672            mSettings.writeLPr();
19673        }
19674
19675        for (PackageFreezer freezer : freezers) {
19676            freezer.close();
19677        }
19678
19679        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19680        sendResourcesChangedBroadcast(true, false, loaded, null);
19681    }
19682
19683    private void unloadPrivatePackages(final VolumeInfo vol) {
19684        mHandler.post(new Runnable() {
19685            @Override
19686            public void run() {
19687                unloadPrivatePackagesInner(vol);
19688            }
19689        });
19690    }
19691
19692    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19693        final String volumeUuid = vol.fsUuid;
19694        if (TextUtils.isEmpty(volumeUuid)) {
19695            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19696            return;
19697        }
19698
19699        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19700        synchronized (mInstallLock) {
19701        synchronized (mPackages) {
19702            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19703            for (PackageSetting ps : packages) {
19704                if (ps.pkg == null) continue;
19705
19706                final ApplicationInfo info = ps.pkg.applicationInfo;
19707                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19708                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19709
19710                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19711                        "unloadPrivatePackagesInner")) {
19712                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19713                            false, null)) {
19714                        unloaded.add(info);
19715                    } else {
19716                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19717                    }
19718                }
19719
19720                // Try very hard to release any references to this package
19721                // so we don't risk the system server being killed due to
19722                // open FDs
19723                AttributeCache.instance().removePackage(ps.name);
19724            }
19725
19726            mSettings.writeLPr();
19727        }
19728        }
19729
19730        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19731        sendResourcesChangedBroadcast(false, false, unloaded, null);
19732
19733        // Try very hard to release any references to this path so we don't risk
19734        // the system server being killed due to open FDs
19735        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19736
19737        for (int i = 0; i < 3; i++) {
19738            System.gc();
19739            System.runFinalization();
19740        }
19741    }
19742
19743    /**
19744     * Prepare storage areas for given user on all mounted devices.
19745     */
19746    void prepareUserData(int userId, int userSerial, int flags) {
19747        synchronized (mInstallLock) {
19748            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19749            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19750                final String volumeUuid = vol.getFsUuid();
19751                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19752            }
19753        }
19754    }
19755
19756    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19757            boolean allowRecover) {
19758        // Prepare storage and verify that serial numbers are consistent; if
19759        // there's a mismatch we need to destroy to avoid leaking data
19760        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19761        try {
19762            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19763
19764            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19765                UserManagerService.enforceSerialNumber(
19766                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19767                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19768                    UserManagerService.enforceSerialNumber(
19769                            Environment.getDataSystemDeDirectory(userId), userSerial);
19770                }
19771            }
19772            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19773                UserManagerService.enforceSerialNumber(
19774                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19775                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19776                    UserManagerService.enforceSerialNumber(
19777                            Environment.getDataSystemCeDirectory(userId), userSerial);
19778                }
19779            }
19780
19781            synchronized (mInstallLock) {
19782                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19783            }
19784        } catch (Exception e) {
19785            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19786                    + " because we failed to prepare: " + e);
19787            destroyUserDataLI(volumeUuid, userId,
19788                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19789
19790            if (allowRecover) {
19791                // Try one last time; if we fail again we're really in trouble
19792                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19793            }
19794        }
19795    }
19796
19797    /**
19798     * Destroy storage areas for given user on all mounted devices.
19799     */
19800    void destroyUserData(int userId, int flags) {
19801        synchronized (mInstallLock) {
19802            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19803            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19804                final String volumeUuid = vol.getFsUuid();
19805                destroyUserDataLI(volumeUuid, userId, flags);
19806            }
19807        }
19808    }
19809
19810    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19811        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19812        try {
19813            // Clean up app data, profile data, and media data
19814            mInstaller.destroyUserData(volumeUuid, userId, flags);
19815
19816            // Clean up system data
19817            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19818                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19819                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19820                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19821                }
19822                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19823                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19824                }
19825            }
19826
19827            // Data with special labels is now gone, so finish the job
19828            storage.destroyUserStorage(volumeUuid, userId, flags);
19829
19830        } catch (Exception e) {
19831            logCriticalInfo(Log.WARN,
19832                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19833        }
19834    }
19835
19836    /**
19837     * Examine all users present on given mounted volume, and destroy data
19838     * belonging to users that are no longer valid, or whose user ID has been
19839     * recycled.
19840     */
19841    private void reconcileUsers(String volumeUuid) {
19842        final List<File> files = new ArrayList<>();
19843        Collections.addAll(files, FileUtils
19844                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19845        Collections.addAll(files, FileUtils
19846                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19847        Collections.addAll(files, FileUtils
19848                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19849        Collections.addAll(files, FileUtils
19850                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19851        for (File file : files) {
19852            if (!file.isDirectory()) continue;
19853
19854            final int userId;
19855            final UserInfo info;
19856            try {
19857                userId = Integer.parseInt(file.getName());
19858                info = sUserManager.getUserInfo(userId);
19859            } catch (NumberFormatException e) {
19860                Slog.w(TAG, "Invalid user directory " + file);
19861                continue;
19862            }
19863
19864            boolean destroyUser = false;
19865            if (info == null) {
19866                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19867                        + " because no matching user was found");
19868                destroyUser = true;
19869            } else if (!mOnlyCore) {
19870                try {
19871                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19872                } catch (IOException e) {
19873                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19874                            + " because we failed to enforce serial number: " + e);
19875                    destroyUser = true;
19876                }
19877            }
19878
19879            if (destroyUser) {
19880                synchronized (mInstallLock) {
19881                    destroyUserDataLI(volumeUuid, userId,
19882                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19883                }
19884            }
19885        }
19886    }
19887
19888    private void assertPackageKnown(String volumeUuid, String packageName)
19889            throws PackageManagerException {
19890        synchronized (mPackages) {
19891            final PackageSetting ps = mSettings.mPackages.get(packageName);
19892            if (ps == null) {
19893                throw new PackageManagerException("Package " + packageName + " is unknown");
19894            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19895                throw new PackageManagerException(
19896                        "Package " + packageName + " found on unknown volume " + volumeUuid
19897                                + "; expected volume " + ps.volumeUuid);
19898            }
19899        }
19900    }
19901
19902    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19903            throws PackageManagerException {
19904        synchronized (mPackages) {
19905            final PackageSetting ps = mSettings.mPackages.get(packageName);
19906            if (ps == null) {
19907                throw new PackageManagerException("Package " + packageName + " is unknown");
19908            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19909                throw new PackageManagerException(
19910                        "Package " + packageName + " found on unknown volume " + volumeUuid
19911                                + "; expected volume " + ps.volumeUuid);
19912            } else if (!ps.getInstalled(userId)) {
19913                throw new PackageManagerException(
19914                        "Package " + packageName + " not installed for user " + userId);
19915            }
19916        }
19917    }
19918
19919    /**
19920     * Examine all apps present on given mounted volume, and destroy apps that
19921     * aren't expected, either due to uninstallation or reinstallation on
19922     * another volume.
19923     */
19924    private void reconcileApps(String volumeUuid) {
19925        final File[] files = FileUtils
19926                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19927        for (File file : files) {
19928            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19929                    && !PackageInstallerService.isStageName(file.getName());
19930            if (!isPackage) {
19931                // Ignore entries which are not packages
19932                continue;
19933            }
19934
19935            try {
19936                final PackageLite pkg = PackageParser.parsePackageLite(file,
19937                        PackageParser.PARSE_MUST_BE_APK);
19938                assertPackageKnown(volumeUuid, pkg.packageName);
19939
19940            } catch (PackageParserException | PackageManagerException e) {
19941                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19942                synchronized (mInstallLock) {
19943                    removeCodePathLI(file);
19944                }
19945            }
19946        }
19947    }
19948
19949    /**
19950     * Reconcile all app data for the given user.
19951     * <p>
19952     * Verifies that directories exist and that ownership and labeling is
19953     * correct for all installed apps on all mounted volumes.
19954     */
19955    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19956        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19957        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19958            final String volumeUuid = vol.getFsUuid();
19959            synchronized (mInstallLock) {
19960                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19961            }
19962        }
19963    }
19964
19965    /**
19966     * Reconcile all app data on given mounted volume.
19967     * <p>
19968     * Destroys app data that isn't expected, either due to uninstallation or
19969     * reinstallation on another volume.
19970     * <p>
19971     * Verifies that directories exist and that ownership and labeling is
19972     * correct for all installed apps.
19973     */
19974    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19975            boolean migrateAppData) {
19976        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19977                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19978
19979        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19980        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19981
19982        // First look for stale data that doesn't belong, and check if things
19983        // have changed since we did our last restorecon
19984        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19985            if (StorageManager.isFileEncryptedNativeOrEmulated()
19986                    && !StorageManager.isUserKeyUnlocked(userId)) {
19987                throw new RuntimeException(
19988                        "Yikes, someone asked us to reconcile CE storage while " + userId
19989                                + " was still locked; this would have caused massive data loss!");
19990            }
19991
19992            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19993            for (File file : files) {
19994                final String packageName = file.getName();
19995                try {
19996                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19997                } catch (PackageManagerException e) {
19998                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19999                    try {
20000                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20001                                StorageManager.FLAG_STORAGE_CE, 0);
20002                    } catch (InstallerException e2) {
20003                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20004                    }
20005                }
20006            }
20007        }
20008        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20009            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20010            for (File file : files) {
20011                final String packageName = file.getName();
20012                try {
20013                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20014                } catch (PackageManagerException e) {
20015                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20016                    try {
20017                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20018                                StorageManager.FLAG_STORAGE_DE, 0);
20019                    } catch (InstallerException e2) {
20020                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20021                    }
20022                }
20023            }
20024        }
20025
20026        // Ensure that data directories are ready to roll for all packages
20027        // installed for this volume and user
20028        final List<PackageSetting> packages;
20029        synchronized (mPackages) {
20030            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20031        }
20032        int preparedCount = 0;
20033        for (PackageSetting ps : packages) {
20034            final String packageName = ps.name;
20035            if (ps.pkg == null) {
20036                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20037                // TODO: might be due to legacy ASEC apps; we should circle back
20038                // and reconcile again once they're scanned
20039                continue;
20040            }
20041
20042            if (ps.getInstalled(userId)) {
20043                prepareAppDataLIF(ps.pkg, userId, flags);
20044
20045                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20046                    // We may have just shuffled around app data directories, so
20047                    // prepare them one more time
20048                    prepareAppDataLIF(ps.pkg, userId, flags);
20049                }
20050
20051                preparedCount++;
20052            }
20053        }
20054
20055        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20056    }
20057
20058    /**
20059     * Prepare app data for the given app just after it was installed or
20060     * upgraded. This method carefully only touches users that it's installed
20061     * for, and it forces a restorecon to handle any seinfo changes.
20062     * <p>
20063     * Verifies that directories exist and that ownership and labeling is
20064     * correct for all installed apps. If there is an ownership mismatch, it
20065     * will try recovering system apps by wiping data; third-party app data is
20066     * left intact.
20067     * <p>
20068     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20069     */
20070    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20071        final PackageSetting ps;
20072        synchronized (mPackages) {
20073            ps = mSettings.mPackages.get(pkg.packageName);
20074            mSettings.writeKernelMappingLPr(ps);
20075        }
20076
20077        final UserManager um = mContext.getSystemService(UserManager.class);
20078        UserManagerInternal umInternal = getUserManagerInternal();
20079        for (UserInfo user : um.getUsers()) {
20080            final int flags;
20081            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20082                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20083            } else if (umInternal.isUserRunning(user.id)) {
20084                flags = StorageManager.FLAG_STORAGE_DE;
20085            } else {
20086                continue;
20087            }
20088
20089            if (ps.getInstalled(user.id)) {
20090                // TODO: when user data is locked, mark that we're still dirty
20091                prepareAppDataLIF(pkg, user.id, flags);
20092            }
20093        }
20094    }
20095
20096    /**
20097     * Prepare app data for the given app.
20098     * <p>
20099     * Verifies that directories exist and that ownership and labeling is
20100     * correct for all installed apps. If there is an ownership mismatch, this
20101     * will try recovering system apps by wiping data; third-party app data is
20102     * left intact.
20103     */
20104    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20105        if (pkg == null) {
20106            Slog.wtf(TAG, "Package was null!", new Throwable());
20107            return;
20108        }
20109        prepareAppDataLeafLIF(pkg, userId, flags);
20110        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20111        for (int i = 0; i < childCount; i++) {
20112            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20113        }
20114    }
20115
20116    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20117        if (DEBUG_APP_DATA) {
20118            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20119                    + Integer.toHexString(flags));
20120        }
20121
20122        final String volumeUuid = pkg.volumeUuid;
20123        final String packageName = pkg.packageName;
20124        final ApplicationInfo app = pkg.applicationInfo;
20125        final int appId = UserHandle.getAppId(app.uid);
20126
20127        Preconditions.checkNotNull(app.seinfo);
20128
20129        try {
20130            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20131                    appId, app.seinfo, app.targetSdkVersion);
20132        } catch (InstallerException e) {
20133            if (app.isSystemApp()) {
20134                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20135                        + ", but trying to recover: " + e);
20136                destroyAppDataLeafLIF(pkg, userId, flags);
20137                try {
20138                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20139                            appId, app.seinfo, app.targetSdkVersion);
20140                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20141                } catch (InstallerException e2) {
20142                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20143                }
20144            } else {
20145                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20146            }
20147        }
20148
20149        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20150            try {
20151                // CE storage is unlocked right now, so read out the inode and
20152                // remember for use later when it's locked
20153                // TODO: mark this structure as dirty so we persist it!
20154                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20155                        StorageManager.FLAG_STORAGE_CE);
20156                synchronized (mPackages) {
20157                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20158                    if (ps != null) {
20159                        ps.setCeDataInode(ceDataInode, userId);
20160                    }
20161                }
20162            } catch (InstallerException e) {
20163                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20164            }
20165        }
20166
20167        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20168    }
20169
20170    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20171        if (pkg == null) {
20172            Slog.wtf(TAG, "Package was null!", new Throwable());
20173            return;
20174        }
20175        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20176        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20177        for (int i = 0; i < childCount; i++) {
20178            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20179        }
20180    }
20181
20182    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20183        final String volumeUuid = pkg.volumeUuid;
20184        final String packageName = pkg.packageName;
20185        final ApplicationInfo app = pkg.applicationInfo;
20186
20187        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20188            // Create a native library symlink only if we have native libraries
20189            // and if the native libraries are 32 bit libraries. We do not provide
20190            // this symlink for 64 bit libraries.
20191            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20192                final String nativeLibPath = app.nativeLibraryDir;
20193                try {
20194                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20195                            nativeLibPath, userId);
20196                } catch (InstallerException e) {
20197                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20198                }
20199            }
20200        }
20201    }
20202
20203    /**
20204     * For system apps on non-FBE devices, this method migrates any existing
20205     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20206     * requested by the app.
20207     */
20208    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20209        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20210                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20211            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20212                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20213            try {
20214                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20215                        storageTarget);
20216            } catch (InstallerException e) {
20217                logCriticalInfo(Log.WARN,
20218                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20219            }
20220            return true;
20221        } else {
20222            return false;
20223        }
20224    }
20225
20226    public PackageFreezer freezePackage(String packageName, String killReason) {
20227        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20228    }
20229
20230    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20231        return new PackageFreezer(packageName, userId, killReason);
20232    }
20233
20234    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20235            String killReason) {
20236        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20237    }
20238
20239    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20240            String killReason) {
20241        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20242            return new PackageFreezer();
20243        } else {
20244            return freezePackage(packageName, userId, killReason);
20245        }
20246    }
20247
20248    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20249            String killReason) {
20250        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20251    }
20252
20253    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20254            String killReason) {
20255        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20256            return new PackageFreezer();
20257        } else {
20258            return freezePackage(packageName, userId, killReason);
20259        }
20260    }
20261
20262    /**
20263     * Class that freezes and kills the given package upon creation, and
20264     * unfreezes it upon closing. This is typically used when doing surgery on
20265     * app code/data to prevent the app from running while you're working.
20266     */
20267    private class PackageFreezer implements AutoCloseable {
20268        private final String mPackageName;
20269        private final PackageFreezer[] mChildren;
20270
20271        private final boolean mWeFroze;
20272
20273        private final AtomicBoolean mClosed = new AtomicBoolean();
20274        private final CloseGuard mCloseGuard = CloseGuard.get();
20275
20276        /**
20277         * Create and return a stub freezer that doesn't actually do anything,
20278         * typically used when someone requested
20279         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20280         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20281         */
20282        public PackageFreezer() {
20283            mPackageName = null;
20284            mChildren = null;
20285            mWeFroze = false;
20286            mCloseGuard.open("close");
20287        }
20288
20289        public PackageFreezer(String packageName, int userId, String killReason) {
20290            synchronized (mPackages) {
20291                mPackageName = packageName;
20292                mWeFroze = mFrozenPackages.add(mPackageName);
20293
20294                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20295                if (ps != null) {
20296                    killApplication(ps.name, ps.appId, userId, killReason);
20297                }
20298
20299                final PackageParser.Package p = mPackages.get(packageName);
20300                if (p != null && p.childPackages != null) {
20301                    final int N = p.childPackages.size();
20302                    mChildren = new PackageFreezer[N];
20303                    for (int i = 0; i < N; i++) {
20304                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20305                                userId, killReason);
20306                    }
20307                } else {
20308                    mChildren = null;
20309                }
20310            }
20311            mCloseGuard.open("close");
20312        }
20313
20314        @Override
20315        protected void finalize() throws Throwable {
20316            try {
20317                mCloseGuard.warnIfOpen();
20318                close();
20319            } finally {
20320                super.finalize();
20321            }
20322        }
20323
20324        @Override
20325        public void close() {
20326            mCloseGuard.close();
20327            if (mClosed.compareAndSet(false, true)) {
20328                synchronized (mPackages) {
20329                    if (mWeFroze) {
20330                        mFrozenPackages.remove(mPackageName);
20331                    }
20332
20333                    if (mChildren != null) {
20334                        for (PackageFreezer freezer : mChildren) {
20335                            freezer.close();
20336                        }
20337                    }
20338                }
20339            }
20340        }
20341    }
20342
20343    /**
20344     * Verify that given package is currently frozen.
20345     */
20346    private void checkPackageFrozen(String packageName) {
20347        synchronized (mPackages) {
20348            if (!mFrozenPackages.contains(packageName)) {
20349                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20350            }
20351        }
20352    }
20353
20354    @Override
20355    public int movePackage(final String packageName, final String volumeUuid) {
20356        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20357
20358        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20359        final int moveId = mNextMoveId.getAndIncrement();
20360        mHandler.post(new Runnable() {
20361            @Override
20362            public void run() {
20363                try {
20364                    movePackageInternal(packageName, volumeUuid, moveId, user);
20365                } catch (PackageManagerException e) {
20366                    Slog.w(TAG, "Failed to move " + packageName, e);
20367                    mMoveCallbacks.notifyStatusChanged(moveId,
20368                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20369                }
20370            }
20371        });
20372        return moveId;
20373    }
20374
20375    private void movePackageInternal(final String packageName, final String volumeUuid,
20376            final int moveId, UserHandle user) throws PackageManagerException {
20377        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20378        final PackageManager pm = mContext.getPackageManager();
20379
20380        final boolean currentAsec;
20381        final String currentVolumeUuid;
20382        final File codeFile;
20383        final String installerPackageName;
20384        final String packageAbiOverride;
20385        final int appId;
20386        final String seinfo;
20387        final String label;
20388        final int targetSdkVersion;
20389        final PackageFreezer freezer;
20390        final int[] installedUserIds;
20391
20392        // reader
20393        synchronized (mPackages) {
20394            final PackageParser.Package pkg = mPackages.get(packageName);
20395            final PackageSetting ps = mSettings.mPackages.get(packageName);
20396            if (pkg == null || ps == null) {
20397                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20398            }
20399
20400            if (pkg.applicationInfo.isSystemApp()) {
20401                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20402                        "Cannot move system application");
20403            }
20404
20405            if (pkg.applicationInfo.isExternalAsec()) {
20406                currentAsec = true;
20407                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20408            } else if (pkg.applicationInfo.isForwardLocked()) {
20409                currentAsec = true;
20410                currentVolumeUuid = "forward_locked";
20411            } else {
20412                currentAsec = false;
20413                currentVolumeUuid = ps.volumeUuid;
20414
20415                final File probe = new File(pkg.codePath);
20416                final File probeOat = new File(probe, "oat");
20417                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20418                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20419                            "Move only supported for modern cluster style installs");
20420                }
20421            }
20422
20423            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20424                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20425                        "Package already moved to " + volumeUuid);
20426            }
20427            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20428                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20429                        "Device admin cannot be moved");
20430            }
20431
20432            if (mFrozenPackages.contains(packageName)) {
20433                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20434                        "Failed to move already frozen package");
20435            }
20436
20437            codeFile = new File(pkg.codePath);
20438            installerPackageName = ps.installerPackageName;
20439            packageAbiOverride = ps.cpuAbiOverrideString;
20440            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20441            seinfo = pkg.applicationInfo.seinfo;
20442            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20443            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20444            freezer = freezePackage(packageName, "movePackageInternal");
20445            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20446        }
20447
20448        final Bundle extras = new Bundle();
20449        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20450        extras.putString(Intent.EXTRA_TITLE, label);
20451        mMoveCallbacks.notifyCreated(moveId, extras);
20452
20453        int installFlags;
20454        final boolean moveCompleteApp;
20455        final File measurePath;
20456
20457        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20458            installFlags = INSTALL_INTERNAL;
20459            moveCompleteApp = !currentAsec;
20460            measurePath = Environment.getDataAppDirectory(volumeUuid);
20461        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20462            installFlags = INSTALL_EXTERNAL;
20463            moveCompleteApp = false;
20464            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20465        } else {
20466            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20467            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20468                    || !volume.isMountedWritable()) {
20469                freezer.close();
20470                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20471                        "Move location not mounted private volume");
20472            }
20473
20474            Preconditions.checkState(!currentAsec);
20475
20476            installFlags = INSTALL_INTERNAL;
20477            moveCompleteApp = true;
20478            measurePath = Environment.getDataAppDirectory(volumeUuid);
20479        }
20480
20481        final PackageStats stats = new PackageStats(null, -1);
20482        synchronized (mInstaller) {
20483            for (int userId : installedUserIds) {
20484                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20485                    freezer.close();
20486                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20487                            "Failed to measure package size");
20488                }
20489            }
20490        }
20491
20492        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20493                + stats.dataSize);
20494
20495        final long startFreeBytes = measurePath.getFreeSpace();
20496        final long sizeBytes;
20497        if (moveCompleteApp) {
20498            sizeBytes = stats.codeSize + stats.dataSize;
20499        } else {
20500            sizeBytes = stats.codeSize;
20501        }
20502
20503        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20504            freezer.close();
20505            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20506                    "Not enough free space to move");
20507        }
20508
20509        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20510
20511        final CountDownLatch installedLatch = new CountDownLatch(1);
20512        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20513            @Override
20514            public void onUserActionRequired(Intent intent) throws RemoteException {
20515                throw new IllegalStateException();
20516            }
20517
20518            @Override
20519            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20520                    Bundle extras) throws RemoteException {
20521                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20522                        + PackageManager.installStatusToString(returnCode, msg));
20523
20524                installedLatch.countDown();
20525                freezer.close();
20526
20527                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20528                switch (status) {
20529                    case PackageInstaller.STATUS_SUCCESS:
20530                        mMoveCallbacks.notifyStatusChanged(moveId,
20531                                PackageManager.MOVE_SUCCEEDED);
20532                        break;
20533                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20534                        mMoveCallbacks.notifyStatusChanged(moveId,
20535                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20536                        break;
20537                    default:
20538                        mMoveCallbacks.notifyStatusChanged(moveId,
20539                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20540                        break;
20541                }
20542            }
20543        };
20544
20545        final MoveInfo move;
20546        if (moveCompleteApp) {
20547            // Kick off a thread to report progress estimates
20548            new Thread() {
20549                @Override
20550                public void run() {
20551                    while (true) {
20552                        try {
20553                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20554                                break;
20555                            }
20556                        } catch (InterruptedException ignored) {
20557                        }
20558
20559                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20560                        final int progress = 10 + (int) MathUtils.constrain(
20561                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20562                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20563                    }
20564                }
20565            }.start();
20566
20567            final String dataAppName = codeFile.getName();
20568            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20569                    dataAppName, appId, seinfo, targetSdkVersion);
20570        } else {
20571            move = null;
20572        }
20573
20574        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20575
20576        final Message msg = mHandler.obtainMessage(INIT_COPY);
20577        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20578        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20579                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20580                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20581        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20582        msg.obj = params;
20583
20584        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20585                System.identityHashCode(msg.obj));
20586        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20587                System.identityHashCode(msg.obj));
20588
20589        mHandler.sendMessage(msg);
20590    }
20591
20592    @Override
20593    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20594        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20595
20596        final int realMoveId = mNextMoveId.getAndIncrement();
20597        final Bundle extras = new Bundle();
20598        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20599        mMoveCallbacks.notifyCreated(realMoveId, extras);
20600
20601        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20602            @Override
20603            public void onCreated(int moveId, Bundle extras) {
20604                // Ignored
20605            }
20606
20607            @Override
20608            public void onStatusChanged(int moveId, int status, long estMillis) {
20609                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20610            }
20611        };
20612
20613        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20614        storage.setPrimaryStorageUuid(volumeUuid, callback);
20615        return realMoveId;
20616    }
20617
20618    @Override
20619    public int getMoveStatus(int moveId) {
20620        mContext.enforceCallingOrSelfPermission(
20621                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20622        return mMoveCallbacks.mLastStatus.get(moveId);
20623    }
20624
20625    @Override
20626    public void registerMoveCallback(IPackageMoveObserver callback) {
20627        mContext.enforceCallingOrSelfPermission(
20628                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20629        mMoveCallbacks.register(callback);
20630    }
20631
20632    @Override
20633    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20634        mContext.enforceCallingOrSelfPermission(
20635                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20636        mMoveCallbacks.unregister(callback);
20637    }
20638
20639    @Override
20640    public boolean setInstallLocation(int loc) {
20641        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20642                null);
20643        if (getInstallLocation() == loc) {
20644            return true;
20645        }
20646        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20647                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20648            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20649                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20650            return true;
20651        }
20652        return false;
20653   }
20654
20655    @Override
20656    public int getInstallLocation() {
20657        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20658                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20659                PackageHelper.APP_INSTALL_AUTO);
20660    }
20661
20662    /** Called by UserManagerService */
20663    void cleanUpUser(UserManagerService userManager, int userHandle) {
20664        synchronized (mPackages) {
20665            mDirtyUsers.remove(userHandle);
20666            mUserNeedsBadging.delete(userHandle);
20667            mSettings.removeUserLPw(userHandle);
20668            mPendingBroadcasts.remove(userHandle);
20669            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20670            removeUnusedPackagesLPw(userManager, userHandle);
20671        }
20672    }
20673
20674    /**
20675     * We're removing userHandle and would like to remove any downloaded packages
20676     * that are no longer in use by any other user.
20677     * @param userHandle the user being removed
20678     */
20679    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20680        final boolean DEBUG_CLEAN_APKS = false;
20681        int [] users = userManager.getUserIds();
20682        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20683        while (psit.hasNext()) {
20684            PackageSetting ps = psit.next();
20685            if (ps.pkg == null) {
20686                continue;
20687            }
20688            final String packageName = ps.pkg.packageName;
20689            // Skip over if system app
20690            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20691                continue;
20692            }
20693            if (DEBUG_CLEAN_APKS) {
20694                Slog.i(TAG, "Checking package " + packageName);
20695            }
20696            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20697            if (keep) {
20698                if (DEBUG_CLEAN_APKS) {
20699                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20700                }
20701            } else {
20702                for (int i = 0; i < users.length; i++) {
20703                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20704                        keep = true;
20705                        if (DEBUG_CLEAN_APKS) {
20706                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20707                                    + users[i]);
20708                        }
20709                        break;
20710                    }
20711                }
20712            }
20713            if (!keep) {
20714                if (DEBUG_CLEAN_APKS) {
20715                    Slog.i(TAG, "  Removing package " + packageName);
20716                }
20717                mHandler.post(new Runnable() {
20718                    public void run() {
20719                        deletePackageX(packageName, userHandle, 0);
20720                    } //end run
20721                });
20722            }
20723        }
20724    }
20725
20726    /** Called by UserManagerService */
20727    void createNewUser(int userId, String[] disallowedPackages) {
20728        synchronized (mInstallLock) {
20729            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
20730        }
20731        synchronized (mPackages) {
20732            scheduleWritePackageRestrictionsLocked(userId);
20733            scheduleWritePackageListLocked(userId);
20734            applyFactoryDefaultBrowserLPw(userId);
20735            primeDomainVerificationsLPw(userId);
20736        }
20737    }
20738
20739    void onNewUserCreated(final int userId) {
20740        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20741        // If permission review for legacy apps is required, we represent
20742        // dagerous permissions for such apps as always granted runtime
20743        // permissions to keep per user flag state whether review is needed.
20744        // Hence, if a new user is added we have to propagate dangerous
20745        // permission grants for these legacy apps.
20746        if (mPermissionReviewRequired) {
20747            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20748                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20749        }
20750    }
20751
20752    @Override
20753    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20754        mContext.enforceCallingOrSelfPermission(
20755                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20756                "Only package verification agents can read the verifier device identity");
20757
20758        synchronized (mPackages) {
20759            return mSettings.getVerifierDeviceIdentityLPw();
20760        }
20761    }
20762
20763    @Override
20764    public void setPermissionEnforced(String permission, boolean enforced) {
20765        // TODO: Now that we no longer change GID for storage, this should to away.
20766        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20767                "setPermissionEnforced");
20768        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20769            synchronized (mPackages) {
20770                if (mSettings.mReadExternalStorageEnforced == null
20771                        || mSettings.mReadExternalStorageEnforced != enforced) {
20772                    mSettings.mReadExternalStorageEnforced = enforced;
20773                    mSettings.writeLPr();
20774                }
20775            }
20776            // kill any non-foreground processes so we restart them and
20777            // grant/revoke the GID.
20778            final IActivityManager am = ActivityManager.getService();
20779            if (am != null) {
20780                final long token = Binder.clearCallingIdentity();
20781                try {
20782                    am.killProcessesBelowForeground("setPermissionEnforcement");
20783                } catch (RemoteException e) {
20784                } finally {
20785                    Binder.restoreCallingIdentity(token);
20786                }
20787            }
20788        } else {
20789            throw new IllegalArgumentException("No selective enforcement for " + permission);
20790        }
20791    }
20792
20793    @Override
20794    @Deprecated
20795    public boolean isPermissionEnforced(String permission) {
20796        return true;
20797    }
20798
20799    @Override
20800    public boolean isStorageLow() {
20801        final long token = Binder.clearCallingIdentity();
20802        try {
20803            final DeviceStorageMonitorInternal
20804                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20805            if (dsm != null) {
20806                return dsm.isMemoryLow();
20807            } else {
20808                return false;
20809            }
20810        } finally {
20811            Binder.restoreCallingIdentity(token);
20812        }
20813    }
20814
20815    @Override
20816    public IPackageInstaller getPackageInstaller() {
20817        return mInstallerService;
20818    }
20819
20820    private boolean userNeedsBadging(int userId) {
20821        int index = mUserNeedsBadging.indexOfKey(userId);
20822        if (index < 0) {
20823            final UserInfo userInfo;
20824            final long token = Binder.clearCallingIdentity();
20825            try {
20826                userInfo = sUserManager.getUserInfo(userId);
20827            } finally {
20828                Binder.restoreCallingIdentity(token);
20829            }
20830            final boolean b;
20831            if (userInfo != null && userInfo.isManagedProfile()) {
20832                b = true;
20833            } else {
20834                b = false;
20835            }
20836            mUserNeedsBadging.put(userId, b);
20837            return b;
20838        }
20839        return mUserNeedsBadging.valueAt(index);
20840    }
20841
20842    @Override
20843    public KeySet getKeySetByAlias(String packageName, String alias) {
20844        if (packageName == null || alias == null) {
20845            return null;
20846        }
20847        synchronized(mPackages) {
20848            final PackageParser.Package pkg = mPackages.get(packageName);
20849            if (pkg == null) {
20850                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20851                throw new IllegalArgumentException("Unknown package: " + packageName);
20852            }
20853            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20854            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20855        }
20856    }
20857
20858    @Override
20859    public KeySet getSigningKeySet(String packageName) {
20860        if (packageName == null) {
20861            return null;
20862        }
20863        synchronized(mPackages) {
20864            final PackageParser.Package pkg = mPackages.get(packageName);
20865            if (pkg == null) {
20866                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20867                throw new IllegalArgumentException("Unknown package: " + packageName);
20868            }
20869            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20870                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20871                throw new SecurityException("May not access signing KeySet of other apps.");
20872            }
20873            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20874            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20875        }
20876    }
20877
20878    @Override
20879    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20880        if (packageName == null || ks == null) {
20881            return false;
20882        }
20883        synchronized(mPackages) {
20884            final PackageParser.Package pkg = mPackages.get(packageName);
20885            if (pkg == null) {
20886                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20887                throw new IllegalArgumentException("Unknown package: " + packageName);
20888            }
20889            IBinder ksh = ks.getToken();
20890            if (ksh instanceof KeySetHandle) {
20891                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20892                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20893            }
20894            return false;
20895        }
20896    }
20897
20898    @Override
20899    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20900        if (packageName == null || ks == null) {
20901            return false;
20902        }
20903        synchronized(mPackages) {
20904            final PackageParser.Package pkg = mPackages.get(packageName);
20905            if (pkg == null) {
20906                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20907                throw new IllegalArgumentException("Unknown package: " + packageName);
20908            }
20909            IBinder ksh = ks.getToken();
20910            if (ksh instanceof KeySetHandle) {
20911                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20912                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20913            }
20914            return false;
20915        }
20916    }
20917
20918    private void deletePackageIfUnusedLPr(final String packageName) {
20919        PackageSetting ps = mSettings.mPackages.get(packageName);
20920        if (ps == null) {
20921            return;
20922        }
20923        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20924            // TODO Implement atomic delete if package is unused
20925            // It is currently possible that the package will be deleted even if it is installed
20926            // after this method returns.
20927            mHandler.post(new Runnable() {
20928                public void run() {
20929                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20930                }
20931            });
20932        }
20933    }
20934
20935    /**
20936     * Check and throw if the given before/after packages would be considered a
20937     * downgrade.
20938     */
20939    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20940            throws PackageManagerException {
20941        if (after.versionCode < before.mVersionCode) {
20942            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20943                    "Update version code " + after.versionCode + " is older than current "
20944                    + before.mVersionCode);
20945        } else if (after.versionCode == before.mVersionCode) {
20946            if (after.baseRevisionCode < before.baseRevisionCode) {
20947                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20948                        "Update base revision code " + after.baseRevisionCode
20949                        + " is older than current " + before.baseRevisionCode);
20950            }
20951
20952            if (!ArrayUtils.isEmpty(after.splitNames)) {
20953                for (int i = 0; i < after.splitNames.length; i++) {
20954                    final String splitName = after.splitNames[i];
20955                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20956                    if (j != -1) {
20957                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20958                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20959                                    "Update split " + splitName + " revision code "
20960                                    + after.splitRevisionCodes[i] + " is older than current "
20961                                    + before.splitRevisionCodes[j]);
20962                        }
20963                    }
20964                }
20965            }
20966        }
20967    }
20968
20969    private static class MoveCallbacks extends Handler {
20970        private static final int MSG_CREATED = 1;
20971        private static final int MSG_STATUS_CHANGED = 2;
20972
20973        private final RemoteCallbackList<IPackageMoveObserver>
20974                mCallbacks = new RemoteCallbackList<>();
20975
20976        private final SparseIntArray mLastStatus = new SparseIntArray();
20977
20978        public MoveCallbacks(Looper looper) {
20979            super(looper);
20980        }
20981
20982        public void register(IPackageMoveObserver callback) {
20983            mCallbacks.register(callback);
20984        }
20985
20986        public void unregister(IPackageMoveObserver callback) {
20987            mCallbacks.unregister(callback);
20988        }
20989
20990        @Override
20991        public void handleMessage(Message msg) {
20992            final SomeArgs args = (SomeArgs) msg.obj;
20993            final int n = mCallbacks.beginBroadcast();
20994            for (int i = 0; i < n; i++) {
20995                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20996                try {
20997                    invokeCallback(callback, msg.what, args);
20998                } catch (RemoteException ignored) {
20999                }
21000            }
21001            mCallbacks.finishBroadcast();
21002            args.recycle();
21003        }
21004
21005        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21006                throws RemoteException {
21007            switch (what) {
21008                case MSG_CREATED: {
21009                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21010                    break;
21011                }
21012                case MSG_STATUS_CHANGED: {
21013                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21014                    break;
21015                }
21016            }
21017        }
21018
21019        private void notifyCreated(int moveId, Bundle extras) {
21020            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21021
21022            final SomeArgs args = SomeArgs.obtain();
21023            args.argi1 = moveId;
21024            args.arg2 = extras;
21025            obtainMessage(MSG_CREATED, args).sendToTarget();
21026        }
21027
21028        private void notifyStatusChanged(int moveId, int status) {
21029            notifyStatusChanged(moveId, status, -1);
21030        }
21031
21032        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21033            Slog.v(TAG, "Move " + moveId + " status " + status);
21034
21035            final SomeArgs args = SomeArgs.obtain();
21036            args.argi1 = moveId;
21037            args.argi2 = status;
21038            args.arg3 = estMillis;
21039            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21040
21041            synchronized (mLastStatus) {
21042                mLastStatus.put(moveId, status);
21043            }
21044        }
21045    }
21046
21047    private final static class OnPermissionChangeListeners extends Handler {
21048        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21049
21050        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21051                new RemoteCallbackList<>();
21052
21053        public OnPermissionChangeListeners(Looper looper) {
21054            super(looper);
21055        }
21056
21057        @Override
21058        public void handleMessage(Message msg) {
21059            switch (msg.what) {
21060                case MSG_ON_PERMISSIONS_CHANGED: {
21061                    final int uid = msg.arg1;
21062                    handleOnPermissionsChanged(uid);
21063                } break;
21064            }
21065        }
21066
21067        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21068            mPermissionListeners.register(listener);
21069
21070        }
21071
21072        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21073            mPermissionListeners.unregister(listener);
21074        }
21075
21076        public void onPermissionsChanged(int uid) {
21077            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21078                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21079            }
21080        }
21081
21082        private void handleOnPermissionsChanged(int uid) {
21083            final int count = mPermissionListeners.beginBroadcast();
21084            try {
21085                for (int i = 0; i < count; i++) {
21086                    IOnPermissionsChangeListener callback = mPermissionListeners
21087                            .getBroadcastItem(i);
21088                    try {
21089                        callback.onPermissionsChanged(uid);
21090                    } catch (RemoteException e) {
21091                        Log.e(TAG, "Permission listener is dead", e);
21092                    }
21093                }
21094            } finally {
21095                mPermissionListeners.finishBroadcast();
21096            }
21097        }
21098    }
21099
21100    private class PackageManagerInternalImpl extends PackageManagerInternal {
21101        @Override
21102        public void setLocationPackagesProvider(PackagesProvider provider) {
21103            synchronized (mPackages) {
21104                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21105            }
21106        }
21107
21108        @Override
21109        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21110            synchronized (mPackages) {
21111                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21112            }
21113        }
21114
21115        @Override
21116        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21117            synchronized (mPackages) {
21118                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21119            }
21120        }
21121
21122        @Override
21123        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21124            synchronized (mPackages) {
21125                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21126            }
21127        }
21128
21129        @Override
21130        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21131            synchronized (mPackages) {
21132                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21133            }
21134        }
21135
21136        @Override
21137        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21138            synchronized (mPackages) {
21139                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21140            }
21141        }
21142
21143        @Override
21144        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21145            synchronized (mPackages) {
21146                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21147                        packageName, userId);
21148            }
21149        }
21150
21151        @Override
21152        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21153            synchronized (mPackages) {
21154                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21155                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21156                        packageName, userId);
21157            }
21158        }
21159
21160        @Override
21161        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21162            synchronized (mPackages) {
21163                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21164                        packageName, userId);
21165            }
21166        }
21167
21168        @Override
21169        public void setKeepUninstalledPackages(final List<String> packageList) {
21170            Preconditions.checkNotNull(packageList);
21171            List<String> removedFromList = null;
21172            synchronized (mPackages) {
21173                if (mKeepUninstalledPackages != null) {
21174                    final int packagesCount = mKeepUninstalledPackages.size();
21175                    for (int i = 0; i < packagesCount; i++) {
21176                        String oldPackage = mKeepUninstalledPackages.get(i);
21177                        if (packageList != null && packageList.contains(oldPackage)) {
21178                            continue;
21179                        }
21180                        if (removedFromList == null) {
21181                            removedFromList = new ArrayList<>();
21182                        }
21183                        removedFromList.add(oldPackage);
21184                    }
21185                }
21186                mKeepUninstalledPackages = new ArrayList<>(packageList);
21187                if (removedFromList != null) {
21188                    final int removedCount = removedFromList.size();
21189                    for (int i = 0; i < removedCount; i++) {
21190                        deletePackageIfUnusedLPr(removedFromList.get(i));
21191                    }
21192                }
21193            }
21194        }
21195
21196        @Override
21197        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21198            synchronized (mPackages) {
21199                // If we do not support permission review, done.
21200                if (!mPermissionReviewRequired) {
21201                    return false;
21202                }
21203
21204                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21205                if (packageSetting == null) {
21206                    return false;
21207                }
21208
21209                // Permission review applies only to apps not supporting the new permission model.
21210                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21211                    return false;
21212                }
21213
21214                // Legacy apps have the permission and get user consent on launch.
21215                PermissionsState permissionsState = packageSetting.getPermissionsState();
21216                return permissionsState.isPermissionReviewRequired(userId);
21217            }
21218        }
21219
21220        @Override
21221        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21222            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21223        }
21224
21225        @Override
21226        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21227                int userId) {
21228            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21229        }
21230
21231        @Override
21232        public void setDeviceAndProfileOwnerPackages(
21233                int deviceOwnerUserId, String deviceOwnerPackage,
21234                SparseArray<String> profileOwnerPackages) {
21235            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21236                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21237        }
21238
21239        @Override
21240        public boolean isPackageDataProtected(int userId, String packageName) {
21241            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21242        }
21243
21244        @Override
21245        public boolean isPackageEphemeral(int userId, String packageName) {
21246            synchronized (mPackages) {
21247                PackageParser.Package p = mPackages.get(packageName);
21248                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21249            }
21250        }
21251
21252        @Override
21253        public boolean wasPackageEverLaunched(String packageName, int userId) {
21254            synchronized (mPackages) {
21255                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21256            }
21257        }
21258
21259        @Override
21260        public void grantRuntimePermission(String packageName, String name, int userId,
21261                boolean overridePolicy) {
21262            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21263                    overridePolicy);
21264        }
21265
21266        @Override
21267        public void revokeRuntimePermission(String packageName, String name, int userId,
21268                boolean overridePolicy) {
21269            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21270                    overridePolicy);
21271        }
21272
21273        @Override
21274        public String getNameForUid(int uid) {
21275            return PackageManagerService.this.getNameForUid(uid);
21276        }
21277
21278        @Override
21279        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21280                Intent origIntent, String resolvedType, Intent launchIntent,
21281                String callingPackage, int userId) {
21282            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21283                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21284        }
21285    }
21286
21287    @Override
21288    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21289        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21290        synchronized (mPackages) {
21291            final long identity = Binder.clearCallingIdentity();
21292            try {
21293                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21294                        packageNames, userId);
21295            } finally {
21296                Binder.restoreCallingIdentity(identity);
21297            }
21298        }
21299    }
21300
21301    private static void enforceSystemOrPhoneCaller(String tag) {
21302        int callingUid = Binder.getCallingUid();
21303        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21304            throw new SecurityException(
21305                    "Cannot call " + tag + " from UID " + callingUid);
21306        }
21307    }
21308
21309    boolean isHistoricalPackageUsageAvailable() {
21310        return mPackageUsage.isHistoricalPackageUsageAvailable();
21311    }
21312
21313    /**
21314     * Return a <b>copy</b> of the collection of packages known to the package manager.
21315     * @return A copy of the values of mPackages.
21316     */
21317    Collection<PackageParser.Package> getPackages() {
21318        synchronized (mPackages) {
21319            return new ArrayList<>(mPackages.values());
21320        }
21321    }
21322
21323    /**
21324     * Logs process start information (including base APK hash) to the security log.
21325     * @hide
21326     */
21327    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21328            String apkFile, int pid) {
21329        if (!SecurityLog.isLoggingEnabled()) {
21330            return;
21331        }
21332        Bundle data = new Bundle();
21333        data.putLong("startTimestamp", System.currentTimeMillis());
21334        data.putString("processName", processName);
21335        data.putInt("uid", uid);
21336        data.putString("seinfo", seinfo);
21337        data.putString("apkFile", apkFile);
21338        data.putInt("pid", pid);
21339        Message msg = mProcessLoggingHandler.obtainMessage(
21340                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21341        msg.setData(data);
21342        mProcessLoggingHandler.sendMessage(msg);
21343    }
21344
21345    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21346        return mCompilerStats.getPackageStats(pkgName);
21347    }
21348
21349    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21350        return getOrCreateCompilerPackageStats(pkg.packageName);
21351    }
21352
21353    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21354        return mCompilerStats.getOrCreatePackageStats(pkgName);
21355    }
21356
21357    public void deleteCompilerPackageStats(String pkgName) {
21358        mCompilerStats.deletePackageStats(pkgName);
21359    }
21360}
21361