PackageManagerService.java revision 1c39a112b43e50da4e801d634e28ae7a130c0dcb
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_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.security.KeyStore;
200import android.security.SystemKeyStore;
201import android.system.ErrnoException;
202import android.system.Os;
203import android.text.TextUtils;
204import android.text.format.DateUtils;
205import android.util.ArrayMap;
206import android.util.ArraySet;
207import android.util.AtomicFile;
208import android.util.DisplayMetrics;
209import android.util.EventLog;
210import android.util.ExceptionUtils;
211import android.util.Log;
212import android.util.LogPrinter;
213import android.util.MathUtils;
214import android.util.PrintStreamPrinter;
215import android.util.Slog;
216import android.util.SparseArray;
217import android.util.SparseBooleanArray;
218import android.util.SparseIntArray;
219import android.util.Xml;
220import android.util.jar.StrictJarFile;
221import android.view.Display;
222
223import com.android.internal.R;
224import com.android.internal.annotations.GuardedBy;
225import com.android.internal.app.IMediaContainerService;
226import com.android.internal.app.ResolverActivity;
227import com.android.internal.content.NativeLibraryHelper;
228import com.android.internal.content.PackageHelper;
229import com.android.internal.logging.MetricsLogger;
230import com.android.internal.os.IParcelFileDescriptorFactory;
231import com.android.internal.os.InstallerConnection.InstallerException;
232import com.android.internal.os.SomeArgs;
233import com.android.internal.os.Zygote;
234import com.android.internal.telephony.CarrierAppUtils;
235import com.android.internal.util.ArrayUtils;
236import com.android.internal.util.FastPrintWriter;
237import com.android.internal.util.FastXmlSerializer;
238import com.android.internal.util.IndentingPrintWriter;
239import com.android.internal.util.Preconditions;
240import com.android.internal.util.XmlUtils;
241import com.android.server.EventLogTags;
242import com.android.server.FgThread;
243import com.android.server.IntentResolver;
244import com.android.server.LocalServices;
245import com.android.server.ServiceThread;
246import com.android.server.SystemConfig;
247import com.android.server.Watchdog;
248import com.android.server.net.NetworkPolicyManagerInternal;
249import com.android.server.pm.PermissionsState.PermissionState;
250import com.android.server.pm.Settings.DatabaseVersion;
251import com.android.server.pm.Settings.VersionInfo;
252import com.android.server.storage.DeviceStorageMonitorInternal;
253
254import dalvik.system.CloseGuard;
255import dalvik.system.DexFile;
256import dalvik.system.VMRuntime;
257
258import libcore.io.IoUtils;
259import libcore.util.EmptyArray;
260
261import org.xmlpull.v1.XmlPullParser;
262import org.xmlpull.v1.XmlPullParserException;
263import org.xmlpull.v1.XmlSerializer;
264
265import java.io.BufferedInputStream;
266import java.io.BufferedOutputStream;
267import java.io.BufferedReader;
268import java.io.ByteArrayInputStream;
269import java.io.ByteArrayOutputStream;
270import java.io.File;
271import java.io.FileDescriptor;
272import java.io.FileInputStream;
273import java.io.FileNotFoundException;
274import java.io.FileOutputStream;
275import java.io.FileReader;
276import java.io.FilenameFilter;
277import java.io.IOException;
278import java.io.InputStream;
279import java.io.PrintWriter;
280import java.nio.charset.StandardCharsets;
281import java.security.DigestInputStream;
282import java.security.MessageDigest;
283import java.security.NoSuchAlgorithmException;
284import java.security.PublicKey;
285import java.security.cert.Certificate;
286import java.security.cert.CertificateEncodingException;
287import java.security.cert.CertificateException;
288import java.text.SimpleDateFormat;
289import java.util.ArrayList;
290import java.util.Arrays;
291import java.util.Collection;
292import java.util.Collections;
293import java.util.Comparator;
294import java.util.Date;
295import java.util.HashSet;
296import java.util.Iterator;
297import java.util.List;
298import java.util.Map;
299import java.util.Objects;
300import java.util.Set;
301import java.util.concurrent.CountDownLatch;
302import java.util.concurrent.TimeUnit;
303import java.util.concurrent.atomic.AtomicBoolean;
304import java.util.concurrent.atomic.AtomicInteger;
305import java.util.concurrent.atomic.AtomicLong;
306
307/**
308 * Keep track of all those APKs everywhere.
309 * <p>
310 * Internally there are two important locks:
311 * <ul>
312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
313 * and other related state. It is a fine-grained lock that should only be held
314 * momentarily, as it's one of the most contended locks in the system.
315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
316 * operations typically involve heavy lifting of application data on disk. Since
317 * {@code installd} is single-threaded, and it's operations can often be slow,
318 * this lock should never be acquired while already holding {@link #mPackages}.
319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
320 * holding {@link #mInstallLock}.
321 * </ul>
322 * Many internal methods rely on the caller to hold the appropriate locks, and
323 * this contract is expressed through method name suffixes:
324 * <ul>
325 * <li>fooLI(): the caller must hold {@link #mInstallLock}
326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
327 * being modified must be frozen
328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
330 * </ul>
331 * <p>
332 * Because this class is very central to the platform's security; please run all
333 * CTS and unit tests whenever making modifications:
334 *
335 * <pre>
336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
338 * </pre>
339 */
340public class PackageManagerService extends IPackageManager.Stub {
341    static final String TAG = "PackageManager";
342    static final boolean DEBUG_SETTINGS = false;
343    static final boolean DEBUG_PREFERRED = false;
344    static final boolean DEBUG_UPGRADE = false;
345    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
346    private static final boolean DEBUG_BACKUP = false;
347    private static final boolean DEBUG_INSTALL = false;
348    private static final boolean DEBUG_REMOVE = false;
349    private static final boolean DEBUG_BROADCASTS = false;
350    private static final boolean DEBUG_SHOW_INFO = false;
351    private static final boolean DEBUG_PACKAGE_INFO = false;
352    private static final boolean DEBUG_INTENT_MATCHING = false;
353    private static final boolean DEBUG_PACKAGE_SCANNING = false;
354    private static final boolean DEBUG_VERIFY = false;
355    private static final boolean DEBUG_FILTERS = false;
356
357    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
358    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
359    // user, but by default initialize to this.
360    static final boolean DEBUG_DEXOPT = false;
361
362    private static final boolean DEBUG_ABI_SELECTION = false;
363    private static final boolean DEBUG_EPHEMERAL = false;
364    private static final boolean DEBUG_TRIAGED_MISSING = false;
365    private static final boolean DEBUG_APP_DATA = false;
366
367    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
368
369    private static final boolean DISABLE_EPHEMERAL_APPS = true;
370
371    private static final int RADIO_UID = Process.PHONE_UID;
372    private static final int LOG_UID = Process.LOG_UID;
373    private static final int NFC_UID = Process.NFC_UID;
374    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
375    private static final int SHELL_UID = Process.SHELL_UID;
376
377    // Cap the size of permission trees that 3rd party apps can define
378    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
379
380    // Suffix used during package installation when copying/moving
381    // package apks to install directory.
382    private static final String INSTALL_PACKAGE_SUFFIX = "-";
383
384    static final int SCAN_NO_DEX = 1<<1;
385    static final int SCAN_FORCE_DEX = 1<<2;
386    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
387    static final int SCAN_NEW_INSTALL = 1<<4;
388    static final int SCAN_NO_PATHS = 1<<5;
389    static final int SCAN_UPDATE_TIME = 1<<6;
390    static final int SCAN_DEFER_DEX = 1<<7;
391    static final int SCAN_BOOTING = 1<<8;
392    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
393    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
394    static final int SCAN_REPLACING = 1<<11;
395    static final int SCAN_REQUIRE_KNOWN = 1<<12;
396    static final int SCAN_MOVE = 1<<13;
397    static final int SCAN_INITIAL = 1<<14;
398    static final int SCAN_CHECK_ONLY = 1<<15;
399    static final int SCAN_DONT_KILL_APP = 1<<17;
400    static final int SCAN_IGNORE_FROZEN = 1<<18;
401
402    static final int REMOVE_CHATTY = 1<<16;
403
404    private static final int[] EMPTY_INT_ARRAY = new int[0];
405
406    /**
407     * Timeout (in milliseconds) after which the watchdog should declare that
408     * our handler thread is wedged.  The usual default for such things is one
409     * minute but we sometimes do very lengthy I/O operations on this thread,
410     * such as installing multi-gigabyte applications, so ours needs to be longer.
411     */
412    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
413
414    /**
415     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
416     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
417     * settings entry if available, otherwise we use the hardcoded default.  If it's been
418     * more than this long since the last fstrim, we force one during the boot sequence.
419     *
420     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
421     * one gets run at the next available charging+idle time.  This final mandatory
422     * no-fstrim check kicks in only of the other scheduling criteria is never met.
423     */
424    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
425
426    /**
427     * Whether verification is enabled by default.
428     */
429    private static final boolean DEFAULT_VERIFY_ENABLE = true;
430
431    /**
432     * The default maximum time to wait for the verification agent to return in
433     * milliseconds.
434     */
435    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
436
437    /**
438     * The default response for package verification timeout.
439     *
440     * This can be either PackageManager.VERIFICATION_ALLOW or
441     * PackageManager.VERIFICATION_REJECT.
442     */
443    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
444
445    static final String PLATFORM_PACKAGE_NAME = "android";
446
447    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
448
449    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
450            DEFAULT_CONTAINER_PACKAGE,
451            "com.android.defcontainer.DefaultContainerService");
452
453    private static final String KILL_APP_REASON_GIDS_CHANGED =
454            "permission grant or revoke changed gids";
455
456    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
457            "permissions revoked";
458
459    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
460
461    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
462
463    /** Permission grant: not grant the permission. */
464    private static final int GRANT_DENIED = 1;
465
466    /** Permission grant: grant the permission as an install permission. */
467    private static final int GRANT_INSTALL = 2;
468
469    /** Permission grant: grant the permission as a runtime one. */
470    private static final int GRANT_RUNTIME = 3;
471
472    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
473    private static final int GRANT_UPGRADE = 4;
474
475    /** Canonical intent used to identify what counts as a "web browser" app */
476    private static final Intent sBrowserIntent;
477    static {
478        sBrowserIntent = new Intent();
479        sBrowserIntent.setAction(Intent.ACTION_VIEW);
480        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
481        sBrowserIntent.setData(Uri.parse("http:"));
482    }
483
484    /**
485     * The set of all protected actions [i.e. those actions for which a high priority
486     * intent filter is disallowed].
487     */
488    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
489    static {
490        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
491        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
493        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
494    }
495
496    // Compilation reasons.
497    public static final int REASON_FIRST_BOOT = 0;
498    public static final int REASON_BOOT = 1;
499    public static final int REASON_INSTALL = 2;
500    public static final int REASON_BACKGROUND_DEXOPT = 3;
501    public static final int REASON_AB_OTA = 4;
502    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
503    public static final int REASON_SHARED_APK = 6;
504    public static final int REASON_FORCED_DEXOPT = 7;
505
506    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
507
508    /** Special library name that skips shared libraries check during compilation. */
509    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
510
511    final ServiceThread mHandlerThread;
512
513    final PackageHandler mHandler;
514
515    private final ProcessLoggingHandler mProcessLoggingHandler;
516
517    /**
518     * Messages for {@link #mHandler} that need to wait for system ready before
519     * being dispatched.
520     */
521    private ArrayList<Message> mPostSystemReadyMessages;
522
523    final int mSdkVersion = Build.VERSION.SDK_INT;
524
525    final Context mContext;
526    final boolean mFactoryTest;
527    final boolean mOnlyCore;
528    final DisplayMetrics mMetrics;
529    final int mDefParseFlags;
530    final String[] mSeparateProcesses;
531    final boolean mIsUpgrade;
532    final boolean mIsPreNUpgrade;
533
534    /** The location for ASEC container files on internal storage. */
535    final String mAsecInternalPath;
536
537    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
538    // LOCK HELD.  Can be called with mInstallLock held.
539    @GuardedBy("mInstallLock")
540    final Installer mInstaller;
541
542    /** Directory where installed third-party apps stored */
543    final File mAppInstallDir;
544    final File mEphemeralInstallDir;
545
546    /**
547     * Directory to which applications installed internally have their
548     * 32 bit native libraries copied.
549     */
550    private File mAppLib32InstallDir;
551
552    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
553    // apps.
554    final File mDrmAppPrivateInstallDir;
555
556    // ----------------------------------------------------------------
557
558    // Lock for state used when installing and doing other long running
559    // operations.  Methods that must be called with this lock held have
560    // the suffix "LI".
561    final Object mInstallLock = new Object();
562
563    // ----------------------------------------------------------------
564
565    // Keys are String (package name), values are Package.  This also serves
566    // as the lock for the global state.  Methods that must be called with
567    // this lock held have the prefix "LP".
568    @GuardedBy("mPackages")
569    final ArrayMap<String, PackageParser.Package> mPackages =
570            new ArrayMap<String, PackageParser.Package>();
571
572    final ArrayMap<String, Set<String>> mKnownCodebase =
573            new ArrayMap<String, Set<String>>();
574
575    // Tracks available target package names -> overlay package paths.
576    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
577        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
578
579    /**
580     * Tracks new system packages [received in an OTA] that we expect to
581     * find updated user-installed versions. Keys are package name, values
582     * are package location.
583     */
584    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
585    /**
586     * Tracks high priority intent filters for protected actions. During boot, certain
587     * filter actions are protected and should never be allowed to have a high priority
588     * intent filter for them. However, there is one, and only one exception -- the
589     * setup wizard. It must be able to define a high priority intent filter for these
590     * actions to ensure there are no escapes from the wizard. We need to delay processing
591     * of these during boot as we need to look at all of the system packages in order
592     * to know which component is the setup wizard.
593     */
594    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
595    /**
596     * Whether or not processing protected filters should be deferred.
597     */
598    private boolean mDeferProtectedFilters = true;
599
600    /**
601     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
602     */
603    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
604    /**
605     * Whether or not system app permissions should be promoted from install to runtime.
606     */
607    boolean mPromoteSystemApps;
608
609    @GuardedBy("mPackages")
610    final Settings mSettings;
611
612    /**
613     * Set of package names that are currently "frozen", which means active
614     * surgery is being done on the code/data for that package. The platform
615     * will refuse to launch frozen packages to avoid race conditions.
616     *
617     * @see PackageFreezer
618     */
619    @GuardedBy("mPackages")
620    final ArraySet<String> mFrozenPackages = new ArraySet<>();
621
622    boolean mRestoredSettings;
623
624    // System configuration read by SystemConfig.
625    final int[] mGlobalGids;
626    final SparseArray<ArraySet<String>> mSystemPermissions;
627    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
628
629    // If mac_permissions.xml was found for seinfo labeling.
630    boolean mFoundPolicyFile;
631
632    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
633
634    public static final class SharedLibraryEntry {
635        public final String path;
636        public final String apk;
637
638        SharedLibraryEntry(String _path, String _apk) {
639            path = _path;
640            apk = _apk;
641        }
642    }
643
644    // Currently known shared libraries.
645    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
646            new ArrayMap<String, SharedLibraryEntry>();
647
648    // All available activities, for your resolving pleasure.
649    final ActivityIntentResolver mActivities =
650            new ActivityIntentResolver();
651
652    // All available receivers, for your resolving pleasure.
653    final ActivityIntentResolver mReceivers =
654            new ActivityIntentResolver();
655
656    // All available services, for your resolving pleasure.
657    final ServiceIntentResolver mServices = new ServiceIntentResolver();
658
659    // All available providers, for your resolving pleasure.
660    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
661
662    // Mapping from provider base names (first directory in content URI codePath)
663    // to the provider information.
664    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
665            new ArrayMap<String, PackageParser.Provider>();
666
667    // Mapping from instrumentation class names to info about them.
668    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
669            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
670
671    // Mapping from permission names to info about them.
672    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
673            new ArrayMap<String, PackageParser.PermissionGroup>();
674
675    // Packages whose data we have transfered into another package, thus
676    // should no longer exist.
677    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
678
679    // Broadcast actions that are only available to the system.
680    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
681
682    /** List of packages waiting for verification. */
683    final SparseArray<PackageVerificationState> mPendingVerification
684            = new SparseArray<PackageVerificationState>();
685
686    /** Set of packages associated with each app op permission. */
687    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
688
689    final PackageInstallerService mInstallerService;
690
691    private final PackageDexOptimizer mPackageDexOptimizer;
692
693    private AtomicInteger mNextMoveId = new AtomicInteger();
694    private final MoveCallbacks mMoveCallbacks;
695
696    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
697
698    // Cache of users who need badging.
699    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
700
701    /** Token for keys in mPendingVerification. */
702    private int mPendingVerificationToken = 0;
703
704    volatile boolean mSystemReady;
705    volatile boolean mSafeMode;
706    volatile boolean mHasSystemUidErrors;
707
708    ApplicationInfo mAndroidApplication;
709    final ActivityInfo mResolveActivity = new ActivityInfo();
710    final ResolveInfo mResolveInfo = new ResolveInfo();
711    ComponentName mResolveComponentName;
712    PackageParser.Package mPlatformPackage;
713    ComponentName mCustomResolverComponentName;
714
715    boolean mResolverReplaced = false;
716
717    private final @Nullable ComponentName mIntentFilterVerifierComponent;
718    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
719
720    private int mIntentFilterVerificationToken = 0;
721
722    /** Component that knows whether or not an ephemeral application exists */
723    final ComponentName mEphemeralResolverComponent;
724    /** The service connection to the ephemeral resolver */
725    final EphemeralResolverConnection mEphemeralResolverConnection;
726
727    /** Component used to install ephemeral applications */
728    final ComponentName mEphemeralInstallerComponent;
729    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
730    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
731
732    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
733            = new SparseArray<IntentFilterVerificationState>();
734
735    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
736            new DefaultPermissionGrantPolicy(this);
737
738    // List of packages names to keep cached, even if they are uninstalled for all users
739    private List<String> mKeepUninstalledPackages;
740
741    private UserManagerInternal mUserManagerInternal;
742
743    private static class IFVerificationParams {
744        PackageParser.Package pkg;
745        boolean replacing;
746        int userId;
747        int verifierUid;
748
749        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
750                int _userId, int _verifierUid) {
751            pkg = _pkg;
752            replacing = _replacing;
753            userId = _userId;
754            replacing = _replacing;
755            verifierUid = _verifierUid;
756        }
757    }
758
759    private interface IntentFilterVerifier<T extends IntentFilter> {
760        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
761                                               T filter, String packageName);
762        void startVerifications(int userId);
763        void receiveVerificationResponse(int verificationId);
764    }
765
766    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
767        private Context mContext;
768        private ComponentName mIntentFilterVerifierComponent;
769        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
770
771        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
772            mContext = context;
773            mIntentFilterVerifierComponent = verifierComponent;
774        }
775
776        private String getDefaultScheme() {
777            return IntentFilter.SCHEME_HTTPS;
778        }
779
780        @Override
781        public void startVerifications(int userId) {
782            // Launch verifications requests
783            int count = mCurrentIntentFilterVerifications.size();
784            for (int n=0; n<count; n++) {
785                int verificationId = mCurrentIntentFilterVerifications.get(n);
786                final IntentFilterVerificationState ivs =
787                        mIntentFilterVerificationStates.get(verificationId);
788
789                String packageName = ivs.getPackageName();
790
791                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
792                final int filterCount = filters.size();
793                ArraySet<String> domainsSet = new ArraySet<>();
794                for (int m=0; m<filterCount; m++) {
795                    PackageParser.ActivityIntentInfo filter = filters.get(m);
796                    domainsSet.addAll(filter.getHostsList());
797                }
798                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
799                synchronized (mPackages) {
800                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
801                            packageName, domainsList) != null) {
802                        scheduleWriteSettingsLocked();
803                    }
804                }
805                sendVerificationRequest(userId, verificationId, ivs);
806            }
807            mCurrentIntentFilterVerifications.clear();
808        }
809
810        private void sendVerificationRequest(int userId, int verificationId,
811                IntentFilterVerificationState ivs) {
812
813            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
814            verificationIntent.putExtra(
815                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
816                    verificationId);
817            verificationIntent.putExtra(
818                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
819                    getDefaultScheme());
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
822                    ivs.getHostsString());
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
825                    ivs.getPackageName());
826            verificationIntent.setComponent(mIntentFilterVerifierComponent);
827            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
828
829            UserHandle user = new UserHandle(userId);
830            mContext.sendBroadcastAsUser(verificationIntent, user);
831            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
832                    "Sending IntentFilter verification broadcast");
833        }
834
835        public void receiveVerificationResponse(int verificationId) {
836            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
837
838            final boolean verified = ivs.isVerified();
839
840            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
841            final int count = filters.size();
842            if (DEBUG_DOMAIN_VERIFICATION) {
843                Slog.i(TAG, "Received verification response " + verificationId
844                        + " for " + count + " filters, verified=" + verified);
845            }
846            for (int n=0; n<count; n++) {
847                PackageParser.ActivityIntentInfo filter = filters.get(n);
848                filter.setVerified(verified);
849
850                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
851                        + " verified with result:" + verified + " and hosts:"
852                        + ivs.getHostsString());
853            }
854
855            mIntentFilterVerificationStates.remove(verificationId);
856
857            final String packageName = ivs.getPackageName();
858            IntentFilterVerificationInfo ivi = null;
859
860            synchronized (mPackages) {
861                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
862            }
863            if (ivi == null) {
864                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
865                        + verificationId + " packageName:" + packageName);
866                return;
867            }
868            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
869                    "Updating IntentFilterVerificationInfo for package " + packageName
870                            +" verificationId:" + verificationId);
871
872            synchronized (mPackages) {
873                if (verified) {
874                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
875                } else {
876                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
877                }
878                scheduleWriteSettingsLocked();
879
880                final int userId = ivs.getUserId();
881                if (userId != UserHandle.USER_ALL) {
882                    final int userStatus =
883                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
884
885                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
886                    boolean needUpdate = false;
887
888                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
889                    // already been set by the User thru the Disambiguation dialog
890                    switch (userStatus) {
891                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
892                            if (verified) {
893                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
894                            } else {
895                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
896                            }
897                            needUpdate = true;
898                            break;
899
900                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
901                            if (verified) {
902                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
903                                needUpdate = true;
904                            }
905                            break;
906
907                        default:
908                            // Nothing to do
909                    }
910
911                    if (needUpdate) {
912                        mSettings.updateIntentFilterVerificationStatusLPw(
913                                packageName, updatedStatus, userId);
914                        scheduleWritePackageRestrictionsLocked(userId);
915                    }
916                }
917            }
918        }
919
920        @Override
921        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
922                    ActivityIntentInfo filter, String packageName) {
923            if (!hasValidDomains(filter)) {
924                return false;
925            }
926            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
927            if (ivs == null) {
928                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
929                        packageName);
930            }
931            if (DEBUG_DOMAIN_VERIFICATION) {
932                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
933            }
934            ivs.addFilter(filter);
935            return true;
936        }
937
938        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
939                int userId, int verificationId, String packageName) {
940            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
941                    verifierUid, userId, packageName);
942            ivs.setPendingState();
943            synchronized (mPackages) {
944                mIntentFilterVerificationStates.append(verificationId, ivs);
945                mCurrentIntentFilterVerifications.add(verificationId);
946            }
947            return ivs;
948        }
949    }
950
951    private static boolean hasValidDomains(ActivityIntentInfo filter) {
952        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
953                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
954                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
955    }
956
957    // Set of pending broadcasts for aggregating enable/disable of components.
958    static class PendingPackageBroadcasts {
959        // for each user id, a map of <package name -> components within that package>
960        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
961
962        public PendingPackageBroadcasts() {
963            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
964        }
965
966        public ArrayList<String> get(int userId, String packageName) {
967            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
968            return packages.get(packageName);
969        }
970
971        public void put(int userId, String packageName, ArrayList<String> components) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            packages.put(packageName, components);
974        }
975
976        public void remove(int userId, String packageName) {
977            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
978            if (packages != null) {
979                packages.remove(packageName);
980            }
981        }
982
983        public void remove(int userId) {
984            mUidMap.remove(userId);
985        }
986
987        public int userIdCount() {
988            return mUidMap.size();
989        }
990
991        public int userIdAt(int n) {
992            return mUidMap.keyAt(n);
993        }
994
995        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
996            return mUidMap.get(userId);
997        }
998
999        public int size() {
1000            // total number of pending broadcast entries across all userIds
1001            int num = 0;
1002            for (int i = 0; i< mUidMap.size(); i++) {
1003                num += mUidMap.valueAt(i).size();
1004            }
1005            return num;
1006        }
1007
1008        public void clear() {
1009            mUidMap.clear();
1010        }
1011
1012        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1013            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1014            if (map == null) {
1015                map = new ArrayMap<String, ArrayList<String>>();
1016                mUidMap.put(userId, map);
1017            }
1018            return map;
1019        }
1020    }
1021    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1022
1023    // Service Connection to remote media container service to copy
1024    // package uri's from external media onto secure containers
1025    // or internal storage.
1026    private IMediaContainerService mContainerService = null;
1027
1028    static final int SEND_PENDING_BROADCAST = 1;
1029    static final int MCS_BOUND = 3;
1030    static final int END_COPY = 4;
1031    static final int INIT_COPY = 5;
1032    static final int MCS_UNBIND = 6;
1033    static final int START_CLEANING_PACKAGE = 7;
1034    static final int FIND_INSTALL_LOC = 8;
1035    static final int POST_INSTALL = 9;
1036    static final int MCS_RECONNECT = 10;
1037    static final int MCS_GIVE_UP = 11;
1038    static final int UPDATED_MEDIA_STATUS = 12;
1039    static final int WRITE_SETTINGS = 13;
1040    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1041    static final int PACKAGE_VERIFIED = 15;
1042    static final int CHECK_PENDING_VERIFICATION = 16;
1043    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1044    static final int INTENT_FILTER_VERIFIED = 18;
1045    static final int WRITE_PACKAGE_LIST = 19;
1046
1047    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1048
1049    // Delay time in millisecs
1050    static final int BROADCAST_DELAY = 10 * 1000;
1051
1052    static UserManagerService sUserManager;
1053
1054    // Stores a list of users whose package restrictions file needs to be updated
1055    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1056
1057    final private DefaultContainerConnection mDefContainerConn =
1058            new DefaultContainerConnection();
1059    class DefaultContainerConnection implements ServiceConnection {
1060        public void onServiceConnected(ComponentName name, IBinder service) {
1061            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1062            IMediaContainerService imcs =
1063                IMediaContainerService.Stub.asInterface(service);
1064            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1065        }
1066
1067        public void onServiceDisconnected(ComponentName name) {
1068            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1069        }
1070    }
1071
1072    // Recordkeeping of restore-after-install operations that are currently in flight
1073    // between the Package Manager and the Backup Manager
1074    static class PostInstallData {
1075        public InstallArgs args;
1076        public PackageInstalledInfo res;
1077
1078        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1079            args = _a;
1080            res = _r;
1081        }
1082    }
1083
1084    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1085    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1086
1087    // XML tags for backup/restore of various bits of state
1088    private static final String TAG_PREFERRED_BACKUP = "pa";
1089    private static final String TAG_DEFAULT_APPS = "da";
1090    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1091
1092    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1093    private static final String TAG_ALL_GRANTS = "rt-grants";
1094    private static final String TAG_GRANT = "grant";
1095    private static final String ATTR_PACKAGE_NAME = "pkg";
1096
1097    private static final String TAG_PERMISSION = "perm";
1098    private static final String ATTR_PERMISSION_NAME = "name";
1099    private static final String ATTR_IS_GRANTED = "g";
1100    private static final String ATTR_USER_SET = "set";
1101    private static final String ATTR_USER_FIXED = "fixed";
1102    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1103
1104    // System/policy permission grants are not backed up
1105    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1106            FLAG_PERMISSION_POLICY_FIXED
1107            | FLAG_PERMISSION_SYSTEM_FIXED
1108            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1109
1110    // And we back up these user-adjusted states
1111    private static final int USER_RUNTIME_GRANT_MASK =
1112            FLAG_PERMISSION_USER_SET
1113            | FLAG_PERMISSION_USER_FIXED
1114            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1115
1116    final @Nullable String mRequiredVerifierPackage;
1117    final @NonNull String mRequiredInstallerPackage;
1118    final @Nullable String mSetupWizardPackage;
1119    final @NonNull String mServicesSystemSharedLibraryPackageName;
1120    final @NonNull String mSharedSystemSharedLibraryPackageName;
1121
1122    private final PackageUsage mPackageUsage = new PackageUsage();
1123
1124    private class PackageUsage {
1125        private static final int WRITE_INTERVAL
1126            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1127
1128        private final Object mFileLock = new Object();
1129        private final AtomicLong mLastWritten = new AtomicLong(0);
1130        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1131
1132        private boolean mIsHistoricalPackageUsageAvailable = true;
1133
1134        boolean isHistoricalPackageUsageAvailable() {
1135            return mIsHistoricalPackageUsageAvailable;
1136        }
1137
1138        void write(boolean force) {
1139            if (force) {
1140                writeInternal();
1141                return;
1142            }
1143            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1144                && !DEBUG_DEXOPT) {
1145                return;
1146            }
1147            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1148                new Thread("PackageUsage_DiskWriter") {
1149                    @Override
1150                    public void run() {
1151                        try {
1152                            writeInternal();
1153                        } finally {
1154                            mBackgroundWriteRunning.set(false);
1155                        }
1156                    }
1157                }.start();
1158            }
1159        }
1160
1161        private void writeInternal() {
1162            synchronized (mPackages) {
1163                synchronized (mFileLock) {
1164                    AtomicFile file = getFile();
1165                    FileOutputStream f = null;
1166                    try {
1167                        f = file.startWrite();
1168                        BufferedOutputStream out = new BufferedOutputStream(f);
1169                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1170                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1171                        StringBuilder sb = new StringBuilder();
1172
1173                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1174                        sb.append('\n');
1175                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1176
1177                        for (PackageParser.Package pkg : mPackages.values()) {
1178                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1179                                continue;
1180                            }
1181                            sb.setLength(0);
1182                            sb.append(pkg.packageName);
1183                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1184                                sb.append(' ');
1185                                sb.append(usageTimeInMillis);
1186                            }
1187                            sb.append('\n');
1188                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1189                        }
1190                        out.flush();
1191                        file.finishWrite(f);
1192                    } catch (IOException e) {
1193                        if (f != null) {
1194                            file.failWrite(f);
1195                        }
1196                        Log.e(TAG, "Failed to write package usage times", e);
1197                    }
1198                }
1199            }
1200            mLastWritten.set(SystemClock.elapsedRealtime());
1201        }
1202
1203        void readLP() {
1204            synchronized (mFileLock) {
1205                AtomicFile file = getFile();
1206                BufferedInputStream in = null;
1207                try {
1208                    in = new BufferedInputStream(file.openRead());
1209                    StringBuffer sb = new StringBuffer();
1210
1211                    String firstLine = readLine(in, sb);
1212                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1213                        readVersion1LP(in, sb);
1214                    } else {
1215                        readVersion0LP(in, sb, firstLine);
1216                    }
1217                } catch (FileNotFoundException expected) {
1218                    mIsHistoricalPackageUsageAvailable = false;
1219                } catch (IOException e) {
1220                    Log.w(TAG, "Failed to read package usage times", e);
1221                } finally {
1222                    IoUtils.closeQuietly(in);
1223                }
1224            }
1225            mLastWritten.set(SystemClock.elapsedRealtime());
1226        }
1227
1228        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1229                throws IOException {
1230            // Initial version of the file had no version number and stored one
1231            // package-timestamp pair per line.
1232            // Note that the first line has already been read from the InputStream.
1233            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1234                String[] tokens = line.split(" ");
1235                if (tokens.length != 2) {
1236                    throw new IOException("Failed to parse " + line +
1237                            " as package-timestamp pair.");
1238                }
1239
1240                String packageName = tokens[0];
1241                PackageParser.Package pkg = mPackages.get(packageName);
1242                if (pkg == null) {
1243                    continue;
1244                }
1245
1246                long timestamp = parseAsLong(tokens[1]);
1247                for (int reason = 0;
1248                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1249                        reason++) {
1250                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1251                }
1252            }
1253        }
1254
1255        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1256            // Version 1 of the file started with the corresponding version
1257            // number and then stored a package name and eight timestamps per line.
1258            String line;
1259            while ((line = readLine(in, sb)) != null) {
1260                String[] tokens = line.split(" ");
1261                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1262                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1263                }
1264
1265                String packageName = tokens[0];
1266                PackageParser.Package pkg = mPackages.get(packageName);
1267                if (pkg == null) {
1268                    continue;
1269                }
1270
1271                for (int reason = 0;
1272                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1273                        reason++) {
1274                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1275                }
1276            }
1277        }
1278
1279        private long parseAsLong(String token) throws IOException {
1280            try {
1281                return Long.parseLong(token);
1282            } catch (NumberFormatException e) {
1283                throw new IOException("Failed to parse " + token + " as a long.", e);
1284            }
1285        }
1286
1287        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1288            return readToken(in, sb, '\n');
1289        }
1290
1291        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1292                throws IOException {
1293            sb.setLength(0);
1294            while (true) {
1295                int ch = in.read();
1296                if (ch == -1) {
1297                    if (sb.length() == 0) {
1298                        return null;
1299                    }
1300                    throw new IOException("Unexpected EOF");
1301                }
1302                if (ch == endOfToken) {
1303                    return sb.toString();
1304                }
1305                sb.append((char)ch);
1306            }
1307        }
1308
1309        private AtomicFile getFile() {
1310            File dataDir = Environment.getDataDirectory();
1311            File systemDir = new File(dataDir, "system");
1312            File fname = new File(systemDir, "package-usage.list");
1313            return new AtomicFile(fname);
1314        }
1315
1316        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1317        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1318    }
1319
1320    class PackageHandler extends Handler {
1321        private boolean mBound = false;
1322        final ArrayList<HandlerParams> mPendingInstalls =
1323            new ArrayList<HandlerParams>();
1324
1325        private boolean connectToService() {
1326            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1327                    " DefaultContainerService");
1328            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1329            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1330            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1331                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1332                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1333                mBound = true;
1334                return true;
1335            }
1336            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1337            return false;
1338        }
1339
1340        private void disconnectService() {
1341            mContainerService = null;
1342            mBound = false;
1343            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1344            mContext.unbindService(mDefContainerConn);
1345            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1346        }
1347
1348        PackageHandler(Looper looper) {
1349            super(looper);
1350        }
1351
1352        public void handleMessage(Message msg) {
1353            try {
1354                doHandleMessage(msg);
1355            } finally {
1356                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1357            }
1358        }
1359
1360        void doHandleMessage(Message msg) {
1361            switch (msg.what) {
1362                case INIT_COPY: {
1363                    HandlerParams params = (HandlerParams) msg.obj;
1364                    int idx = mPendingInstalls.size();
1365                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1366                    // If a bind was already initiated we dont really
1367                    // need to do anything. The pending install
1368                    // will be processed later on.
1369                    if (!mBound) {
1370                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1371                                System.identityHashCode(mHandler));
1372                        // If this is the only one pending we might
1373                        // have to bind to the service again.
1374                        if (!connectToService()) {
1375                            Slog.e(TAG, "Failed to bind to media container service");
1376                            params.serviceError();
1377                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1378                                    System.identityHashCode(mHandler));
1379                            if (params.traceMethod != null) {
1380                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1381                                        params.traceCookie);
1382                            }
1383                            return;
1384                        } else {
1385                            // Once we bind to the service, the first
1386                            // pending request will be processed.
1387                            mPendingInstalls.add(idx, params);
1388                        }
1389                    } else {
1390                        mPendingInstalls.add(idx, params);
1391                        // Already bound to the service. Just make
1392                        // sure we trigger off processing the first request.
1393                        if (idx == 0) {
1394                            mHandler.sendEmptyMessage(MCS_BOUND);
1395                        }
1396                    }
1397                    break;
1398                }
1399                case MCS_BOUND: {
1400                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1401                    if (msg.obj != null) {
1402                        mContainerService = (IMediaContainerService) msg.obj;
1403                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1404                                System.identityHashCode(mHandler));
1405                    }
1406                    if (mContainerService == null) {
1407                        if (!mBound) {
1408                            // Something seriously wrong since we are not bound and we are not
1409                            // waiting for connection. Bail out.
1410                            Slog.e(TAG, "Cannot bind to media container service");
1411                            for (HandlerParams params : mPendingInstalls) {
1412                                // Indicate service bind error
1413                                params.serviceError();
1414                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1415                                        System.identityHashCode(params));
1416                                if (params.traceMethod != null) {
1417                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1418                                            params.traceMethod, params.traceCookie);
1419                                }
1420                                return;
1421                            }
1422                            mPendingInstalls.clear();
1423                        } else {
1424                            Slog.w(TAG, "Waiting to connect to media container service");
1425                        }
1426                    } else if (mPendingInstalls.size() > 0) {
1427                        HandlerParams params = mPendingInstalls.get(0);
1428                        if (params != null) {
1429                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1430                                    System.identityHashCode(params));
1431                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1432                            if (params.startCopy()) {
1433                                // We are done...  look for more work or to
1434                                // go idle.
1435                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1436                                        "Checking for more work or unbind...");
1437                                // Delete pending install
1438                                if (mPendingInstalls.size() > 0) {
1439                                    mPendingInstalls.remove(0);
1440                                }
1441                                if (mPendingInstalls.size() == 0) {
1442                                    if (mBound) {
1443                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1444                                                "Posting delayed MCS_UNBIND");
1445                                        removeMessages(MCS_UNBIND);
1446                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1447                                        // Unbind after a little delay, to avoid
1448                                        // continual thrashing.
1449                                        sendMessageDelayed(ubmsg, 10000);
1450                                    }
1451                                } else {
1452                                    // There are more pending requests in queue.
1453                                    // Just post MCS_BOUND message to trigger processing
1454                                    // of next pending install.
1455                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1456                                            "Posting MCS_BOUND for next work");
1457                                    mHandler.sendEmptyMessage(MCS_BOUND);
1458                                }
1459                            }
1460                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1461                        }
1462                    } else {
1463                        // Should never happen ideally.
1464                        Slog.w(TAG, "Empty queue");
1465                    }
1466                    break;
1467                }
1468                case MCS_RECONNECT: {
1469                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1470                    if (mPendingInstalls.size() > 0) {
1471                        if (mBound) {
1472                            disconnectService();
1473                        }
1474                        if (!connectToService()) {
1475                            Slog.e(TAG, "Failed to bind to media container service");
1476                            for (HandlerParams params : mPendingInstalls) {
1477                                // Indicate service bind error
1478                                params.serviceError();
1479                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1480                                        System.identityHashCode(params));
1481                            }
1482                            mPendingInstalls.clear();
1483                        }
1484                    }
1485                    break;
1486                }
1487                case MCS_UNBIND: {
1488                    // If there is no actual work left, then time to unbind.
1489                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1490
1491                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1492                        if (mBound) {
1493                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1494
1495                            disconnectService();
1496                        }
1497                    } else if (mPendingInstalls.size() > 0) {
1498                        // There are more pending requests in queue.
1499                        // Just post MCS_BOUND message to trigger processing
1500                        // of next pending install.
1501                        mHandler.sendEmptyMessage(MCS_BOUND);
1502                    }
1503
1504                    break;
1505                }
1506                case MCS_GIVE_UP: {
1507                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1508                    HandlerParams params = mPendingInstalls.remove(0);
1509                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1510                            System.identityHashCode(params));
1511                    break;
1512                }
1513                case SEND_PENDING_BROADCAST: {
1514                    String packages[];
1515                    ArrayList<String> components[];
1516                    int size = 0;
1517                    int uids[];
1518                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1519                    synchronized (mPackages) {
1520                        if (mPendingBroadcasts == null) {
1521                            return;
1522                        }
1523                        size = mPendingBroadcasts.size();
1524                        if (size <= 0) {
1525                            // Nothing to be done. Just return
1526                            return;
1527                        }
1528                        packages = new String[size];
1529                        components = new ArrayList[size];
1530                        uids = new int[size];
1531                        int i = 0;  // filling out the above arrays
1532
1533                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1534                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1535                            Iterator<Map.Entry<String, ArrayList<String>>> it
1536                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1537                                            .entrySet().iterator();
1538                            while (it.hasNext() && i < size) {
1539                                Map.Entry<String, ArrayList<String>> ent = it.next();
1540                                packages[i] = ent.getKey();
1541                                components[i] = ent.getValue();
1542                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1543                                uids[i] = (ps != null)
1544                                        ? UserHandle.getUid(packageUserId, ps.appId)
1545                                        : -1;
1546                                i++;
1547                            }
1548                        }
1549                        size = i;
1550                        mPendingBroadcasts.clear();
1551                    }
1552                    // Send broadcasts
1553                    for (int i = 0; i < size; i++) {
1554                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1555                    }
1556                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1557                    break;
1558                }
1559                case START_CLEANING_PACKAGE: {
1560                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1561                    final String packageName = (String)msg.obj;
1562                    final int userId = msg.arg1;
1563                    final boolean andCode = msg.arg2 != 0;
1564                    synchronized (mPackages) {
1565                        if (userId == UserHandle.USER_ALL) {
1566                            int[] users = sUserManager.getUserIds();
1567                            for (int user : users) {
1568                                mSettings.addPackageToCleanLPw(
1569                                        new PackageCleanItem(user, packageName, andCode));
1570                            }
1571                        } else {
1572                            mSettings.addPackageToCleanLPw(
1573                                    new PackageCleanItem(userId, packageName, andCode));
1574                        }
1575                    }
1576                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1577                    startCleaningPackages();
1578                } break;
1579                case POST_INSTALL: {
1580                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1581
1582                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1583                    final boolean didRestore = (msg.arg2 != 0);
1584                    mRunningInstalls.delete(msg.arg1);
1585
1586                    if (data != null) {
1587                        InstallArgs args = data.args;
1588                        PackageInstalledInfo parentRes = data.res;
1589
1590                        final boolean grantPermissions = (args.installFlags
1591                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1592                        final boolean killApp = (args.installFlags
1593                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1594                        final String[] grantedPermissions = args.installGrantPermissions;
1595
1596                        // Handle the parent package
1597                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1598                                grantedPermissions, didRestore, args.installerPackageName,
1599                                args.observer);
1600
1601                        // Handle the child packages
1602                        final int childCount = (parentRes.addedChildPackages != null)
1603                                ? parentRes.addedChildPackages.size() : 0;
1604                        for (int i = 0; i < childCount; i++) {
1605                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1606                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1607                                    grantedPermissions, false, args.installerPackageName,
1608                                    args.observer);
1609                        }
1610
1611                        // Log tracing if needed
1612                        if (args.traceMethod != null) {
1613                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1614                                    args.traceCookie);
1615                        }
1616                    } else {
1617                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1618                    }
1619
1620                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1621                } break;
1622                case UPDATED_MEDIA_STATUS: {
1623                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1624                    boolean reportStatus = msg.arg1 == 1;
1625                    boolean doGc = msg.arg2 == 1;
1626                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1627                    if (doGc) {
1628                        // Force a gc to clear up stale containers.
1629                        Runtime.getRuntime().gc();
1630                    }
1631                    if (msg.obj != null) {
1632                        @SuppressWarnings("unchecked")
1633                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1634                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1635                        // Unload containers
1636                        unloadAllContainers(args);
1637                    }
1638                    if (reportStatus) {
1639                        try {
1640                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1641                            PackageHelper.getMountService().finishMediaUpdate();
1642                        } catch (RemoteException e) {
1643                            Log.e(TAG, "MountService not running?");
1644                        }
1645                    }
1646                } break;
1647                case WRITE_SETTINGS: {
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1649                    synchronized (mPackages) {
1650                        removeMessages(WRITE_SETTINGS);
1651                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1652                        mSettings.writeLPr();
1653                        mDirtyUsers.clear();
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                } break;
1657                case WRITE_PACKAGE_RESTRICTIONS: {
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1659                    synchronized (mPackages) {
1660                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1661                        for (int userId : mDirtyUsers) {
1662                            mSettings.writePackageRestrictionsLPr(userId);
1663                        }
1664                        mDirtyUsers.clear();
1665                    }
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1667                } break;
1668                case WRITE_PACKAGE_LIST: {
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1670                    synchronized (mPackages) {
1671                        removeMessages(WRITE_PACKAGE_LIST);
1672                        mSettings.writePackageListLPr(msg.arg1);
1673                    }
1674                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1675                } break;
1676                case CHECK_PENDING_VERIFICATION: {
1677                    final int verificationId = msg.arg1;
1678                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1679
1680                    if ((state != null) && !state.timeoutExtended()) {
1681                        final InstallArgs args = state.getInstallArgs();
1682                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1683
1684                        Slog.i(TAG, "Verification timed out for " + originUri);
1685                        mPendingVerification.remove(verificationId);
1686
1687                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1688
1689                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1690                            Slog.i(TAG, "Continuing with installation of " + originUri);
1691                            state.setVerifierResponse(Binder.getCallingUid(),
1692                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1693                            broadcastPackageVerified(verificationId, originUri,
1694                                    PackageManager.VERIFICATION_ALLOW,
1695                                    state.getInstallArgs().getUser());
1696                            try {
1697                                ret = args.copyApk(mContainerService, true);
1698                            } catch (RemoteException e) {
1699                                Slog.e(TAG, "Could not contact the ContainerService");
1700                            }
1701                        } else {
1702                            broadcastPackageVerified(verificationId, originUri,
1703                                    PackageManager.VERIFICATION_REJECT,
1704                                    state.getInstallArgs().getUser());
1705                        }
1706
1707                        Trace.asyncTraceEnd(
1708                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1709
1710                        processPendingInstall(args, ret);
1711                        mHandler.sendEmptyMessage(MCS_UNBIND);
1712                    }
1713                    break;
1714                }
1715                case PACKAGE_VERIFIED: {
1716                    final int verificationId = msg.arg1;
1717
1718                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1719                    if (state == null) {
1720                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1721                        break;
1722                    }
1723
1724                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1725
1726                    state.setVerifierResponse(response.callerUid, response.code);
1727
1728                    if (state.isVerificationComplete()) {
1729                        mPendingVerification.remove(verificationId);
1730
1731                        final InstallArgs args = state.getInstallArgs();
1732                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1733
1734                        int ret;
1735                        if (state.isInstallAllowed()) {
1736                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1737                            broadcastPackageVerified(verificationId, originUri,
1738                                    response.code, state.getInstallArgs().getUser());
1739                            try {
1740                                ret = args.copyApk(mContainerService, true);
1741                            } catch (RemoteException e) {
1742                                Slog.e(TAG, "Could not contact the ContainerService");
1743                            }
1744                        } else {
1745                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1746                        }
1747
1748                        Trace.asyncTraceEnd(
1749                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1750
1751                        processPendingInstall(args, ret);
1752                        mHandler.sendEmptyMessage(MCS_UNBIND);
1753                    }
1754
1755                    break;
1756                }
1757                case START_INTENT_FILTER_VERIFICATIONS: {
1758                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1759                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1760                            params.replacing, params.pkg);
1761                    break;
1762                }
1763                case INTENT_FILTER_VERIFIED: {
1764                    final int verificationId = msg.arg1;
1765
1766                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1767                            verificationId);
1768                    if (state == null) {
1769                        Slog.w(TAG, "Invalid IntentFilter verification token "
1770                                + verificationId + " received");
1771                        break;
1772                    }
1773
1774                    final int userId = state.getUserId();
1775
1776                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1777                            "Processing IntentFilter verification with token:"
1778                            + verificationId + " and userId:" + userId);
1779
1780                    final IntentFilterVerificationResponse response =
1781                            (IntentFilterVerificationResponse) msg.obj;
1782
1783                    state.setVerifierResponse(response.callerUid, response.code);
1784
1785                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1786                            "IntentFilter verification with token:" + verificationId
1787                            + " and userId:" + userId
1788                            + " is settings verifier response with response code:"
1789                            + response.code);
1790
1791                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1792                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1793                                + response.getFailedDomainsString());
1794                    }
1795
1796                    if (state.isVerificationComplete()) {
1797                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1798                    } else {
1799                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1800                                "IntentFilter verification with token:" + verificationId
1801                                + " was not said to be complete");
1802                    }
1803
1804                    break;
1805                }
1806            }
1807        }
1808    }
1809
1810    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1811            boolean killApp, String[] grantedPermissions,
1812            boolean launchedForRestore, String installerPackage,
1813            IPackageInstallObserver2 installObserver) {
1814        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1815            // Send the removed broadcasts
1816            if (res.removedInfo != null) {
1817                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1818            }
1819
1820            // Now that we successfully installed the package, grant runtime
1821            // permissions if requested before broadcasting the install.
1822            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1823                    >= Build.VERSION_CODES.M) {
1824                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1825            }
1826
1827            final boolean update = res.removedInfo != null
1828                    && res.removedInfo.removedPackage != null;
1829
1830            // If this is the first time we have child packages for a disabled privileged
1831            // app that had no children, we grant requested runtime permissions to the new
1832            // children if the parent on the system image had them already granted.
1833            if (res.pkg.parentPackage != null) {
1834                synchronized (mPackages) {
1835                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1836                }
1837            }
1838
1839            synchronized (mPackages) {
1840                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1841            }
1842
1843            final String packageName = res.pkg.applicationInfo.packageName;
1844            Bundle extras = new Bundle(1);
1845            extras.putInt(Intent.EXTRA_UID, res.uid);
1846
1847            // Determine the set of users who are adding this package for
1848            // the first time vs. those who are seeing an update.
1849            int[] firstUsers = EMPTY_INT_ARRAY;
1850            int[] updateUsers = EMPTY_INT_ARRAY;
1851            if (res.origUsers == null || res.origUsers.length == 0) {
1852                firstUsers = res.newUsers;
1853            } else {
1854                for (int newUser : res.newUsers) {
1855                    boolean isNew = true;
1856                    for (int origUser : res.origUsers) {
1857                        if (origUser == newUser) {
1858                            isNew = false;
1859                            break;
1860                        }
1861                    }
1862                    if (isNew) {
1863                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1864                    } else {
1865                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1866                    }
1867                }
1868            }
1869
1870            // Send installed broadcasts if the install/update is not ephemeral
1871            if (!isEphemeral(res.pkg)) {
1872                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1873
1874                // Send added for users that see the package for the first time
1875                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1876                        extras, 0 /*flags*/, null /*targetPackage*/,
1877                        null /*finishedReceiver*/, firstUsers);
1878
1879                // Send added for users that don't see the package for the first time
1880                if (update) {
1881                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1882                }
1883                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1884                        extras, 0 /*flags*/, null /*targetPackage*/,
1885                        null /*finishedReceiver*/, updateUsers);
1886
1887                // Send replaced for users that don't see the package for the first time
1888                if (update) {
1889                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1890                            packageName, extras, 0 /*flags*/,
1891                            null /*targetPackage*/, null /*finishedReceiver*/,
1892                            updateUsers);
1893                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1894                            null /*package*/, null /*extras*/, 0 /*flags*/,
1895                            packageName /*targetPackage*/,
1896                            null /*finishedReceiver*/, updateUsers);
1897                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1898                    // First-install and we did a restore, so we're responsible for the
1899                    // first-launch broadcast.
1900                    if (DEBUG_BACKUP) {
1901                        Slog.i(TAG, "Post-restore of " + packageName
1902                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1903                    }
1904                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1905                }
1906
1907                // Send broadcast package appeared if forward locked/external for all users
1908                // treat asec-hosted packages like removable media on upgrade
1909                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1910                    if (DEBUG_INSTALL) {
1911                        Slog.i(TAG, "upgrading pkg " + res.pkg
1912                                + " is ASEC-hosted -> AVAILABLE");
1913                    }
1914                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1915                    ArrayList<String> pkgList = new ArrayList<>(1);
1916                    pkgList.add(packageName);
1917                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1918                }
1919            }
1920
1921            // Work that needs to happen on first install within each user
1922            if (firstUsers != null && firstUsers.length > 0) {
1923                synchronized (mPackages) {
1924                    for (int userId : firstUsers) {
1925                        // If this app is a browser and it's newly-installed for some
1926                        // users, clear any default-browser state in those users. The
1927                        // app's nature doesn't depend on the user, so we can just check
1928                        // its browser nature in any user and generalize.
1929                        if (packageIsBrowser(packageName, userId)) {
1930                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1931                        }
1932
1933                        // We may also need to apply pending (restored) runtime
1934                        // permission grants within these users.
1935                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1936                    }
1937                }
1938            }
1939
1940            // Log current value of "unknown sources" setting
1941            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1942                    getUnknownSourcesSettings());
1943
1944            // Force a gc to clear up things
1945            Runtime.getRuntime().gc();
1946
1947            // Remove the replaced package's older resources safely now
1948            // We delete after a gc for applications  on sdcard.
1949            if (res.removedInfo != null && res.removedInfo.args != null) {
1950                synchronized (mInstallLock) {
1951                    res.removedInfo.args.doPostDeleteLI(true);
1952                }
1953            }
1954        }
1955
1956        // If someone is watching installs - notify them
1957        if (installObserver != null) {
1958            try {
1959                Bundle extras = extrasForInstallResult(res);
1960                installObserver.onPackageInstalled(res.name, res.returnCode,
1961                        res.returnMsg, extras);
1962            } catch (RemoteException e) {
1963                Slog.i(TAG, "Observer no longer exists.");
1964            }
1965        }
1966    }
1967
1968    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1969            PackageParser.Package pkg) {
1970        if (pkg.parentPackage == null) {
1971            return;
1972        }
1973        if (pkg.requestedPermissions == null) {
1974            return;
1975        }
1976        final PackageSetting disabledSysParentPs = mSettings
1977                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1978        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1979                || !disabledSysParentPs.isPrivileged()
1980                || (disabledSysParentPs.childPackageNames != null
1981                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1982            return;
1983        }
1984        final int[] allUserIds = sUserManager.getUserIds();
1985        final int permCount = pkg.requestedPermissions.size();
1986        for (int i = 0; i < permCount; i++) {
1987            String permission = pkg.requestedPermissions.get(i);
1988            BasePermission bp = mSettings.mPermissions.get(permission);
1989            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1990                continue;
1991            }
1992            for (int userId : allUserIds) {
1993                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1994                        permission, userId)) {
1995                    grantRuntimePermission(pkg.packageName, permission, userId);
1996                }
1997            }
1998        }
1999    }
2000
2001    private StorageEventListener mStorageListener = new StorageEventListener() {
2002        @Override
2003        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2004            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2005                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2006                    final String volumeUuid = vol.getFsUuid();
2007
2008                    // Clean up any users or apps that were removed or recreated
2009                    // while this volume was missing
2010                    reconcileUsers(volumeUuid);
2011                    reconcileApps(volumeUuid);
2012
2013                    // Clean up any install sessions that expired or were
2014                    // cancelled while this volume was missing
2015                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2016
2017                    loadPrivatePackages(vol);
2018
2019                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2020                    unloadPrivatePackages(vol);
2021                }
2022            }
2023
2024            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2025                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2026                    updateExternalMediaStatus(true, false);
2027                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2028                    updateExternalMediaStatus(false, false);
2029                }
2030            }
2031        }
2032
2033        @Override
2034        public void onVolumeForgotten(String fsUuid) {
2035            if (TextUtils.isEmpty(fsUuid)) {
2036                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2037                return;
2038            }
2039
2040            // Remove any apps installed on the forgotten volume
2041            synchronized (mPackages) {
2042                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2043                for (PackageSetting ps : packages) {
2044                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2045                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2046                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2047                }
2048
2049                mSettings.onVolumeForgotten(fsUuid);
2050                mSettings.writeLPr();
2051            }
2052        }
2053    };
2054
2055    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2056            String[] grantedPermissions) {
2057        for (int userId : userIds) {
2058            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2059        }
2060
2061        // We could have touched GID membership, so flush out packages.list
2062        synchronized (mPackages) {
2063            mSettings.writePackageListLPr();
2064        }
2065    }
2066
2067    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2068            String[] grantedPermissions) {
2069        SettingBase sb = (SettingBase) pkg.mExtras;
2070        if (sb == null) {
2071            return;
2072        }
2073
2074        PermissionsState permissionsState = sb.getPermissionsState();
2075
2076        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2077                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2078
2079        for (String permission : pkg.requestedPermissions) {
2080            final BasePermission bp;
2081            synchronized (mPackages) {
2082                bp = mSettings.mPermissions.get(permission);
2083            }
2084            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2085                    && (grantedPermissions == null
2086                           || ArrayUtils.contains(grantedPermissions, permission))) {
2087                final int flags = permissionsState.getPermissionFlags(permission, userId);
2088                // Installer cannot change immutable permissions.
2089                if ((flags & immutableFlags) == 0) {
2090                    grantRuntimePermission(pkg.packageName, permission, userId);
2091                }
2092            }
2093        }
2094    }
2095
2096    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2097        Bundle extras = null;
2098        switch (res.returnCode) {
2099            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2100                extras = new Bundle();
2101                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2102                        res.origPermission);
2103                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2104                        res.origPackage);
2105                break;
2106            }
2107            case PackageManager.INSTALL_SUCCEEDED: {
2108                extras = new Bundle();
2109                extras.putBoolean(Intent.EXTRA_REPLACING,
2110                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2111                break;
2112            }
2113        }
2114        return extras;
2115    }
2116
2117    void scheduleWriteSettingsLocked() {
2118        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2119            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2120        }
2121    }
2122
2123    void scheduleWritePackageListLocked(int userId) {
2124        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2125            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2126            msg.arg1 = userId;
2127            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2128        }
2129    }
2130
2131    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2132        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2133        scheduleWritePackageRestrictionsLocked(userId);
2134    }
2135
2136    void scheduleWritePackageRestrictionsLocked(int userId) {
2137        final int[] userIds = (userId == UserHandle.USER_ALL)
2138                ? sUserManager.getUserIds() : new int[]{userId};
2139        for (int nextUserId : userIds) {
2140            if (!sUserManager.exists(nextUserId)) return;
2141            mDirtyUsers.add(nextUserId);
2142            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2143                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2144            }
2145        }
2146    }
2147
2148    public static PackageManagerService main(Context context, Installer installer,
2149            boolean factoryTest, boolean onlyCore) {
2150        // Self-check for initial settings.
2151        PackageManagerServiceCompilerMapping.checkProperties();
2152
2153        PackageManagerService m = new PackageManagerService(context, installer,
2154                factoryTest, onlyCore);
2155        m.enableSystemUserPackages();
2156        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2157        // disabled after already being started.
2158        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2159                UserHandle.USER_SYSTEM);
2160        ServiceManager.addService("package", m);
2161        return m;
2162    }
2163
2164    private void enableSystemUserPackages() {
2165        if (!UserManager.isSplitSystemUser()) {
2166            return;
2167        }
2168        // For system user, enable apps based on the following conditions:
2169        // - app is whitelisted or belong to one of these groups:
2170        //   -- system app which has no launcher icons
2171        //   -- system app which has INTERACT_ACROSS_USERS permission
2172        //   -- system IME app
2173        // - app is not in the blacklist
2174        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2175        Set<String> enableApps = new ArraySet<>();
2176        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2177                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2178                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2179        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2180        enableApps.addAll(wlApps);
2181        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2182                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2183        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2184        enableApps.removeAll(blApps);
2185        Log.i(TAG, "Applications installed for system user: " + enableApps);
2186        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2187                UserHandle.SYSTEM);
2188        final int allAppsSize = allAps.size();
2189        synchronized (mPackages) {
2190            for (int i = 0; i < allAppsSize; i++) {
2191                String pName = allAps.get(i);
2192                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2193                // Should not happen, but we shouldn't be failing if it does
2194                if (pkgSetting == null) {
2195                    continue;
2196                }
2197                boolean install = enableApps.contains(pName);
2198                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2199                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2200                            + " for system user");
2201                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2202                }
2203            }
2204        }
2205    }
2206
2207    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2208        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2209                Context.DISPLAY_SERVICE);
2210        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2211    }
2212
2213    public PackageManagerService(Context context, Installer installer,
2214            boolean factoryTest, boolean onlyCore) {
2215        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2216                SystemClock.uptimeMillis());
2217
2218        if (mSdkVersion <= 0) {
2219            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2220        }
2221
2222        mContext = context;
2223        mFactoryTest = factoryTest;
2224        mOnlyCore = onlyCore;
2225        mMetrics = new DisplayMetrics();
2226        mSettings = new Settings(mPackages);
2227        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2228                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2229        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2230                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2231        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2232                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2233        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2234                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2235        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2236                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2237        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239
2240        String separateProcesses = SystemProperties.get("debug.separate_processes");
2241        if (separateProcesses != null && separateProcesses.length() > 0) {
2242            if ("*".equals(separateProcesses)) {
2243                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2244                mSeparateProcesses = null;
2245                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2246            } else {
2247                mDefParseFlags = 0;
2248                mSeparateProcesses = separateProcesses.split(",");
2249                Slog.w(TAG, "Running with debug.separate_processes: "
2250                        + separateProcesses);
2251            }
2252        } else {
2253            mDefParseFlags = 0;
2254            mSeparateProcesses = null;
2255        }
2256
2257        mInstaller = installer;
2258        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2259                "*dexopt*");
2260        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2261
2262        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2263                FgThread.get().getLooper());
2264
2265        getDefaultDisplayMetrics(context, mMetrics);
2266
2267        SystemConfig systemConfig = SystemConfig.getInstance();
2268        mGlobalGids = systemConfig.getGlobalGids();
2269        mSystemPermissions = systemConfig.getSystemPermissions();
2270        mAvailableFeatures = systemConfig.getAvailableFeatures();
2271
2272        synchronized (mInstallLock) {
2273        // writer
2274        synchronized (mPackages) {
2275            mHandlerThread = new ServiceThread(TAG,
2276                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2277            mHandlerThread.start();
2278            mHandler = new PackageHandler(mHandlerThread.getLooper());
2279            mProcessLoggingHandler = new ProcessLoggingHandler();
2280            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2281
2282            File dataDir = Environment.getDataDirectory();
2283            mAppInstallDir = new File(dataDir, "app");
2284            mAppLib32InstallDir = new File(dataDir, "app-lib");
2285            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2286            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2287            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2288
2289            sUserManager = new UserManagerService(context, this, mPackages);
2290
2291            // Propagate permission configuration in to package manager.
2292            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2293                    = systemConfig.getPermissions();
2294            for (int i=0; i<permConfig.size(); i++) {
2295                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2296                BasePermission bp = mSettings.mPermissions.get(perm.name);
2297                if (bp == null) {
2298                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2299                    mSettings.mPermissions.put(perm.name, bp);
2300                }
2301                if (perm.gids != null) {
2302                    bp.setGids(perm.gids, perm.perUser);
2303                }
2304            }
2305
2306            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2307            for (int i=0; i<libConfig.size(); i++) {
2308                mSharedLibraries.put(libConfig.keyAt(i),
2309                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2310            }
2311
2312            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2313
2314            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2315
2316            String customResolverActivity = Resources.getSystem().getString(
2317                    R.string.config_customResolverActivity);
2318            if (TextUtils.isEmpty(customResolverActivity)) {
2319                customResolverActivity = null;
2320            } else {
2321                mCustomResolverComponentName = ComponentName.unflattenFromString(
2322                        customResolverActivity);
2323            }
2324
2325            long startTime = SystemClock.uptimeMillis();
2326
2327            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2328                    startTime);
2329
2330            // Set flag to monitor and not change apk file paths when
2331            // scanning install directories.
2332            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2333
2334            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2335            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2336
2337            if (bootClassPath == null) {
2338                Slog.w(TAG, "No BOOTCLASSPATH found!");
2339            }
2340
2341            if (systemServerClassPath == null) {
2342                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2343            }
2344
2345            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2346            final String[] dexCodeInstructionSets =
2347                    getDexCodeInstructionSets(
2348                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2349
2350            /**
2351             * Ensure all external libraries have had dexopt run on them.
2352             */
2353            if (mSharedLibraries.size() > 0) {
2354                // NOTE: For now, we're compiling these system "shared libraries"
2355                // (and framework jars) into all available architectures. It's possible
2356                // to compile them only when we come across an app that uses them (there's
2357                // already logic for that in scanPackageLI) but that adds some complexity.
2358                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2359                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2360                        final String lib = libEntry.path;
2361                        if (lib == null) {
2362                            continue;
2363                        }
2364
2365                        try {
2366                            // Shared libraries do not have profiles so we perform a full
2367                            // AOT compilation (if needed).
2368                            int dexoptNeeded = DexFile.getDexOptNeeded(
2369                                    lib, dexCodeInstructionSet,
2370                                    getCompilerFilterForReason(REASON_SHARED_APK),
2371                                    false /* newProfile */);
2372                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2373                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2374                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2375                                        getCompilerFilterForReason(REASON_SHARED_APK),
2376                                        StorageManager.UUID_PRIVATE_INTERNAL,
2377                                        SKIP_SHARED_LIBRARY_CHECK);
2378                            }
2379                        } catch (FileNotFoundException e) {
2380                            Slog.w(TAG, "Library not found: " + lib);
2381                        } catch (IOException | InstallerException e) {
2382                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2383                                    + e.getMessage());
2384                        }
2385                    }
2386                }
2387            }
2388
2389            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2390
2391            final VersionInfo ver = mSettings.getInternalVersion();
2392            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2393
2394            // when upgrading from pre-M, promote system app permissions from install to runtime
2395            mPromoteSystemApps =
2396                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2397
2398            // When upgrading from pre-N, we need to handle package extraction like first boot,
2399            // as there is no profiling data available.
2400            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2401
2402            // save off the names of pre-existing system packages prior to scanning; we don't
2403            // want to automatically grant runtime permissions for new system apps
2404            if (mPromoteSystemApps) {
2405                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2406                while (pkgSettingIter.hasNext()) {
2407                    PackageSetting ps = pkgSettingIter.next();
2408                    if (isSystemApp(ps)) {
2409                        mExistingSystemPackages.add(ps.name);
2410                    }
2411                }
2412            }
2413
2414            // Collect vendor overlay packages.
2415            // (Do this before scanning any apps.)
2416            // For security and version matching reason, only consider
2417            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2418            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2419            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2420                    | PackageParser.PARSE_IS_SYSTEM
2421                    | PackageParser.PARSE_IS_SYSTEM_DIR
2422                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2423
2424            // Find base frameworks (resource packages without code).
2425            scanDirTracedLI(frameworkDir, mDefParseFlags
2426                    | PackageParser.PARSE_IS_SYSTEM
2427                    | PackageParser.PARSE_IS_SYSTEM_DIR
2428                    | PackageParser.PARSE_IS_PRIVILEGED,
2429                    scanFlags | SCAN_NO_DEX, 0);
2430
2431            // Collected privileged system packages.
2432            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2433            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2434                    | PackageParser.PARSE_IS_SYSTEM
2435                    | PackageParser.PARSE_IS_SYSTEM_DIR
2436                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2437
2438            // Collect ordinary system packages.
2439            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2440            scanDirTracedLI(systemAppDir, mDefParseFlags
2441                    | PackageParser.PARSE_IS_SYSTEM
2442                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2443
2444            // Collect all vendor packages.
2445            File vendorAppDir = new File("/vendor/app");
2446            try {
2447                vendorAppDir = vendorAppDir.getCanonicalFile();
2448            } catch (IOException e) {
2449                // failed to look up canonical path, continue with original one
2450            }
2451            scanDirTracedLI(vendorAppDir, mDefParseFlags
2452                    | PackageParser.PARSE_IS_SYSTEM
2453                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2454
2455            // Collect all OEM packages.
2456            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2457            scanDirTracedLI(oemAppDir, mDefParseFlags
2458                    | PackageParser.PARSE_IS_SYSTEM
2459                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2460
2461            // Prune any system packages that no longer exist.
2462            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2463            if (!mOnlyCore) {
2464                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2465                while (psit.hasNext()) {
2466                    PackageSetting ps = psit.next();
2467
2468                    /*
2469                     * If this is not a system app, it can't be a
2470                     * disable system app.
2471                     */
2472                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2473                        continue;
2474                    }
2475
2476                    /*
2477                     * If the package is scanned, it's not erased.
2478                     */
2479                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2480                    if (scannedPkg != null) {
2481                        /*
2482                         * If the system app is both scanned and in the
2483                         * disabled packages list, then it must have been
2484                         * added via OTA. Remove it from the currently
2485                         * scanned package so the previously user-installed
2486                         * application can be scanned.
2487                         */
2488                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2489                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2490                                    + ps.name + "; removing system app.  Last known codePath="
2491                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2492                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2493                                    + scannedPkg.mVersionCode);
2494                            removePackageLI(scannedPkg, true);
2495                            mExpectingBetter.put(ps.name, ps.codePath);
2496                        }
2497
2498                        continue;
2499                    }
2500
2501                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2502                        psit.remove();
2503                        logCriticalInfo(Log.WARN, "System package " + ps.name
2504                                + " no longer exists; it's data will be wiped");
2505                        // Actual deletion of code and data will be handled by later
2506                        // reconciliation step
2507                    } else {
2508                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2509                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2510                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2511                        }
2512                    }
2513                }
2514            }
2515
2516            //look for any incomplete package installations
2517            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2518            for (int i = 0; i < deletePkgsList.size(); i++) {
2519                // Actual deletion of code and data will be handled by later
2520                // reconciliation step
2521                final String packageName = deletePkgsList.get(i).name;
2522                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2523                synchronized (mPackages) {
2524                    mSettings.removePackageLPw(packageName);
2525                }
2526            }
2527
2528            //delete tmp files
2529            deleteTempPackageFiles();
2530
2531            // Remove any shared userIDs that have no associated packages
2532            mSettings.pruneSharedUsersLPw();
2533
2534            if (!mOnlyCore) {
2535                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2536                        SystemClock.uptimeMillis());
2537                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2538
2539                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2540                        | PackageParser.PARSE_FORWARD_LOCK,
2541                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2542
2543                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2544                        | PackageParser.PARSE_IS_EPHEMERAL,
2545                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2546
2547                /**
2548                 * Remove disable package settings for any updated system
2549                 * apps that were removed via an OTA. If they're not a
2550                 * previously-updated app, remove them completely.
2551                 * Otherwise, just revoke their system-level permissions.
2552                 */
2553                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2554                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2555                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2556
2557                    String msg;
2558                    if (deletedPkg == null) {
2559                        msg = "Updated system package " + deletedAppName
2560                                + " no longer exists; it's data will be wiped";
2561                        // Actual deletion of code and data will be handled by later
2562                        // reconciliation step
2563                    } else {
2564                        msg = "Updated system app + " + deletedAppName
2565                                + " no longer present; removing system privileges for "
2566                                + deletedAppName;
2567
2568                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2569
2570                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2571                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2572                    }
2573                    logCriticalInfo(Log.WARN, msg);
2574                }
2575
2576                /**
2577                 * Make sure all system apps that we expected to appear on
2578                 * the userdata partition actually showed up. If they never
2579                 * appeared, crawl back and revive the system version.
2580                 */
2581                for (int i = 0; i < mExpectingBetter.size(); i++) {
2582                    final String packageName = mExpectingBetter.keyAt(i);
2583                    if (!mPackages.containsKey(packageName)) {
2584                        final File scanFile = mExpectingBetter.valueAt(i);
2585
2586                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2587                                + " but never showed up; reverting to system");
2588
2589                        int reparseFlags = mDefParseFlags;
2590                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2591                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2592                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2593                                    | PackageParser.PARSE_IS_PRIVILEGED;
2594                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2595                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2596                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2597                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2598                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2599                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2600                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2601                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2602                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2603                        } else {
2604                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2605                            continue;
2606                        }
2607
2608                        mSettings.enableSystemPackageLPw(packageName);
2609
2610                        try {
2611                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2612                        } catch (PackageManagerException e) {
2613                            Slog.e(TAG, "Failed to parse original system package: "
2614                                    + e.getMessage());
2615                        }
2616                    }
2617                }
2618            }
2619            mExpectingBetter.clear();
2620
2621            // Resolve protected action filters. Only the setup wizard is allowed to
2622            // have a high priority filter for these actions.
2623            mSetupWizardPackage = getSetupWizardPackageName();
2624            if (mProtectedFilters.size() > 0) {
2625                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2626                    Slog.i(TAG, "No setup wizard;"
2627                        + " All protected intents capped to priority 0");
2628                }
2629                for (ActivityIntentInfo filter : mProtectedFilters) {
2630                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2631                        if (DEBUG_FILTERS) {
2632                            Slog.i(TAG, "Found setup wizard;"
2633                                + " allow priority " + filter.getPriority() + ";"
2634                                + " package: " + filter.activity.info.packageName
2635                                + " activity: " + filter.activity.className
2636                                + " priority: " + filter.getPriority());
2637                        }
2638                        // skip setup wizard; allow it to keep the high priority filter
2639                        continue;
2640                    }
2641                    Slog.w(TAG, "Protected action; cap priority to 0;"
2642                            + " package: " + filter.activity.info.packageName
2643                            + " activity: " + filter.activity.className
2644                            + " origPrio: " + filter.getPriority());
2645                    filter.setPriority(0);
2646                }
2647            }
2648            mDeferProtectedFilters = false;
2649            mProtectedFilters.clear();
2650
2651            // Now that we know all of the shared libraries, update all clients to have
2652            // the correct library paths.
2653            updateAllSharedLibrariesLPw();
2654
2655            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2656                // NOTE: We ignore potential failures here during a system scan (like
2657                // the rest of the commands above) because there's precious little we
2658                // can do about it. A settings error is reported, though.
2659                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2660                        false /* boot complete */);
2661            }
2662
2663            // Now that we know all the packages we are keeping,
2664            // read and update their last usage times.
2665            mPackageUsage.readLP();
2666
2667            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2668                    SystemClock.uptimeMillis());
2669            Slog.i(TAG, "Time to scan packages: "
2670                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2671                    + " seconds");
2672
2673            // If the platform SDK has changed since the last time we booted,
2674            // we need to re-grant app permission to catch any new ones that
2675            // appear.  This is really a hack, and means that apps can in some
2676            // cases get permissions that the user didn't initially explicitly
2677            // allow...  it would be nice to have some better way to handle
2678            // this situation.
2679            int updateFlags = UPDATE_PERMISSIONS_ALL;
2680            if (ver.sdkVersion != mSdkVersion) {
2681                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2682                        + mSdkVersion + "; regranting permissions for internal storage");
2683                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2684            }
2685            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2686            ver.sdkVersion = mSdkVersion;
2687
2688            // If this is the first boot or an update from pre-M, and it is a normal
2689            // boot, then we need to initialize the default preferred apps across
2690            // all defined users.
2691            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2692                for (UserInfo user : sUserManager.getUsers(true)) {
2693                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2694                    applyFactoryDefaultBrowserLPw(user.id);
2695                    primeDomainVerificationsLPw(user.id);
2696                }
2697            }
2698
2699            // Prepare storage for system user really early during boot,
2700            // since core system apps like SettingsProvider and SystemUI
2701            // can't wait for user to start
2702            final int storageFlags;
2703            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2704                storageFlags = StorageManager.FLAG_STORAGE_DE;
2705            } else {
2706                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2707            }
2708            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2709                    storageFlags);
2710
2711            // If this is first boot after an OTA, and a normal boot, then
2712            // we need to clear code cache directories.
2713            // Note that we do *not* clear the application profiles. These remain valid
2714            // across OTAs and are used to drive profile verification (post OTA) and
2715            // profile compilation (without waiting to collect a fresh set of profiles).
2716            if (mIsUpgrade && !onlyCore) {
2717                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2718                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2719                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2720                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2721                        // No apps are running this early, so no need to freeze
2722                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2723                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2724                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2725                    }
2726                    clearAppProfilesLIF(ps.pkg, UserHandle.USER_ALL);
2727                }
2728                ver.fingerprint = Build.FINGERPRINT;
2729            }
2730
2731            checkDefaultBrowser();
2732
2733            // clear only after permissions and other defaults have been updated
2734            mExistingSystemPackages.clear();
2735            mPromoteSystemApps = false;
2736
2737            // All the changes are done during package scanning.
2738            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2739
2740            // can downgrade to reader
2741            mSettings.writeLPr();
2742
2743            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2744                    SystemClock.uptimeMillis());
2745
2746            if (!mOnlyCore) {
2747                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2748                mRequiredInstallerPackage = getRequiredInstallerLPr();
2749                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2750                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2751                        mIntentFilterVerifierComponent);
2752                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2753                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2754                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2755                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2756            } else {
2757                mRequiredVerifierPackage = null;
2758                mRequiredInstallerPackage = null;
2759                mIntentFilterVerifierComponent = null;
2760                mIntentFilterVerifier = null;
2761                mServicesSystemSharedLibraryPackageName = null;
2762                mSharedSystemSharedLibraryPackageName = null;
2763            }
2764
2765            mInstallerService = new PackageInstallerService(context, this);
2766
2767            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2768            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2769            // both the installer and resolver must be present to enable ephemeral
2770            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2771                if (DEBUG_EPHEMERAL) {
2772                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2773                            + " installer:" + ephemeralInstallerComponent);
2774                }
2775                mEphemeralResolverComponent = ephemeralResolverComponent;
2776                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2777                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2778                mEphemeralResolverConnection =
2779                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2780            } else {
2781                if (DEBUG_EPHEMERAL) {
2782                    final String missingComponent =
2783                            (ephemeralResolverComponent == null)
2784                            ? (ephemeralInstallerComponent == null)
2785                                    ? "resolver and installer"
2786                                    : "resolver"
2787                            : "installer";
2788                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2789                }
2790                mEphemeralResolverComponent = null;
2791                mEphemeralInstallerComponent = null;
2792                mEphemeralResolverConnection = null;
2793            }
2794
2795            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2796        } // synchronized (mPackages)
2797        } // synchronized (mInstallLock)
2798
2799        // Now after opening every single application zip, make sure they
2800        // are all flushed.  Not really needed, but keeps things nice and
2801        // tidy.
2802        Runtime.getRuntime().gc();
2803
2804        // The initial scanning above does many calls into installd while
2805        // holding the mPackages lock, but we're mostly interested in yelling
2806        // once we have a booted system.
2807        mInstaller.setWarnIfHeld(mPackages);
2808
2809        // Expose private service for system components to use.
2810        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2811    }
2812
2813    @Override
2814    public boolean isFirstBoot() {
2815        return !mRestoredSettings;
2816    }
2817
2818    @Override
2819    public boolean isOnlyCoreApps() {
2820        return mOnlyCore;
2821    }
2822
2823    @Override
2824    public boolean isUpgrade() {
2825        return mIsUpgrade;
2826    }
2827
2828    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2829        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2830
2831        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2832                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2833                UserHandle.USER_SYSTEM);
2834        if (matches.size() == 1) {
2835            return matches.get(0).getComponentInfo().packageName;
2836        } else {
2837            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2838            return null;
2839        }
2840    }
2841
2842    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2843        synchronized (mPackages) {
2844            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2845            if (libraryEntry == null) {
2846                throw new IllegalStateException("Missing required shared library:" + libraryName);
2847            }
2848            return libraryEntry.apk;
2849        }
2850    }
2851
2852    private @NonNull String getRequiredInstallerLPr() {
2853        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2854        intent.addCategory(Intent.CATEGORY_DEFAULT);
2855        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2856
2857        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2858                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2859                UserHandle.USER_SYSTEM);
2860        if (matches.size() == 1) {
2861            ResolveInfo resolveInfo = matches.get(0);
2862            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2863                throw new RuntimeException("The installer must be a privileged app");
2864            }
2865            return matches.get(0).getComponentInfo().packageName;
2866        } else {
2867            throw new RuntimeException("There must be exactly one installer; found " + matches);
2868        }
2869    }
2870
2871    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2872        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2873
2874        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2875                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2876                UserHandle.USER_SYSTEM);
2877        ResolveInfo best = null;
2878        final int N = matches.size();
2879        for (int i = 0; i < N; i++) {
2880            final ResolveInfo cur = matches.get(i);
2881            final String packageName = cur.getComponentInfo().packageName;
2882            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2883                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2884                continue;
2885            }
2886
2887            if (best == null || cur.priority > best.priority) {
2888                best = cur;
2889            }
2890        }
2891
2892        if (best != null) {
2893            return best.getComponentInfo().getComponentName();
2894        } else {
2895            throw new RuntimeException("There must be at least one intent filter verifier");
2896        }
2897    }
2898
2899    private @Nullable ComponentName getEphemeralResolverLPr() {
2900        final String[] packageArray =
2901                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2902        if (packageArray.length == 0) {
2903            if (DEBUG_EPHEMERAL) {
2904                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2905            }
2906            return null;
2907        }
2908
2909        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2910        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2911                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2912                UserHandle.USER_SYSTEM);
2913
2914        final int N = resolvers.size();
2915        if (N == 0) {
2916            if (DEBUG_EPHEMERAL) {
2917                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2918            }
2919            return null;
2920        }
2921
2922        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2923        for (int i = 0; i < N; i++) {
2924            final ResolveInfo info = resolvers.get(i);
2925
2926            if (info.serviceInfo == null) {
2927                continue;
2928            }
2929
2930            final String packageName = info.serviceInfo.packageName;
2931            if (!possiblePackages.contains(packageName)) {
2932                if (DEBUG_EPHEMERAL) {
2933                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2934                            + " pkg: " + packageName + ", info:" + info);
2935                }
2936                continue;
2937            }
2938
2939            if (DEBUG_EPHEMERAL) {
2940                Slog.v(TAG, "Ephemeral resolver found;"
2941                        + " pkg: " + packageName + ", info:" + info);
2942            }
2943            return new ComponentName(packageName, info.serviceInfo.name);
2944        }
2945        if (DEBUG_EPHEMERAL) {
2946            Slog.v(TAG, "Ephemeral resolver NOT found");
2947        }
2948        return null;
2949    }
2950
2951    private @Nullable ComponentName getEphemeralInstallerLPr() {
2952        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2953        intent.addCategory(Intent.CATEGORY_DEFAULT);
2954        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2955
2956        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2957                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2958                UserHandle.USER_SYSTEM);
2959        if (matches.size() == 0) {
2960            return null;
2961        } else if (matches.size() == 1) {
2962            return matches.get(0).getComponentInfo().getComponentName();
2963        } else {
2964            throw new RuntimeException(
2965                    "There must be at most one ephemeral installer; found " + matches);
2966        }
2967    }
2968
2969    private void primeDomainVerificationsLPw(int userId) {
2970        if (DEBUG_DOMAIN_VERIFICATION) {
2971            Slog.d(TAG, "Priming domain verifications in user " + userId);
2972        }
2973
2974        SystemConfig systemConfig = SystemConfig.getInstance();
2975        ArraySet<String> packages = systemConfig.getLinkedApps();
2976        ArraySet<String> domains = new ArraySet<String>();
2977
2978        for (String packageName : packages) {
2979            PackageParser.Package pkg = mPackages.get(packageName);
2980            if (pkg != null) {
2981                if (!pkg.isSystemApp()) {
2982                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2983                    continue;
2984                }
2985
2986                domains.clear();
2987                for (PackageParser.Activity a : pkg.activities) {
2988                    for (ActivityIntentInfo filter : a.intents) {
2989                        if (hasValidDomains(filter)) {
2990                            domains.addAll(filter.getHostsList());
2991                        }
2992                    }
2993                }
2994
2995                if (domains.size() > 0) {
2996                    if (DEBUG_DOMAIN_VERIFICATION) {
2997                        Slog.v(TAG, "      + " + packageName);
2998                    }
2999                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3000                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3001                    // and then 'always' in the per-user state actually used for intent resolution.
3002                    final IntentFilterVerificationInfo ivi;
3003                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3004                            new ArrayList<String>(domains));
3005                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3006                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3007                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3008                } else {
3009                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3010                            + "' does not handle web links");
3011                }
3012            } else {
3013                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3014            }
3015        }
3016
3017        scheduleWritePackageRestrictionsLocked(userId);
3018        scheduleWriteSettingsLocked();
3019    }
3020
3021    private void applyFactoryDefaultBrowserLPw(int userId) {
3022        // The default browser app's package name is stored in a string resource,
3023        // with a product-specific overlay used for vendor customization.
3024        String browserPkg = mContext.getResources().getString(
3025                com.android.internal.R.string.default_browser);
3026        if (!TextUtils.isEmpty(browserPkg)) {
3027            // non-empty string => required to be a known package
3028            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3029            if (ps == null) {
3030                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3031                browserPkg = null;
3032            } else {
3033                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3034            }
3035        }
3036
3037        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3038        // default.  If there's more than one, just leave everything alone.
3039        if (browserPkg == null) {
3040            calculateDefaultBrowserLPw(userId);
3041        }
3042    }
3043
3044    private void calculateDefaultBrowserLPw(int userId) {
3045        List<String> allBrowsers = resolveAllBrowserApps(userId);
3046        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3047        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3048    }
3049
3050    private List<String> resolveAllBrowserApps(int userId) {
3051        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3052        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3053                PackageManager.MATCH_ALL, userId);
3054
3055        final int count = list.size();
3056        List<String> result = new ArrayList<String>(count);
3057        for (int i=0; i<count; i++) {
3058            ResolveInfo info = list.get(i);
3059            if (info.activityInfo == null
3060                    || !info.handleAllWebDataURI
3061                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3062                    || result.contains(info.activityInfo.packageName)) {
3063                continue;
3064            }
3065            result.add(info.activityInfo.packageName);
3066        }
3067
3068        return result;
3069    }
3070
3071    private boolean packageIsBrowser(String packageName, int userId) {
3072        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3073                PackageManager.MATCH_ALL, userId);
3074        final int N = list.size();
3075        for (int i = 0; i < N; i++) {
3076            ResolveInfo info = list.get(i);
3077            if (packageName.equals(info.activityInfo.packageName)) {
3078                return true;
3079            }
3080        }
3081        return false;
3082    }
3083
3084    private void checkDefaultBrowser() {
3085        final int myUserId = UserHandle.myUserId();
3086        final String packageName = getDefaultBrowserPackageName(myUserId);
3087        if (packageName != null) {
3088            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3089            if (info == null) {
3090                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3091                synchronized (mPackages) {
3092                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3093                }
3094            }
3095        }
3096    }
3097
3098    @Override
3099    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3100            throws RemoteException {
3101        try {
3102            return super.onTransact(code, data, reply, flags);
3103        } catch (RuntimeException e) {
3104            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3105                Slog.wtf(TAG, "Package Manager Crash", e);
3106            }
3107            throw e;
3108        }
3109    }
3110
3111    static int[] appendInts(int[] cur, int[] add) {
3112        if (add == null) return cur;
3113        if (cur == null) return add;
3114        final int N = add.length;
3115        for (int i=0; i<N; i++) {
3116            cur = appendInt(cur, add[i]);
3117        }
3118        return cur;
3119    }
3120
3121    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3122        if (!sUserManager.exists(userId)) return null;
3123        if (ps == null) {
3124            return null;
3125        }
3126        final PackageParser.Package p = ps.pkg;
3127        if (p == null) {
3128            return null;
3129        }
3130
3131        final PermissionsState permissionsState = ps.getPermissionsState();
3132
3133        final int[] gids = permissionsState.computeGids(userId);
3134        final Set<String> permissions = permissionsState.getPermissions(userId);
3135        final PackageUserState state = ps.readUserState(userId);
3136
3137        return PackageParser.generatePackageInfo(p, gids, flags,
3138                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3139    }
3140
3141    @Override
3142    public void checkPackageStartable(String packageName, int userId) {
3143        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3144
3145        synchronized (mPackages) {
3146            final PackageSetting ps = mSettings.mPackages.get(packageName);
3147            if (ps == null) {
3148                throw new SecurityException("Package " + packageName + " was not found!");
3149            }
3150
3151            if (!ps.getInstalled(userId)) {
3152                throw new SecurityException(
3153                        "Package " + packageName + " was not installed for user " + userId + "!");
3154            }
3155
3156            if (mSafeMode && !ps.isSystem()) {
3157                throw new SecurityException("Package " + packageName + " not a system app!");
3158            }
3159
3160            if (mFrozenPackages.contains(packageName)) {
3161                throw new SecurityException("Package " + packageName + " is currently frozen!");
3162            }
3163
3164            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3165                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3166                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3167            }
3168        }
3169    }
3170
3171    @Override
3172    public boolean isPackageAvailable(String packageName, int userId) {
3173        if (!sUserManager.exists(userId)) return false;
3174        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3175                false /* requireFullPermission */, false /* checkShell */, "is package available");
3176        synchronized (mPackages) {
3177            PackageParser.Package p = mPackages.get(packageName);
3178            if (p != null) {
3179                final PackageSetting ps = (PackageSetting) p.mExtras;
3180                if (ps != null) {
3181                    final PackageUserState state = ps.readUserState(userId);
3182                    if (state != null) {
3183                        return PackageParser.isAvailable(state);
3184                    }
3185                }
3186            }
3187        }
3188        return false;
3189    }
3190
3191    @Override
3192    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3193        if (!sUserManager.exists(userId)) return null;
3194        flags = updateFlagsForPackage(flags, userId, packageName);
3195        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3196                false /* requireFullPermission */, false /* checkShell */, "get package info");
3197        // reader
3198        synchronized (mPackages) {
3199            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3200            PackageParser.Package p = null;
3201            if (matchFactoryOnly) {
3202                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3203                if (ps != null) {
3204                    return generatePackageInfo(ps, flags, userId);
3205                }
3206            }
3207            if (p == null) {
3208                p = mPackages.get(packageName);
3209                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3210                    return null;
3211                }
3212            }
3213            if (DEBUG_PACKAGE_INFO)
3214                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3215            if (p != null) {
3216                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3217            }
3218            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3219                final PackageSetting ps = mSettings.mPackages.get(packageName);
3220                return generatePackageInfo(ps, flags, userId);
3221            }
3222        }
3223        return null;
3224    }
3225
3226    @Override
3227    public String[] currentToCanonicalPackageNames(String[] names) {
3228        String[] out = new String[names.length];
3229        // reader
3230        synchronized (mPackages) {
3231            for (int i=names.length-1; i>=0; i--) {
3232                PackageSetting ps = mSettings.mPackages.get(names[i]);
3233                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3234            }
3235        }
3236        return out;
3237    }
3238
3239    @Override
3240    public String[] canonicalToCurrentPackageNames(String[] names) {
3241        String[] out = new String[names.length];
3242        // reader
3243        synchronized (mPackages) {
3244            for (int i=names.length-1; i>=0; i--) {
3245                String cur = mSettings.mRenamedPackages.get(names[i]);
3246                out[i] = cur != null ? cur : names[i];
3247            }
3248        }
3249        return out;
3250    }
3251
3252    @Override
3253    public int getPackageUid(String packageName, int flags, int userId) {
3254        if (!sUserManager.exists(userId)) return -1;
3255        flags = updateFlagsForPackage(flags, userId, packageName);
3256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3257                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3258
3259        // reader
3260        synchronized (mPackages) {
3261            final PackageParser.Package p = mPackages.get(packageName);
3262            if (p != null && p.isMatch(flags)) {
3263                return UserHandle.getUid(userId, p.applicationInfo.uid);
3264            }
3265            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3266                final PackageSetting ps = mSettings.mPackages.get(packageName);
3267                if (ps != null && ps.isMatch(flags)) {
3268                    return UserHandle.getUid(userId, ps.appId);
3269                }
3270            }
3271        }
3272
3273        return -1;
3274    }
3275
3276    @Override
3277    public int[] getPackageGids(String packageName, int flags, int userId) {
3278        if (!sUserManager.exists(userId)) return null;
3279        flags = updateFlagsForPackage(flags, userId, packageName);
3280        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3281                false /* requireFullPermission */, false /* checkShell */,
3282                "getPackageGids");
3283
3284        // reader
3285        synchronized (mPackages) {
3286            final PackageParser.Package p = mPackages.get(packageName);
3287            if (p != null && p.isMatch(flags)) {
3288                PackageSetting ps = (PackageSetting) p.mExtras;
3289                return ps.getPermissionsState().computeGids(userId);
3290            }
3291            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3292                final PackageSetting ps = mSettings.mPackages.get(packageName);
3293                if (ps != null && ps.isMatch(flags)) {
3294                    return ps.getPermissionsState().computeGids(userId);
3295                }
3296            }
3297        }
3298
3299        return null;
3300    }
3301
3302    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3303        if (bp.perm != null) {
3304            return PackageParser.generatePermissionInfo(bp.perm, flags);
3305        }
3306        PermissionInfo pi = new PermissionInfo();
3307        pi.name = bp.name;
3308        pi.packageName = bp.sourcePackage;
3309        pi.nonLocalizedLabel = bp.name;
3310        pi.protectionLevel = bp.protectionLevel;
3311        return pi;
3312    }
3313
3314    @Override
3315    public PermissionInfo getPermissionInfo(String name, int flags) {
3316        // reader
3317        synchronized (mPackages) {
3318            final BasePermission p = mSettings.mPermissions.get(name);
3319            if (p != null) {
3320                return generatePermissionInfo(p, flags);
3321            }
3322            return null;
3323        }
3324    }
3325
3326    @Override
3327    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3328            int flags) {
3329        // reader
3330        synchronized (mPackages) {
3331            if (group != null && !mPermissionGroups.containsKey(group)) {
3332                // This is thrown as NameNotFoundException
3333                return null;
3334            }
3335
3336            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3337            for (BasePermission p : mSettings.mPermissions.values()) {
3338                if (group == null) {
3339                    if (p.perm == null || p.perm.info.group == null) {
3340                        out.add(generatePermissionInfo(p, flags));
3341                    }
3342                } else {
3343                    if (p.perm != null && group.equals(p.perm.info.group)) {
3344                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3345                    }
3346                }
3347            }
3348            return new ParceledListSlice<>(out);
3349        }
3350    }
3351
3352    @Override
3353    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3354        // reader
3355        synchronized (mPackages) {
3356            return PackageParser.generatePermissionGroupInfo(
3357                    mPermissionGroups.get(name), flags);
3358        }
3359    }
3360
3361    @Override
3362    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3363        // reader
3364        synchronized (mPackages) {
3365            final int N = mPermissionGroups.size();
3366            ArrayList<PermissionGroupInfo> out
3367                    = new ArrayList<PermissionGroupInfo>(N);
3368            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3369                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3370            }
3371            return new ParceledListSlice<>(out);
3372        }
3373    }
3374
3375    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3376            int userId) {
3377        if (!sUserManager.exists(userId)) return null;
3378        PackageSetting ps = mSettings.mPackages.get(packageName);
3379        if (ps != null) {
3380            if (ps.pkg == null) {
3381                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3382                if (pInfo != null) {
3383                    return pInfo.applicationInfo;
3384                }
3385                return null;
3386            }
3387            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3388                    ps.readUserState(userId), userId);
3389        }
3390        return null;
3391    }
3392
3393    @Override
3394    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3395        if (!sUserManager.exists(userId)) return null;
3396        flags = updateFlagsForApplication(flags, userId, packageName);
3397        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3398                false /* requireFullPermission */, false /* checkShell */, "get application info");
3399        // writer
3400        synchronized (mPackages) {
3401            PackageParser.Package p = mPackages.get(packageName);
3402            if (DEBUG_PACKAGE_INFO) Log.v(
3403                    TAG, "getApplicationInfo " + packageName
3404                    + ": " + p);
3405            if (p != null) {
3406                PackageSetting ps = mSettings.mPackages.get(packageName);
3407                if (ps == null) return null;
3408                // Note: isEnabledLP() does not apply here - always return info
3409                return PackageParser.generateApplicationInfo(
3410                        p, flags, ps.readUserState(userId), userId);
3411            }
3412            if ("android".equals(packageName)||"system".equals(packageName)) {
3413                return mAndroidApplication;
3414            }
3415            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3416                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3417            }
3418        }
3419        return null;
3420    }
3421
3422    @Override
3423    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3424            final IPackageDataObserver observer) {
3425        mContext.enforceCallingOrSelfPermission(
3426                android.Manifest.permission.CLEAR_APP_CACHE, null);
3427        // Queue up an async operation since clearing cache may take a little while.
3428        mHandler.post(new Runnable() {
3429            public void run() {
3430                mHandler.removeCallbacks(this);
3431                boolean success = true;
3432                synchronized (mInstallLock) {
3433                    try {
3434                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3435                    } catch (InstallerException e) {
3436                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3437                        success = false;
3438                    }
3439                }
3440                if (observer != null) {
3441                    try {
3442                        observer.onRemoveCompleted(null, success);
3443                    } catch (RemoteException e) {
3444                        Slog.w(TAG, "RemoveException when invoking call back");
3445                    }
3446                }
3447            }
3448        });
3449    }
3450
3451    @Override
3452    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3453            final IntentSender pi) {
3454        mContext.enforceCallingOrSelfPermission(
3455                android.Manifest.permission.CLEAR_APP_CACHE, null);
3456        // Queue up an async operation since clearing cache may take a little while.
3457        mHandler.post(new Runnable() {
3458            public void run() {
3459                mHandler.removeCallbacks(this);
3460                boolean success = true;
3461                synchronized (mInstallLock) {
3462                    try {
3463                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3464                    } catch (InstallerException e) {
3465                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3466                        success = false;
3467                    }
3468                }
3469                if(pi != null) {
3470                    try {
3471                        // Callback via pending intent
3472                        int code = success ? 1 : 0;
3473                        pi.sendIntent(null, code, null,
3474                                null, null);
3475                    } catch (SendIntentException e1) {
3476                        Slog.i(TAG, "Failed to send pending intent");
3477                    }
3478                }
3479            }
3480        });
3481    }
3482
3483    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3484        synchronized (mInstallLock) {
3485            try {
3486                mInstaller.freeCache(volumeUuid, freeStorageSize);
3487            } catch (InstallerException e) {
3488                throw new IOException("Failed to free enough space", e);
3489            }
3490        }
3491    }
3492
3493    /**
3494     * Update given flags based on encryption status of current user.
3495     */
3496    private int updateFlags(int flags, int userId) {
3497        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3498                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3499            // Caller expressed an explicit opinion about what encryption
3500            // aware/unaware components they want to see, so fall through and
3501            // give them what they want
3502        } else {
3503            // Caller expressed no opinion, so match based on user state
3504            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3505                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3506            } else {
3507                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3508            }
3509        }
3510        return flags;
3511    }
3512
3513    private UserManagerInternal getUserManagerInternal() {
3514        if (mUserManagerInternal == null) {
3515            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3516        }
3517        return mUserManagerInternal;
3518    }
3519
3520    /**
3521     * Update given flags when being used to request {@link PackageInfo}.
3522     */
3523    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3524        boolean triaged = true;
3525        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3526                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3527            // Caller is asking for component details, so they'd better be
3528            // asking for specific encryption matching behavior, or be triaged
3529            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3530                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3531                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3532                triaged = false;
3533            }
3534        }
3535        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3536                | PackageManager.MATCH_SYSTEM_ONLY
3537                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3538            triaged = false;
3539        }
3540        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3541            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3542                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3543        }
3544        return updateFlags(flags, userId);
3545    }
3546
3547    /**
3548     * Update given flags when being used to request {@link ApplicationInfo}.
3549     */
3550    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3551        return updateFlagsForPackage(flags, userId, cookie);
3552    }
3553
3554    /**
3555     * Update given flags when being used to request {@link ComponentInfo}.
3556     */
3557    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3558        if (cookie instanceof Intent) {
3559            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3560                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3561            }
3562        }
3563
3564        boolean triaged = true;
3565        // Caller is asking for component details, so they'd better be
3566        // asking for specific encryption matching behavior, or be triaged
3567        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3568                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3569                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3570            triaged = false;
3571        }
3572        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3573            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3574                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3575        }
3576
3577        return updateFlags(flags, userId);
3578    }
3579
3580    /**
3581     * Update given flags when being used to request {@link ResolveInfo}.
3582     */
3583    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3584        // Safe mode means we shouldn't match any third-party components
3585        if (mSafeMode) {
3586            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3587        }
3588
3589        return updateFlagsForComponent(flags, userId, cookie);
3590    }
3591
3592    @Override
3593    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3594        if (!sUserManager.exists(userId)) return null;
3595        flags = updateFlagsForComponent(flags, userId, component);
3596        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3597                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3598        synchronized (mPackages) {
3599            PackageParser.Activity a = mActivities.mActivities.get(component);
3600
3601            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3602            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3603                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3604                if (ps == null) return null;
3605                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3606                        userId);
3607            }
3608            if (mResolveComponentName.equals(component)) {
3609                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3610                        new PackageUserState(), userId);
3611            }
3612        }
3613        return null;
3614    }
3615
3616    @Override
3617    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3618            String resolvedType) {
3619        synchronized (mPackages) {
3620            if (component.equals(mResolveComponentName)) {
3621                // The resolver supports EVERYTHING!
3622                return true;
3623            }
3624            PackageParser.Activity a = mActivities.mActivities.get(component);
3625            if (a == null) {
3626                return false;
3627            }
3628            for (int i=0; i<a.intents.size(); i++) {
3629                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3630                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3631                    return true;
3632                }
3633            }
3634            return false;
3635        }
3636    }
3637
3638    @Override
3639    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3640        if (!sUserManager.exists(userId)) return null;
3641        flags = updateFlagsForComponent(flags, userId, component);
3642        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3643                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3644        synchronized (mPackages) {
3645            PackageParser.Activity a = mReceivers.mActivities.get(component);
3646            if (DEBUG_PACKAGE_INFO) Log.v(
3647                TAG, "getReceiverInfo " + component + ": " + a);
3648            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3649                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3650                if (ps == null) return null;
3651                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3652                        userId);
3653            }
3654        }
3655        return null;
3656    }
3657
3658    @Override
3659    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3660        if (!sUserManager.exists(userId)) return null;
3661        flags = updateFlagsForComponent(flags, userId, component);
3662        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3663                false /* requireFullPermission */, false /* checkShell */, "get service info");
3664        synchronized (mPackages) {
3665            PackageParser.Service s = mServices.mServices.get(component);
3666            if (DEBUG_PACKAGE_INFO) Log.v(
3667                TAG, "getServiceInfo " + component + ": " + s);
3668            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3669                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3670                if (ps == null) return null;
3671                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3672                        userId);
3673            }
3674        }
3675        return null;
3676    }
3677
3678    @Override
3679    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3680        if (!sUserManager.exists(userId)) return null;
3681        flags = updateFlagsForComponent(flags, userId, component);
3682        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3683                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3684        synchronized (mPackages) {
3685            PackageParser.Provider p = mProviders.mProviders.get(component);
3686            if (DEBUG_PACKAGE_INFO) Log.v(
3687                TAG, "getProviderInfo " + component + ": " + p);
3688            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3689                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3690                if (ps == null) return null;
3691                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3692                        userId);
3693            }
3694        }
3695        return null;
3696    }
3697
3698    @Override
3699    public String[] getSystemSharedLibraryNames() {
3700        Set<String> libSet;
3701        synchronized (mPackages) {
3702            libSet = mSharedLibraries.keySet();
3703            int size = libSet.size();
3704            if (size > 0) {
3705                String[] libs = new String[size];
3706                libSet.toArray(libs);
3707                return libs;
3708            }
3709        }
3710        return null;
3711    }
3712
3713    @Override
3714    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3715        synchronized (mPackages) {
3716            return mServicesSystemSharedLibraryPackageName;
3717        }
3718    }
3719
3720    @Override
3721    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3722        synchronized (mPackages) {
3723            return mSharedSystemSharedLibraryPackageName;
3724        }
3725    }
3726
3727    @Override
3728    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3729        synchronized (mPackages) {
3730            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3731
3732            final FeatureInfo fi = new FeatureInfo();
3733            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3734                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3735            res.add(fi);
3736
3737            return new ParceledListSlice<>(res);
3738        }
3739    }
3740
3741    @Override
3742    public boolean hasSystemFeature(String name, int version) {
3743        synchronized (mPackages) {
3744            final FeatureInfo feat = mAvailableFeatures.get(name);
3745            if (feat == null) {
3746                return false;
3747            } else {
3748                return feat.version >= version;
3749            }
3750        }
3751    }
3752
3753    @Override
3754    public int checkPermission(String permName, String pkgName, int userId) {
3755        if (!sUserManager.exists(userId)) {
3756            return PackageManager.PERMISSION_DENIED;
3757        }
3758
3759        synchronized (mPackages) {
3760            final PackageParser.Package p = mPackages.get(pkgName);
3761            if (p != null && p.mExtras != null) {
3762                final PackageSetting ps = (PackageSetting) p.mExtras;
3763                final PermissionsState permissionsState = ps.getPermissionsState();
3764                if (permissionsState.hasPermission(permName, userId)) {
3765                    return PackageManager.PERMISSION_GRANTED;
3766                }
3767                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3768                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3769                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3770                    return PackageManager.PERMISSION_GRANTED;
3771                }
3772            }
3773        }
3774
3775        return PackageManager.PERMISSION_DENIED;
3776    }
3777
3778    @Override
3779    public int checkUidPermission(String permName, int uid) {
3780        final int userId = UserHandle.getUserId(uid);
3781
3782        if (!sUserManager.exists(userId)) {
3783            return PackageManager.PERMISSION_DENIED;
3784        }
3785
3786        synchronized (mPackages) {
3787            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3788            if (obj != null) {
3789                final SettingBase ps = (SettingBase) obj;
3790                final PermissionsState permissionsState = ps.getPermissionsState();
3791                if (permissionsState.hasPermission(permName, userId)) {
3792                    return PackageManager.PERMISSION_GRANTED;
3793                }
3794                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3795                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3796                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3797                    return PackageManager.PERMISSION_GRANTED;
3798                }
3799            } else {
3800                ArraySet<String> perms = mSystemPermissions.get(uid);
3801                if (perms != null) {
3802                    if (perms.contains(permName)) {
3803                        return PackageManager.PERMISSION_GRANTED;
3804                    }
3805                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3806                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3807                        return PackageManager.PERMISSION_GRANTED;
3808                    }
3809                }
3810            }
3811        }
3812
3813        return PackageManager.PERMISSION_DENIED;
3814    }
3815
3816    @Override
3817    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3818        if (UserHandle.getCallingUserId() != userId) {
3819            mContext.enforceCallingPermission(
3820                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3821                    "isPermissionRevokedByPolicy for user " + userId);
3822        }
3823
3824        if (checkPermission(permission, packageName, userId)
3825                == PackageManager.PERMISSION_GRANTED) {
3826            return false;
3827        }
3828
3829        final long identity = Binder.clearCallingIdentity();
3830        try {
3831            final int flags = getPermissionFlags(permission, packageName, userId);
3832            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3833        } finally {
3834            Binder.restoreCallingIdentity(identity);
3835        }
3836    }
3837
3838    @Override
3839    public String getPermissionControllerPackageName() {
3840        synchronized (mPackages) {
3841            return mRequiredInstallerPackage;
3842        }
3843    }
3844
3845    /**
3846     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3847     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3848     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3849     * @param message the message to log on security exception
3850     */
3851    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3852            boolean checkShell, String message) {
3853        if (userId < 0) {
3854            throw new IllegalArgumentException("Invalid userId " + userId);
3855        }
3856        if (checkShell) {
3857            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3858        }
3859        if (userId == UserHandle.getUserId(callingUid)) return;
3860        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3861            if (requireFullPermission) {
3862                mContext.enforceCallingOrSelfPermission(
3863                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3864            } else {
3865                try {
3866                    mContext.enforceCallingOrSelfPermission(
3867                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3868                } catch (SecurityException se) {
3869                    mContext.enforceCallingOrSelfPermission(
3870                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3871                }
3872            }
3873        }
3874    }
3875
3876    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3877        if (callingUid == Process.SHELL_UID) {
3878            if (userHandle >= 0
3879                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3880                throw new SecurityException("Shell does not have permission to access user "
3881                        + userHandle);
3882            } else if (userHandle < 0) {
3883                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3884                        + Debug.getCallers(3));
3885            }
3886        }
3887    }
3888
3889    private BasePermission findPermissionTreeLP(String permName) {
3890        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3891            if (permName.startsWith(bp.name) &&
3892                    permName.length() > bp.name.length() &&
3893                    permName.charAt(bp.name.length()) == '.') {
3894                return bp;
3895            }
3896        }
3897        return null;
3898    }
3899
3900    private BasePermission checkPermissionTreeLP(String permName) {
3901        if (permName != null) {
3902            BasePermission bp = findPermissionTreeLP(permName);
3903            if (bp != null) {
3904                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3905                    return bp;
3906                }
3907                throw new SecurityException("Calling uid "
3908                        + Binder.getCallingUid()
3909                        + " is not allowed to add to permission tree "
3910                        + bp.name + " owned by uid " + bp.uid);
3911            }
3912        }
3913        throw new SecurityException("No permission tree found for " + permName);
3914    }
3915
3916    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3917        if (s1 == null) {
3918            return s2 == null;
3919        }
3920        if (s2 == null) {
3921            return false;
3922        }
3923        if (s1.getClass() != s2.getClass()) {
3924            return false;
3925        }
3926        return s1.equals(s2);
3927    }
3928
3929    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3930        if (pi1.icon != pi2.icon) return false;
3931        if (pi1.logo != pi2.logo) return false;
3932        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3933        if (!compareStrings(pi1.name, pi2.name)) return false;
3934        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3935        // We'll take care of setting this one.
3936        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3937        // These are not currently stored in settings.
3938        //if (!compareStrings(pi1.group, pi2.group)) return false;
3939        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3940        //if (pi1.labelRes != pi2.labelRes) return false;
3941        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3942        return true;
3943    }
3944
3945    int permissionInfoFootprint(PermissionInfo info) {
3946        int size = info.name.length();
3947        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3948        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3949        return size;
3950    }
3951
3952    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3953        int size = 0;
3954        for (BasePermission perm : mSettings.mPermissions.values()) {
3955            if (perm.uid == tree.uid) {
3956                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3957            }
3958        }
3959        return size;
3960    }
3961
3962    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3963        // We calculate the max size of permissions defined by this uid and throw
3964        // if that plus the size of 'info' would exceed our stated maximum.
3965        if (tree.uid != Process.SYSTEM_UID) {
3966            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3967            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3968                throw new SecurityException("Permission tree size cap exceeded");
3969            }
3970        }
3971    }
3972
3973    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3974        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3975            throw new SecurityException("Label must be specified in permission");
3976        }
3977        BasePermission tree = checkPermissionTreeLP(info.name);
3978        BasePermission bp = mSettings.mPermissions.get(info.name);
3979        boolean added = bp == null;
3980        boolean changed = true;
3981        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3982        if (added) {
3983            enforcePermissionCapLocked(info, tree);
3984            bp = new BasePermission(info.name, tree.sourcePackage,
3985                    BasePermission.TYPE_DYNAMIC);
3986        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3987            throw new SecurityException(
3988                    "Not allowed to modify non-dynamic permission "
3989                    + info.name);
3990        } else {
3991            if (bp.protectionLevel == fixedLevel
3992                    && bp.perm.owner.equals(tree.perm.owner)
3993                    && bp.uid == tree.uid
3994                    && comparePermissionInfos(bp.perm.info, info)) {
3995                changed = false;
3996            }
3997        }
3998        bp.protectionLevel = fixedLevel;
3999        info = new PermissionInfo(info);
4000        info.protectionLevel = fixedLevel;
4001        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4002        bp.perm.info.packageName = tree.perm.info.packageName;
4003        bp.uid = tree.uid;
4004        if (added) {
4005            mSettings.mPermissions.put(info.name, bp);
4006        }
4007        if (changed) {
4008            if (!async) {
4009                mSettings.writeLPr();
4010            } else {
4011                scheduleWriteSettingsLocked();
4012            }
4013        }
4014        return added;
4015    }
4016
4017    @Override
4018    public boolean addPermission(PermissionInfo info) {
4019        synchronized (mPackages) {
4020            return addPermissionLocked(info, false);
4021        }
4022    }
4023
4024    @Override
4025    public boolean addPermissionAsync(PermissionInfo info) {
4026        synchronized (mPackages) {
4027            return addPermissionLocked(info, true);
4028        }
4029    }
4030
4031    @Override
4032    public void removePermission(String name) {
4033        synchronized (mPackages) {
4034            checkPermissionTreeLP(name);
4035            BasePermission bp = mSettings.mPermissions.get(name);
4036            if (bp != null) {
4037                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4038                    throw new SecurityException(
4039                            "Not allowed to modify non-dynamic permission "
4040                            + name);
4041                }
4042                mSettings.mPermissions.remove(name);
4043                mSettings.writeLPr();
4044            }
4045        }
4046    }
4047
4048    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4049            BasePermission bp) {
4050        int index = pkg.requestedPermissions.indexOf(bp.name);
4051        if (index == -1) {
4052            throw new SecurityException("Package " + pkg.packageName
4053                    + " has not requested permission " + bp.name);
4054        }
4055        if (!bp.isRuntime() && !bp.isDevelopment()) {
4056            throw new SecurityException("Permission " + bp.name
4057                    + " is not a changeable permission type");
4058        }
4059    }
4060
4061    @Override
4062    public void grantRuntimePermission(String packageName, String name, final int userId) {
4063        if (!sUserManager.exists(userId)) {
4064            Log.e(TAG, "No such user:" + userId);
4065            return;
4066        }
4067
4068        mContext.enforceCallingOrSelfPermission(
4069                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4070                "grantRuntimePermission");
4071
4072        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4073                true /* requireFullPermission */, true /* checkShell */,
4074                "grantRuntimePermission");
4075
4076        final int uid;
4077        final SettingBase sb;
4078
4079        synchronized (mPackages) {
4080            final PackageParser.Package pkg = mPackages.get(packageName);
4081            if (pkg == null) {
4082                throw new IllegalArgumentException("Unknown package: " + packageName);
4083            }
4084
4085            final BasePermission bp = mSettings.mPermissions.get(name);
4086            if (bp == null) {
4087                throw new IllegalArgumentException("Unknown permission: " + name);
4088            }
4089
4090            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4091
4092            // If a permission review is required for legacy apps we represent
4093            // their permissions as always granted runtime ones since we need
4094            // to keep the review required permission flag per user while an
4095            // install permission's state is shared across all users.
4096            if (Build.PERMISSIONS_REVIEW_REQUIRED
4097                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4098                    && bp.isRuntime()) {
4099                return;
4100            }
4101
4102            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4103            sb = (SettingBase) pkg.mExtras;
4104            if (sb == null) {
4105                throw new IllegalArgumentException("Unknown package: " + packageName);
4106            }
4107
4108            final PermissionsState permissionsState = sb.getPermissionsState();
4109
4110            final int flags = permissionsState.getPermissionFlags(name, userId);
4111            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4112                throw new SecurityException("Cannot grant system fixed permission "
4113                        + name + " for package " + packageName);
4114            }
4115
4116            if (bp.isDevelopment()) {
4117                // Development permissions must be handled specially, since they are not
4118                // normal runtime permissions.  For now they apply to all users.
4119                if (permissionsState.grantInstallPermission(bp) !=
4120                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4121                    scheduleWriteSettingsLocked();
4122                }
4123                return;
4124            }
4125
4126            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4127                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4128                return;
4129            }
4130
4131            final int result = permissionsState.grantRuntimePermission(bp, userId);
4132            switch (result) {
4133                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4134                    return;
4135                }
4136
4137                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4138                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4139                    mHandler.post(new Runnable() {
4140                        @Override
4141                        public void run() {
4142                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4143                        }
4144                    });
4145                }
4146                break;
4147            }
4148
4149            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4150
4151            // Not critical if that is lost - app has to request again.
4152            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4153        }
4154
4155        // Only need to do this if user is initialized. Otherwise it's a new user
4156        // and there are no processes running as the user yet and there's no need
4157        // to make an expensive call to remount processes for the changed permissions.
4158        if (READ_EXTERNAL_STORAGE.equals(name)
4159                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4160            final long token = Binder.clearCallingIdentity();
4161            try {
4162                if (sUserManager.isInitialized(userId)) {
4163                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4164                            MountServiceInternal.class);
4165                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4166                }
4167            } finally {
4168                Binder.restoreCallingIdentity(token);
4169            }
4170        }
4171    }
4172
4173    @Override
4174    public void revokeRuntimePermission(String packageName, String name, int userId) {
4175        if (!sUserManager.exists(userId)) {
4176            Log.e(TAG, "No such user:" + userId);
4177            return;
4178        }
4179
4180        mContext.enforceCallingOrSelfPermission(
4181                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4182                "revokeRuntimePermission");
4183
4184        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4185                true /* requireFullPermission */, true /* checkShell */,
4186                "revokeRuntimePermission");
4187
4188        final int appId;
4189
4190        synchronized (mPackages) {
4191            final PackageParser.Package pkg = mPackages.get(packageName);
4192            if (pkg == null) {
4193                throw new IllegalArgumentException("Unknown package: " + packageName);
4194            }
4195
4196            final BasePermission bp = mSettings.mPermissions.get(name);
4197            if (bp == null) {
4198                throw new IllegalArgumentException("Unknown permission: " + name);
4199            }
4200
4201            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4202
4203            // If a permission review is required for legacy apps we represent
4204            // their permissions as always granted runtime ones since we need
4205            // to keep the review required permission flag per user while an
4206            // install permission's state is shared across all users.
4207            if (Build.PERMISSIONS_REVIEW_REQUIRED
4208                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4209                    && bp.isRuntime()) {
4210                return;
4211            }
4212
4213            SettingBase sb = (SettingBase) pkg.mExtras;
4214            if (sb == null) {
4215                throw new IllegalArgumentException("Unknown package: " + packageName);
4216            }
4217
4218            final PermissionsState permissionsState = sb.getPermissionsState();
4219
4220            final int flags = permissionsState.getPermissionFlags(name, userId);
4221            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4222                throw new SecurityException("Cannot revoke system fixed permission "
4223                        + name + " for package " + packageName);
4224            }
4225
4226            if (bp.isDevelopment()) {
4227                // Development permissions must be handled specially, since they are not
4228                // normal runtime permissions.  For now they apply to all users.
4229                if (permissionsState.revokeInstallPermission(bp) !=
4230                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4231                    scheduleWriteSettingsLocked();
4232                }
4233                return;
4234            }
4235
4236            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4237                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4238                return;
4239            }
4240
4241            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4242
4243            // Critical, after this call app should never have the permission.
4244            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4245
4246            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4247        }
4248
4249        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4250    }
4251
4252    @Override
4253    public void resetRuntimePermissions() {
4254        mContext.enforceCallingOrSelfPermission(
4255                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4256                "revokeRuntimePermission");
4257
4258        int callingUid = Binder.getCallingUid();
4259        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4260            mContext.enforceCallingOrSelfPermission(
4261                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4262                    "resetRuntimePermissions");
4263        }
4264
4265        synchronized (mPackages) {
4266            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4267            for (int userId : UserManagerService.getInstance().getUserIds()) {
4268                final int packageCount = mPackages.size();
4269                for (int i = 0; i < packageCount; i++) {
4270                    PackageParser.Package pkg = mPackages.valueAt(i);
4271                    if (!(pkg.mExtras instanceof PackageSetting)) {
4272                        continue;
4273                    }
4274                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4275                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4276                }
4277            }
4278        }
4279    }
4280
4281    @Override
4282    public int getPermissionFlags(String name, String packageName, int userId) {
4283        if (!sUserManager.exists(userId)) {
4284            return 0;
4285        }
4286
4287        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4288
4289        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4290                true /* requireFullPermission */, false /* checkShell */,
4291                "getPermissionFlags");
4292
4293        synchronized (mPackages) {
4294            final PackageParser.Package pkg = mPackages.get(packageName);
4295            if (pkg == null) {
4296                return 0;
4297            }
4298
4299            final BasePermission bp = mSettings.mPermissions.get(name);
4300            if (bp == null) {
4301                return 0;
4302            }
4303
4304            SettingBase sb = (SettingBase) pkg.mExtras;
4305            if (sb == null) {
4306                return 0;
4307            }
4308
4309            PermissionsState permissionsState = sb.getPermissionsState();
4310            return permissionsState.getPermissionFlags(name, userId);
4311        }
4312    }
4313
4314    @Override
4315    public void updatePermissionFlags(String name, String packageName, int flagMask,
4316            int flagValues, int userId) {
4317        if (!sUserManager.exists(userId)) {
4318            return;
4319        }
4320
4321        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4322
4323        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4324                true /* requireFullPermission */, true /* checkShell */,
4325                "updatePermissionFlags");
4326
4327        // Only the system can change these flags and nothing else.
4328        if (getCallingUid() != Process.SYSTEM_UID) {
4329            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4330            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4331            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4332            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4333            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4334        }
4335
4336        synchronized (mPackages) {
4337            final PackageParser.Package pkg = mPackages.get(packageName);
4338            if (pkg == null) {
4339                throw new IllegalArgumentException("Unknown package: " + packageName);
4340            }
4341
4342            final BasePermission bp = mSettings.mPermissions.get(name);
4343            if (bp == null) {
4344                throw new IllegalArgumentException("Unknown permission: " + name);
4345            }
4346
4347            SettingBase sb = (SettingBase) pkg.mExtras;
4348            if (sb == null) {
4349                throw new IllegalArgumentException("Unknown package: " + packageName);
4350            }
4351
4352            PermissionsState permissionsState = sb.getPermissionsState();
4353
4354            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4355
4356            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4357                // Install and runtime permissions are stored in different places,
4358                // so figure out what permission changed and persist the change.
4359                if (permissionsState.getInstallPermissionState(name) != null) {
4360                    scheduleWriteSettingsLocked();
4361                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4362                        || hadState) {
4363                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4364                }
4365            }
4366        }
4367    }
4368
4369    /**
4370     * Update the permission flags for all packages and runtime permissions of a user in order
4371     * to allow device or profile owner to remove POLICY_FIXED.
4372     */
4373    @Override
4374    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4375        if (!sUserManager.exists(userId)) {
4376            return;
4377        }
4378
4379        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4380
4381        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4382                true /* requireFullPermission */, true /* checkShell */,
4383                "updatePermissionFlagsForAllApps");
4384
4385        // Only the system can change system fixed flags.
4386        if (getCallingUid() != Process.SYSTEM_UID) {
4387            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4388            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4389        }
4390
4391        synchronized (mPackages) {
4392            boolean changed = false;
4393            final int packageCount = mPackages.size();
4394            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4395                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4396                SettingBase sb = (SettingBase) pkg.mExtras;
4397                if (sb == null) {
4398                    continue;
4399                }
4400                PermissionsState permissionsState = sb.getPermissionsState();
4401                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4402                        userId, flagMask, flagValues);
4403            }
4404            if (changed) {
4405                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4406            }
4407        }
4408    }
4409
4410    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4411        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4412                != PackageManager.PERMISSION_GRANTED
4413            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4414                != PackageManager.PERMISSION_GRANTED) {
4415            throw new SecurityException(message + " requires "
4416                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4417                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4418        }
4419    }
4420
4421    @Override
4422    public boolean shouldShowRequestPermissionRationale(String permissionName,
4423            String packageName, int userId) {
4424        if (UserHandle.getCallingUserId() != userId) {
4425            mContext.enforceCallingPermission(
4426                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4427                    "canShowRequestPermissionRationale for user " + userId);
4428        }
4429
4430        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4431        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4432            return false;
4433        }
4434
4435        if (checkPermission(permissionName, packageName, userId)
4436                == PackageManager.PERMISSION_GRANTED) {
4437            return false;
4438        }
4439
4440        final int flags;
4441
4442        final long identity = Binder.clearCallingIdentity();
4443        try {
4444            flags = getPermissionFlags(permissionName,
4445                    packageName, userId);
4446        } finally {
4447            Binder.restoreCallingIdentity(identity);
4448        }
4449
4450        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4451                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4452                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4453
4454        if ((flags & fixedFlags) != 0) {
4455            return false;
4456        }
4457
4458        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4459    }
4460
4461    @Override
4462    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4463        mContext.enforceCallingOrSelfPermission(
4464                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4465                "addOnPermissionsChangeListener");
4466
4467        synchronized (mPackages) {
4468            mOnPermissionChangeListeners.addListenerLocked(listener);
4469        }
4470    }
4471
4472    @Override
4473    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4474        synchronized (mPackages) {
4475            mOnPermissionChangeListeners.removeListenerLocked(listener);
4476        }
4477    }
4478
4479    @Override
4480    public boolean isProtectedBroadcast(String actionName) {
4481        synchronized (mPackages) {
4482            if (mProtectedBroadcasts.contains(actionName)) {
4483                return true;
4484            } else if (actionName != null) {
4485                // TODO: remove these terrible hacks
4486                if (actionName.startsWith("android.net.netmon.lingerExpired")
4487                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4488                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4489                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4490                    return true;
4491                }
4492            }
4493        }
4494        return false;
4495    }
4496
4497    @Override
4498    public int checkSignatures(String pkg1, String pkg2) {
4499        synchronized (mPackages) {
4500            final PackageParser.Package p1 = mPackages.get(pkg1);
4501            final PackageParser.Package p2 = mPackages.get(pkg2);
4502            if (p1 == null || p1.mExtras == null
4503                    || p2 == null || p2.mExtras == null) {
4504                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4505            }
4506            return compareSignatures(p1.mSignatures, p2.mSignatures);
4507        }
4508    }
4509
4510    @Override
4511    public int checkUidSignatures(int uid1, int uid2) {
4512        // Map to base uids.
4513        uid1 = UserHandle.getAppId(uid1);
4514        uid2 = UserHandle.getAppId(uid2);
4515        // reader
4516        synchronized (mPackages) {
4517            Signature[] s1;
4518            Signature[] s2;
4519            Object obj = mSettings.getUserIdLPr(uid1);
4520            if (obj != null) {
4521                if (obj instanceof SharedUserSetting) {
4522                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4523                } else if (obj instanceof PackageSetting) {
4524                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4525                } else {
4526                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4527                }
4528            } else {
4529                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4530            }
4531            obj = mSettings.getUserIdLPr(uid2);
4532            if (obj != null) {
4533                if (obj instanceof SharedUserSetting) {
4534                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4535                } else if (obj instanceof PackageSetting) {
4536                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4537                } else {
4538                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4539                }
4540            } else {
4541                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4542            }
4543            return compareSignatures(s1, s2);
4544        }
4545    }
4546
4547    /**
4548     * This method should typically only be used when granting or revoking
4549     * permissions, since the app may immediately restart after this call.
4550     * <p>
4551     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4552     * guard your work against the app being relaunched.
4553     */
4554    private void killUid(int appId, int userId, String reason) {
4555        final long identity = Binder.clearCallingIdentity();
4556        try {
4557            IActivityManager am = ActivityManagerNative.getDefault();
4558            if (am != null) {
4559                try {
4560                    am.killUid(appId, userId, reason);
4561                } catch (RemoteException e) {
4562                    /* ignore - same process */
4563                }
4564            }
4565        } finally {
4566            Binder.restoreCallingIdentity(identity);
4567        }
4568    }
4569
4570    /**
4571     * Compares two sets of signatures. Returns:
4572     * <br />
4573     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4574     * <br />
4575     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4576     * <br />
4577     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4578     * <br />
4579     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4580     * <br />
4581     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4582     */
4583    static int compareSignatures(Signature[] s1, Signature[] s2) {
4584        if (s1 == null) {
4585            return s2 == null
4586                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4587                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4588        }
4589
4590        if (s2 == null) {
4591            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4592        }
4593
4594        if (s1.length != s2.length) {
4595            return PackageManager.SIGNATURE_NO_MATCH;
4596        }
4597
4598        // Since both signature sets are of size 1, we can compare without HashSets.
4599        if (s1.length == 1) {
4600            return s1[0].equals(s2[0]) ?
4601                    PackageManager.SIGNATURE_MATCH :
4602                    PackageManager.SIGNATURE_NO_MATCH;
4603        }
4604
4605        ArraySet<Signature> set1 = new ArraySet<Signature>();
4606        for (Signature sig : s1) {
4607            set1.add(sig);
4608        }
4609        ArraySet<Signature> set2 = new ArraySet<Signature>();
4610        for (Signature sig : s2) {
4611            set2.add(sig);
4612        }
4613        // Make sure s2 contains all signatures in s1.
4614        if (set1.equals(set2)) {
4615            return PackageManager.SIGNATURE_MATCH;
4616        }
4617        return PackageManager.SIGNATURE_NO_MATCH;
4618    }
4619
4620    /**
4621     * If the database version for this type of package (internal storage or
4622     * external storage) is less than the version where package signatures
4623     * were updated, return true.
4624     */
4625    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4626        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4627        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4628    }
4629
4630    /**
4631     * Used for backward compatibility to make sure any packages with
4632     * certificate chains get upgraded to the new style. {@code existingSigs}
4633     * will be in the old format (since they were stored on disk from before the
4634     * system upgrade) and {@code scannedSigs} will be in the newer format.
4635     */
4636    private int compareSignaturesCompat(PackageSignatures existingSigs,
4637            PackageParser.Package scannedPkg) {
4638        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4639            return PackageManager.SIGNATURE_NO_MATCH;
4640        }
4641
4642        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4643        for (Signature sig : existingSigs.mSignatures) {
4644            existingSet.add(sig);
4645        }
4646        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4647        for (Signature sig : scannedPkg.mSignatures) {
4648            try {
4649                Signature[] chainSignatures = sig.getChainSignatures();
4650                for (Signature chainSig : chainSignatures) {
4651                    scannedCompatSet.add(chainSig);
4652                }
4653            } catch (CertificateEncodingException e) {
4654                scannedCompatSet.add(sig);
4655            }
4656        }
4657        /*
4658         * Make sure the expanded scanned set contains all signatures in the
4659         * existing one.
4660         */
4661        if (scannedCompatSet.equals(existingSet)) {
4662            // Migrate the old signatures to the new scheme.
4663            existingSigs.assignSignatures(scannedPkg.mSignatures);
4664            // The new KeySets will be re-added later in the scanning process.
4665            synchronized (mPackages) {
4666                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4667            }
4668            return PackageManager.SIGNATURE_MATCH;
4669        }
4670        return PackageManager.SIGNATURE_NO_MATCH;
4671    }
4672
4673    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4674        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4675        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4676    }
4677
4678    private int compareSignaturesRecover(PackageSignatures existingSigs,
4679            PackageParser.Package scannedPkg) {
4680        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4681            return PackageManager.SIGNATURE_NO_MATCH;
4682        }
4683
4684        String msg = null;
4685        try {
4686            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4687                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4688                        + scannedPkg.packageName);
4689                return PackageManager.SIGNATURE_MATCH;
4690            }
4691        } catch (CertificateException e) {
4692            msg = e.getMessage();
4693        }
4694
4695        logCriticalInfo(Log.INFO,
4696                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4697        return PackageManager.SIGNATURE_NO_MATCH;
4698    }
4699
4700    @Override
4701    public List<String> getAllPackages() {
4702        synchronized (mPackages) {
4703            return new ArrayList<String>(mPackages.keySet());
4704        }
4705    }
4706
4707    @Override
4708    public String[] getPackagesForUid(int uid) {
4709        uid = UserHandle.getAppId(uid);
4710        // reader
4711        synchronized (mPackages) {
4712            Object obj = mSettings.getUserIdLPr(uid);
4713            if (obj instanceof SharedUserSetting) {
4714                final SharedUserSetting sus = (SharedUserSetting) obj;
4715                final int N = sus.packages.size();
4716                final String[] res = new String[N];
4717                final Iterator<PackageSetting> it = sus.packages.iterator();
4718                int i = 0;
4719                while (it.hasNext()) {
4720                    res[i++] = it.next().name;
4721                }
4722                return res;
4723            } else if (obj instanceof PackageSetting) {
4724                final PackageSetting ps = (PackageSetting) obj;
4725                return new String[] { ps.name };
4726            }
4727        }
4728        return null;
4729    }
4730
4731    @Override
4732    public String getNameForUid(int uid) {
4733        // reader
4734        synchronized (mPackages) {
4735            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4736            if (obj instanceof SharedUserSetting) {
4737                final SharedUserSetting sus = (SharedUserSetting) obj;
4738                return sus.name + ":" + sus.userId;
4739            } else if (obj instanceof PackageSetting) {
4740                final PackageSetting ps = (PackageSetting) obj;
4741                return ps.name;
4742            }
4743        }
4744        return null;
4745    }
4746
4747    @Override
4748    public int getUidForSharedUser(String sharedUserName) {
4749        if(sharedUserName == null) {
4750            return -1;
4751        }
4752        // reader
4753        synchronized (mPackages) {
4754            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4755            if (suid == null) {
4756                return -1;
4757            }
4758            return suid.userId;
4759        }
4760    }
4761
4762    @Override
4763    public int getFlagsForUid(int uid) {
4764        synchronized (mPackages) {
4765            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4766            if (obj instanceof SharedUserSetting) {
4767                final SharedUserSetting sus = (SharedUserSetting) obj;
4768                return sus.pkgFlags;
4769            } else if (obj instanceof PackageSetting) {
4770                final PackageSetting ps = (PackageSetting) obj;
4771                return ps.pkgFlags;
4772            }
4773        }
4774        return 0;
4775    }
4776
4777    @Override
4778    public int getPrivateFlagsForUid(int uid) {
4779        synchronized (mPackages) {
4780            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4781            if (obj instanceof SharedUserSetting) {
4782                final SharedUserSetting sus = (SharedUserSetting) obj;
4783                return sus.pkgPrivateFlags;
4784            } else if (obj instanceof PackageSetting) {
4785                final PackageSetting ps = (PackageSetting) obj;
4786                return ps.pkgPrivateFlags;
4787            }
4788        }
4789        return 0;
4790    }
4791
4792    @Override
4793    public boolean isUidPrivileged(int uid) {
4794        uid = UserHandle.getAppId(uid);
4795        // reader
4796        synchronized (mPackages) {
4797            Object obj = mSettings.getUserIdLPr(uid);
4798            if (obj instanceof SharedUserSetting) {
4799                final SharedUserSetting sus = (SharedUserSetting) obj;
4800                final Iterator<PackageSetting> it = sus.packages.iterator();
4801                while (it.hasNext()) {
4802                    if (it.next().isPrivileged()) {
4803                        return true;
4804                    }
4805                }
4806            } else if (obj instanceof PackageSetting) {
4807                final PackageSetting ps = (PackageSetting) obj;
4808                return ps.isPrivileged();
4809            }
4810        }
4811        return false;
4812    }
4813
4814    @Override
4815    public String[] getAppOpPermissionPackages(String permissionName) {
4816        synchronized (mPackages) {
4817            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4818            if (pkgs == null) {
4819                return null;
4820            }
4821            return pkgs.toArray(new String[pkgs.size()]);
4822        }
4823    }
4824
4825    @Override
4826    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4827            int flags, int userId) {
4828        try {
4829            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4830
4831            if (!sUserManager.exists(userId)) return null;
4832            flags = updateFlagsForResolve(flags, userId, intent);
4833            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4834                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4835
4836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4837            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4838                    flags, userId);
4839            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4840
4841            final ResolveInfo bestChoice =
4842                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4843
4844            if (isEphemeralAllowed(intent, query, userId)) {
4845                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4846                final EphemeralResolveInfo ai =
4847                        getEphemeralResolveInfo(intent, resolvedType, userId);
4848                if (ai != null) {
4849                    if (DEBUG_EPHEMERAL) {
4850                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4851                    }
4852                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4853                    bestChoice.ephemeralResolveInfo = ai;
4854                }
4855                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4856            }
4857            return bestChoice;
4858        } finally {
4859            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4860        }
4861    }
4862
4863    @Override
4864    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4865            IntentFilter filter, int match, ComponentName activity) {
4866        final int userId = UserHandle.getCallingUserId();
4867        if (DEBUG_PREFERRED) {
4868            Log.v(TAG, "setLastChosenActivity intent=" + intent
4869                + " resolvedType=" + resolvedType
4870                + " flags=" + flags
4871                + " filter=" + filter
4872                + " match=" + match
4873                + " activity=" + activity);
4874            filter.dump(new PrintStreamPrinter(System.out), "    ");
4875        }
4876        intent.setComponent(null);
4877        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4878                userId);
4879        // Find any earlier preferred or last chosen entries and nuke them
4880        findPreferredActivity(intent, resolvedType,
4881                flags, query, 0, false, true, false, userId);
4882        // Add the new activity as the last chosen for this filter
4883        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4884                "Setting last chosen");
4885    }
4886
4887    @Override
4888    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4889        final int userId = UserHandle.getCallingUserId();
4890        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4891        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4892                userId);
4893        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4894                false, false, false, userId);
4895    }
4896
4897
4898    private boolean isEphemeralAllowed(
4899            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4900        // Short circuit and return early if possible.
4901        if (DISABLE_EPHEMERAL_APPS) {
4902            return false;
4903        }
4904        final int callingUser = UserHandle.getCallingUserId();
4905        if (callingUser != UserHandle.USER_SYSTEM) {
4906            return false;
4907        }
4908        if (mEphemeralResolverConnection == null) {
4909            return false;
4910        }
4911        if (intent.getComponent() != null) {
4912            return false;
4913        }
4914        if (intent.getPackage() != null) {
4915            return false;
4916        }
4917        final boolean isWebUri = hasWebURI(intent);
4918        if (!isWebUri) {
4919            return false;
4920        }
4921        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4922        synchronized (mPackages) {
4923            final int count = resolvedActivites.size();
4924            for (int n = 0; n < count; n++) {
4925                ResolveInfo info = resolvedActivites.get(n);
4926                String packageName = info.activityInfo.packageName;
4927                PackageSetting ps = mSettings.mPackages.get(packageName);
4928                if (ps != null) {
4929                    // Try to get the status from User settings first
4930                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4931                    int status = (int) (packedStatus >> 32);
4932                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4933                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4934                        if (DEBUG_EPHEMERAL) {
4935                            Slog.v(TAG, "DENY ephemeral apps;"
4936                                + " pkg: " + packageName + ", status: " + status);
4937                        }
4938                        return false;
4939                    }
4940                }
4941            }
4942        }
4943        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4944        return true;
4945    }
4946
4947    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4948            int userId) {
4949        MessageDigest digest = null;
4950        try {
4951            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4952        } catch (NoSuchAlgorithmException e) {
4953            // If we can't create a digest, ignore ephemeral apps.
4954            return null;
4955        }
4956
4957        final byte[] hostBytes = intent.getData().getHost().getBytes();
4958        final byte[] digestBytes = digest.digest(hostBytes);
4959        int shaPrefix =
4960                digestBytes[0] << 24
4961                | digestBytes[1] << 16
4962                | digestBytes[2] << 8
4963                | digestBytes[3] << 0;
4964        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4965                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4966        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4967            // No hash prefix match; there are no ephemeral apps for this domain.
4968            return null;
4969        }
4970        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4971            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4972            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4973                continue;
4974            }
4975            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4976            // No filters; this should never happen.
4977            if (filters.isEmpty()) {
4978                continue;
4979            }
4980            // We have a domain match; resolve the filters to see if anything matches.
4981            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4982            for (int j = filters.size() - 1; j >= 0; --j) {
4983                final EphemeralResolveIntentInfo intentInfo =
4984                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4985                ephemeralResolver.addFilter(intentInfo);
4986            }
4987            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4988                    intent, resolvedType, false /*defaultOnly*/, userId);
4989            if (!matchedResolveInfoList.isEmpty()) {
4990                return matchedResolveInfoList.get(0);
4991            }
4992        }
4993        // Hash or filter mis-match; no ephemeral apps for this domain.
4994        return null;
4995    }
4996
4997    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4998            int flags, List<ResolveInfo> query, int userId) {
4999        if (query != null) {
5000            final int N = query.size();
5001            if (N == 1) {
5002                return query.get(0);
5003            } else if (N > 1) {
5004                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5005                // If there is more than one activity with the same priority,
5006                // then let the user decide between them.
5007                ResolveInfo r0 = query.get(0);
5008                ResolveInfo r1 = query.get(1);
5009                if (DEBUG_INTENT_MATCHING || debug) {
5010                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5011                            + r1.activityInfo.name + "=" + r1.priority);
5012                }
5013                // If the first activity has a higher priority, or a different
5014                // default, then it is always desirable to pick it.
5015                if (r0.priority != r1.priority
5016                        || r0.preferredOrder != r1.preferredOrder
5017                        || r0.isDefault != r1.isDefault) {
5018                    return query.get(0);
5019                }
5020                // If we have saved a preference for a preferred activity for
5021                // this Intent, use that.
5022                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5023                        flags, query, r0.priority, true, false, debug, userId);
5024                if (ri != null) {
5025                    return ri;
5026                }
5027                ri = new ResolveInfo(mResolveInfo);
5028                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5029                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5030                // If all of the options come from the same package, show the application's
5031                // label and icon instead of the generic resolver's.
5032                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5033                // and then throw away the ResolveInfo itself, meaning that the caller loses
5034                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5035                // a fallback for this case; we only set the target package's resources on
5036                // the ResolveInfo, not the ActivityInfo.
5037                final String intentPackage = intent.getPackage();
5038                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5039                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5040                    ri.resolvePackageName = intentPackage;
5041                    if (userNeedsBadging(userId)) {
5042                        ri.noResourceId = true;
5043                    } else {
5044                        ri.icon = appi.icon;
5045                    }
5046                    ri.iconResourceId = appi.icon;
5047                    ri.labelRes = appi.labelRes;
5048                }
5049                ri.activityInfo.applicationInfo = new ApplicationInfo(
5050                        ri.activityInfo.applicationInfo);
5051                if (userId != 0) {
5052                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5053                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5054                }
5055                // Make sure that the resolver is displayable in car mode
5056                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5057                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5058                return ri;
5059            }
5060        }
5061        return null;
5062    }
5063
5064    /**
5065     * Return true if the given list is not empty and all of its contents have
5066     * an activityInfo with the given package name.
5067     */
5068    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5069        if (ArrayUtils.isEmpty(list)) {
5070            return false;
5071        }
5072        for (int i = 0, N = list.size(); i < N; i++) {
5073            final ResolveInfo ri = list.get(i);
5074            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5075            if (ai == null || !packageName.equals(ai.packageName)) {
5076                return false;
5077            }
5078        }
5079        return true;
5080    }
5081
5082    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5083            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5084        final int N = query.size();
5085        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5086                .get(userId);
5087        // Get the list of persistent preferred activities that handle the intent
5088        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5089        List<PersistentPreferredActivity> pprefs = ppir != null
5090                ? ppir.queryIntent(intent, resolvedType,
5091                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5092                : null;
5093        if (pprefs != null && pprefs.size() > 0) {
5094            final int M = pprefs.size();
5095            for (int i=0; i<M; i++) {
5096                final PersistentPreferredActivity ppa = pprefs.get(i);
5097                if (DEBUG_PREFERRED || debug) {
5098                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5099                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5100                            + "\n  component=" + ppa.mComponent);
5101                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5102                }
5103                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5104                        flags | MATCH_DISABLED_COMPONENTS, userId);
5105                if (DEBUG_PREFERRED || debug) {
5106                    Slog.v(TAG, "Found persistent preferred activity:");
5107                    if (ai != null) {
5108                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5109                    } else {
5110                        Slog.v(TAG, "  null");
5111                    }
5112                }
5113                if (ai == null) {
5114                    // This previously registered persistent preferred activity
5115                    // component is no longer known. Ignore it and do NOT remove it.
5116                    continue;
5117                }
5118                for (int j=0; j<N; j++) {
5119                    final ResolveInfo ri = query.get(j);
5120                    if (!ri.activityInfo.applicationInfo.packageName
5121                            .equals(ai.applicationInfo.packageName)) {
5122                        continue;
5123                    }
5124                    if (!ri.activityInfo.name.equals(ai.name)) {
5125                        continue;
5126                    }
5127                    //  Found a persistent preference that can handle the intent.
5128                    if (DEBUG_PREFERRED || debug) {
5129                        Slog.v(TAG, "Returning persistent preferred activity: " +
5130                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5131                    }
5132                    return ri;
5133                }
5134            }
5135        }
5136        return null;
5137    }
5138
5139    // TODO: handle preferred activities missing while user has amnesia
5140    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5141            List<ResolveInfo> query, int priority, boolean always,
5142            boolean removeMatches, boolean debug, int userId) {
5143        if (!sUserManager.exists(userId)) return null;
5144        flags = updateFlagsForResolve(flags, userId, intent);
5145        // writer
5146        synchronized (mPackages) {
5147            if (intent.getSelector() != null) {
5148                intent = intent.getSelector();
5149            }
5150            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5151
5152            // Try to find a matching persistent preferred activity.
5153            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5154                    debug, userId);
5155
5156            // If a persistent preferred activity matched, use it.
5157            if (pri != null) {
5158                return pri;
5159            }
5160
5161            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5162            // Get the list of preferred activities that handle the intent
5163            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5164            List<PreferredActivity> prefs = pir != null
5165                    ? pir.queryIntent(intent, resolvedType,
5166                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5167                    : null;
5168            if (prefs != null && prefs.size() > 0) {
5169                boolean changed = false;
5170                try {
5171                    // First figure out how good the original match set is.
5172                    // We will only allow preferred activities that came
5173                    // from the same match quality.
5174                    int match = 0;
5175
5176                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5177
5178                    final int N = query.size();
5179                    for (int j=0; j<N; j++) {
5180                        final ResolveInfo ri = query.get(j);
5181                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5182                                + ": 0x" + Integer.toHexString(match));
5183                        if (ri.match > match) {
5184                            match = ri.match;
5185                        }
5186                    }
5187
5188                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5189                            + Integer.toHexString(match));
5190
5191                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5192                    final int M = prefs.size();
5193                    for (int i=0; i<M; i++) {
5194                        final PreferredActivity pa = prefs.get(i);
5195                        if (DEBUG_PREFERRED || debug) {
5196                            Slog.v(TAG, "Checking PreferredActivity ds="
5197                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5198                                    + "\n  component=" + pa.mPref.mComponent);
5199                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5200                        }
5201                        if (pa.mPref.mMatch != match) {
5202                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5203                                    + Integer.toHexString(pa.mPref.mMatch));
5204                            continue;
5205                        }
5206                        // If it's not an "always" type preferred activity and that's what we're
5207                        // looking for, skip it.
5208                        if (always && !pa.mPref.mAlways) {
5209                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5210                            continue;
5211                        }
5212                        final ActivityInfo ai = getActivityInfo(
5213                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5214                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5215                                userId);
5216                        if (DEBUG_PREFERRED || debug) {
5217                            Slog.v(TAG, "Found preferred activity:");
5218                            if (ai != null) {
5219                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5220                            } else {
5221                                Slog.v(TAG, "  null");
5222                            }
5223                        }
5224                        if (ai == null) {
5225                            // This previously registered preferred activity
5226                            // component is no longer known.  Most likely an update
5227                            // to the app was installed and in the new version this
5228                            // component no longer exists.  Clean it up by removing
5229                            // it from the preferred activities list, and skip it.
5230                            Slog.w(TAG, "Removing dangling preferred activity: "
5231                                    + pa.mPref.mComponent);
5232                            pir.removeFilter(pa);
5233                            changed = true;
5234                            continue;
5235                        }
5236                        for (int j=0; j<N; j++) {
5237                            final ResolveInfo ri = query.get(j);
5238                            if (!ri.activityInfo.applicationInfo.packageName
5239                                    .equals(ai.applicationInfo.packageName)) {
5240                                continue;
5241                            }
5242                            if (!ri.activityInfo.name.equals(ai.name)) {
5243                                continue;
5244                            }
5245
5246                            if (removeMatches) {
5247                                pir.removeFilter(pa);
5248                                changed = true;
5249                                if (DEBUG_PREFERRED) {
5250                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5251                                }
5252                                break;
5253                            }
5254
5255                            // Okay we found a previously set preferred or last chosen app.
5256                            // If the result set is different from when this
5257                            // was created, we need to clear it and re-ask the
5258                            // user their preference, if we're looking for an "always" type entry.
5259                            if (always && !pa.mPref.sameSet(query)) {
5260                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5261                                        + intent + " type " + resolvedType);
5262                                if (DEBUG_PREFERRED) {
5263                                    Slog.v(TAG, "Removing preferred activity since set changed "
5264                                            + pa.mPref.mComponent);
5265                                }
5266                                pir.removeFilter(pa);
5267                                // Re-add the filter as a "last chosen" entry (!always)
5268                                PreferredActivity lastChosen = new PreferredActivity(
5269                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5270                                pir.addFilter(lastChosen);
5271                                changed = true;
5272                                return null;
5273                            }
5274
5275                            // Yay! Either the set matched or we're looking for the last chosen
5276                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5277                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5278                            return ri;
5279                        }
5280                    }
5281                } finally {
5282                    if (changed) {
5283                        if (DEBUG_PREFERRED) {
5284                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5285                        }
5286                        scheduleWritePackageRestrictionsLocked(userId);
5287                    }
5288                }
5289            }
5290        }
5291        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5292        return null;
5293    }
5294
5295    /*
5296     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5297     */
5298    @Override
5299    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5300            int targetUserId) {
5301        mContext.enforceCallingOrSelfPermission(
5302                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5303        List<CrossProfileIntentFilter> matches =
5304                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5305        if (matches != null) {
5306            int size = matches.size();
5307            for (int i = 0; i < size; i++) {
5308                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5309            }
5310        }
5311        if (hasWebURI(intent)) {
5312            // cross-profile app linking works only towards the parent.
5313            final UserInfo parent = getProfileParent(sourceUserId);
5314            synchronized(mPackages) {
5315                int flags = updateFlagsForResolve(0, parent.id, intent);
5316                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5317                        intent, resolvedType, flags, sourceUserId, parent.id);
5318                return xpDomainInfo != null;
5319            }
5320        }
5321        return false;
5322    }
5323
5324    private UserInfo getProfileParent(int userId) {
5325        final long identity = Binder.clearCallingIdentity();
5326        try {
5327            return sUserManager.getProfileParent(userId);
5328        } finally {
5329            Binder.restoreCallingIdentity(identity);
5330        }
5331    }
5332
5333    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5334            String resolvedType, int userId) {
5335        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5336        if (resolver != null) {
5337            return resolver.queryIntent(intent, resolvedType, false, userId);
5338        }
5339        return null;
5340    }
5341
5342    @Override
5343    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5344            String resolvedType, int flags, int userId) {
5345        try {
5346            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5347
5348            return new ParceledListSlice<>(
5349                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5350        } finally {
5351            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5352        }
5353    }
5354
5355    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5356            String resolvedType, int flags, int userId) {
5357        if (!sUserManager.exists(userId)) return Collections.emptyList();
5358        flags = updateFlagsForResolve(flags, userId, intent);
5359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5360                false /* requireFullPermission */, false /* checkShell */,
5361                "query intent activities");
5362        ComponentName comp = intent.getComponent();
5363        if (comp == null) {
5364            if (intent.getSelector() != null) {
5365                intent = intent.getSelector();
5366                comp = intent.getComponent();
5367            }
5368        }
5369
5370        if (comp != null) {
5371            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5372            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5373            if (ai != null) {
5374                final ResolveInfo ri = new ResolveInfo();
5375                ri.activityInfo = ai;
5376                list.add(ri);
5377            }
5378            return list;
5379        }
5380
5381        // reader
5382        synchronized (mPackages) {
5383            final String pkgName = intent.getPackage();
5384            if (pkgName == null) {
5385                List<CrossProfileIntentFilter> matchingFilters =
5386                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5387                // Check for results that need to skip the current profile.
5388                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5389                        resolvedType, flags, userId);
5390                if (xpResolveInfo != null) {
5391                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5392                    result.add(xpResolveInfo);
5393                    return filterIfNotSystemUser(result, userId);
5394                }
5395
5396                // Check for results in the current profile.
5397                List<ResolveInfo> result = mActivities.queryIntent(
5398                        intent, resolvedType, flags, userId);
5399                result = filterIfNotSystemUser(result, userId);
5400
5401                // Check for cross profile results.
5402                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5403                xpResolveInfo = queryCrossProfileIntents(
5404                        matchingFilters, intent, resolvedType, flags, userId,
5405                        hasNonNegativePriorityResult);
5406                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5407                    boolean isVisibleToUser = filterIfNotSystemUser(
5408                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5409                    if (isVisibleToUser) {
5410                        result.add(xpResolveInfo);
5411                        Collections.sort(result, mResolvePrioritySorter);
5412                    }
5413                }
5414                if (hasWebURI(intent)) {
5415                    CrossProfileDomainInfo xpDomainInfo = null;
5416                    final UserInfo parent = getProfileParent(userId);
5417                    if (parent != null) {
5418                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5419                                flags, userId, parent.id);
5420                    }
5421                    if (xpDomainInfo != null) {
5422                        if (xpResolveInfo != null) {
5423                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5424                            // in the result.
5425                            result.remove(xpResolveInfo);
5426                        }
5427                        if (result.size() == 0) {
5428                            result.add(xpDomainInfo.resolveInfo);
5429                            return result;
5430                        }
5431                    } else if (result.size() <= 1) {
5432                        return result;
5433                    }
5434                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5435                            xpDomainInfo, userId);
5436                    Collections.sort(result, mResolvePrioritySorter);
5437                }
5438                return result;
5439            }
5440            final PackageParser.Package pkg = mPackages.get(pkgName);
5441            if (pkg != null) {
5442                return filterIfNotSystemUser(
5443                        mActivities.queryIntentForPackage(
5444                                intent, resolvedType, flags, pkg.activities, userId),
5445                        userId);
5446            }
5447            return new ArrayList<ResolveInfo>();
5448        }
5449    }
5450
5451    private static class CrossProfileDomainInfo {
5452        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5453        ResolveInfo resolveInfo;
5454        /* Best domain verification status of the activities found in the other profile */
5455        int bestDomainVerificationStatus;
5456    }
5457
5458    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5459            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5460        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5461                sourceUserId)) {
5462            return null;
5463        }
5464        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5465                resolvedType, flags, parentUserId);
5466
5467        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5468            return null;
5469        }
5470        CrossProfileDomainInfo result = null;
5471        int size = resultTargetUser.size();
5472        for (int i = 0; i < size; i++) {
5473            ResolveInfo riTargetUser = resultTargetUser.get(i);
5474            // Intent filter verification is only for filters that specify a host. So don't return
5475            // those that handle all web uris.
5476            if (riTargetUser.handleAllWebDataURI) {
5477                continue;
5478            }
5479            String packageName = riTargetUser.activityInfo.packageName;
5480            PackageSetting ps = mSettings.mPackages.get(packageName);
5481            if (ps == null) {
5482                continue;
5483            }
5484            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5485            int status = (int)(verificationState >> 32);
5486            if (result == null) {
5487                result = new CrossProfileDomainInfo();
5488                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5489                        sourceUserId, parentUserId);
5490                result.bestDomainVerificationStatus = status;
5491            } else {
5492                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5493                        result.bestDomainVerificationStatus);
5494            }
5495        }
5496        // Don't consider matches with status NEVER across profiles.
5497        if (result != null && result.bestDomainVerificationStatus
5498                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5499            return null;
5500        }
5501        return result;
5502    }
5503
5504    /**
5505     * Verification statuses are ordered from the worse to the best, except for
5506     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5507     */
5508    private int bestDomainVerificationStatus(int status1, int status2) {
5509        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5510            return status2;
5511        }
5512        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5513            return status1;
5514        }
5515        return (int) MathUtils.max(status1, status2);
5516    }
5517
5518    private boolean isUserEnabled(int userId) {
5519        long callingId = Binder.clearCallingIdentity();
5520        try {
5521            UserInfo userInfo = sUserManager.getUserInfo(userId);
5522            return userInfo != null && userInfo.isEnabled();
5523        } finally {
5524            Binder.restoreCallingIdentity(callingId);
5525        }
5526    }
5527
5528    /**
5529     * Filter out activities with systemUserOnly flag set, when current user is not System.
5530     *
5531     * @return filtered list
5532     */
5533    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5534        if (userId == UserHandle.USER_SYSTEM) {
5535            return resolveInfos;
5536        }
5537        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5538            ResolveInfo info = resolveInfos.get(i);
5539            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5540                resolveInfos.remove(i);
5541            }
5542        }
5543        return resolveInfos;
5544    }
5545
5546    /**
5547     * @param resolveInfos list of resolve infos in descending priority order
5548     * @return if the list contains a resolve info with non-negative priority
5549     */
5550    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5551        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5552    }
5553
5554    private static boolean hasWebURI(Intent intent) {
5555        if (intent.getData() == null) {
5556            return false;
5557        }
5558        final String scheme = intent.getScheme();
5559        if (TextUtils.isEmpty(scheme)) {
5560            return false;
5561        }
5562        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5563    }
5564
5565    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5566            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5567            int userId) {
5568        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5569
5570        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5571            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5572                    candidates.size());
5573        }
5574
5575        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5576        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5577        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5578        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5579        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5580        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5581
5582        synchronized (mPackages) {
5583            final int count = candidates.size();
5584            // First, try to use linked apps. Partition the candidates into four lists:
5585            // one for the final results, one for the "do not use ever", one for "undefined status"
5586            // and finally one for "browser app type".
5587            for (int n=0; n<count; n++) {
5588                ResolveInfo info = candidates.get(n);
5589                String packageName = info.activityInfo.packageName;
5590                PackageSetting ps = mSettings.mPackages.get(packageName);
5591                if (ps != null) {
5592                    // Add to the special match all list (Browser use case)
5593                    if (info.handleAllWebDataURI) {
5594                        matchAllList.add(info);
5595                        continue;
5596                    }
5597                    // Try to get the status from User settings first
5598                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5599                    int status = (int)(packedStatus >> 32);
5600                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5601                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5602                        if (DEBUG_DOMAIN_VERIFICATION) {
5603                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5604                                    + " : linkgen=" + linkGeneration);
5605                        }
5606                        // Use link-enabled generation as preferredOrder, i.e.
5607                        // prefer newly-enabled over earlier-enabled.
5608                        info.preferredOrder = linkGeneration;
5609                        alwaysList.add(info);
5610                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5611                        if (DEBUG_DOMAIN_VERIFICATION) {
5612                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5613                        }
5614                        neverList.add(info);
5615                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5616                        if (DEBUG_DOMAIN_VERIFICATION) {
5617                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5618                        }
5619                        alwaysAskList.add(info);
5620                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5621                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5622                        if (DEBUG_DOMAIN_VERIFICATION) {
5623                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5624                        }
5625                        undefinedList.add(info);
5626                    }
5627                }
5628            }
5629
5630            // We'll want to include browser possibilities in a few cases
5631            boolean includeBrowser = false;
5632
5633            // First try to add the "always" resolution(s) for the current user, if any
5634            if (alwaysList.size() > 0) {
5635                result.addAll(alwaysList);
5636            } else {
5637                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5638                result.addAll(undefinedList);
5639                // Maybe add one for the other profile.
5640                if (xpDomainInfo != null && (
5641                        xpDomainInfo.bestDomainVerificationStatus
5642                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5643                    result.add(xpDomainInfo.resolveInfo);
5644                }
5645                includeBrowser = true;
5646            }
5647
5648            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5649            // If there were 'always' entries their preferred order has been set, so we also
5650            // back that off to make the alternatives equivalent
5651            if (alwaysAskList.size() > 0) {
5652                for (ResolveInfo i : result) {
5653                    i.preferredOrder = 0;
5654                }
5655                result.addAll(alwaysAskList);
5656                includeBrowser = true;
5657            }
5658
5659            if (includeBrowser) {
5660                // Also add browsers (all of them or only the default one)
5661                if (DEBUG_DOMAIN_VERIFICATION) {
5662                    Slog.v(TAG, "   ...including browsers in candidate set");
5663                }
5664                if ((matchFlags & MATCH_ALL) != 0) {
5665                    result.addAll(matchAllList);
5666                } else {
5667                    // Browser/generic handling case.  If there's a default browser, go straight
5668                    // to that (but only if there is no other higher-priority match).
5669                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5670                    int maxMatchPrio = 0;
5671                    ResolveInfo defaultBrowserMatch = null;
5672                    final int numCandidates = matchAllList.size();
5673                    for (int n = 0; n < numCandidates; n++) {
5674                        ResolveInfo info = matchAllList.get(n);
5675                        // track the highest overall match priority...
5676                        if (info.priority > maxMatchPrio) {
5677                            maxMatchPrio = info.priority;
5678                        }
5679                        // ...and the highest-priority default browser match
5680                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5681                            if (defaultBrowserMatch == null
5682                                    || (defaultBrowserMatch.priority < info.priority)) {
5683                                if (debug) {
5684                                    Slog.v(TAG, "Considering default browser match " + info);
5685                                }
5686                                defaultBrowserMatch = info;
5687                            }
5688                        }
5689                    }
5690                    if (defaultBrowserMatch != null
5691                            && defaultBrowserMatch.priority >= maxMatchPrio
5692                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5693                    {
5694                        if (debug) {
5695                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5696                        }
5697                        result.add(defaultBrowserMatch);
5698                    } else {
5699                        result.addAll(matchAllList);
5700                    }
5701                }
5702
5703                // If there is nothing selected, add all candidates and remove the ones that the user
5704                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5705                if (result.size() == 0) {
5706                    result.addAll(candidates);
5707                    result.removeAll(neverList);
5708                }
5709            }
5710        }
5711        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5712            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5713                    result.size());
5714            for (ResolveInfo info : result) {
5715                Slog.v(TAG, "  + " + info.activityInfo);
5716            }
5717        }
5718        return result;
5719    }
5720
5721    // Returns a packed value as a long:
5722    //
5723    // high 'int'-sized word: link status: undefined/ask/never/always.
5724    // low 'int'-sized word: relative priority among 'always' results.
5725    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5726        long result = ps.getDomainVerificationStatusForUser(userId);
5727        // if none available, get the master status
5728        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5729            if (ps.getIntentFilterVerificationInfo() != null) {
5730                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5731            }
5732        }
5733        return result;
5734    }
5735
5736    private ResolveInfo querySkipCurrentProfileIntents(
5737            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5738            int flags, int sourceUserId) {
5739        if (matchingFilters != null) {
5740            int size = matchingFilters.size();
5741            for (int i = 0; i < size; i ++) {
5742                CrossProfileIntentFilter filter = matchingFilters.get(i);
5743                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5744                    // Checking if there are activities in the target user that can handle the
5745                    // intent.
5746                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5747                            resolvedType, flags, sourceUserId);
5748                    if (resolveInfo != null) {
5749                        return resolveInfo;
5750                    }
5751                }
5752            }
5753        }
5754        return null;
5755    }
5756
5757    // Return matching ResolveInfo in target user if any.
5758    private ResolveInfo queryCrossProfileIntents(
5759            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5760            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5761        if (matchingFilters != null) {
5762            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5763            // match the same intent. For performance reasons, it is better not to
5764            // run queryIntent twice for the same userId
5765            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5766            int size = matchingFilters.size();
5767            for (int i = 0; i < size; i++) {
5768                CrossProfileIntentFilter filter = matchingFilters.get(i);
5769                int targetUserId = filter.getTargetUserId();
5770                boolean skipCurrentProfile =
5771                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5772                boolean skipCurrentProfileIfNoMatchFound =
5773                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5774                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5775                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5776                    // Checking if there are activities in the target user that can handle the
5777                    // intent.
5778                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5779                            resolvedType, flags, sourceUserId);
5780                    if (resolveInfo != null) return resolveInfo;
5781                    alreadyTriedUserIds.put(targetUserId, true);
5782                }
5783            }
5784        }
5785        return null;
5786    }
5787
5788    /**
5789     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5790     * will forward the intent to the filter's target user.
5791     * Otherwise, returns null.
5792     */
5793    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5794            String resolvedType, int flags, int sourceUserId) {
5795        int targetUserId = filter.getTargetUserId();
5796        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5797                resolvedType, flags, targetUserId);
5798        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5799            // If all the matches in the target profile are suspended, return null.
5800            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5801                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5802                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5803                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5804                            targetUserId);
5805                }
5806            }
5807        }
5808        return null;
5809    }
5810
5811    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5812            int sourceUserId, int targetUserId) {
5813        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5814        long ident = Binder.clearCallingIdentity();
5815        boolean targetIsProfile;
5816        try {
5817            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5818        } finally {
5819            Binder.restoreCallingIdentity(ident);
5820        }
5821        String className;
5822        if (targetIsProfile) {
5823            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5824        } else {
5825            className = FORWARD_INTENT_TO_PARENT;
5826        }
5827        ComponentName forwardingActivityComponentName = new ComponentName(
5828                mAndroidApplication.packageName, className);
5829        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5830                sourceUserId);
5831        if (!targetIsProfile) {
5832            forwardingActivityInfo.showUserIcon = targetUserId;
5833            forwardingResolveInfo.noResourceId = true;
5834        }
5835        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5836        forwardingResolveInfo.priority = 0;
5837        forwardingResolveInfo.preferredOrder = 0;
5838        forwardingResolveInfo.match = 0;
5839        forwardingResolveInfo.isDefault = true;
5840        forwardingResolveInfo.filter = filter;
5841        forwardingResolveInfo.targetUserId = targetUserId;
5842        return forwardingResolveInfo;
5843    }
5844
5845    @Override
5846    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5847            Intent[] specifics, String[] specificTypes, Intent intent,
5848            String resolvedType, int flags, int userId) {
5849        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5850                specificTypes, intent, resolvedType, flags, userId));
5851    }
5852
5853    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5854            Intent[] specifics, String[] specificTypes, Intent intent,
5855            String resolvedType, int flags, int userId) {
5856        if (!sUserManager.exists(userId)) return Collections.emptyList();
5857        flags = updateFlagsForResolve(flags, userId, intent);
5858        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5859                false /* requireFullPermission */, false /* checkShell */,
5860                "query intent activity options");
5861        final String resultsAction = intent.getAction();
5862
5863        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5864                | PackageManager.GET_RESOLVED_FILTER, userId);
5865
5866        if (DEBUG_INTENT_MATCHING) {
5867            Log.v(TAG, "Query " + intent + ": " + results);
5868        }
5869
5870        int specificsPos = 0;
5871        int N;
5872
5873        // todo: note that the algorithm used here is O(N^2).  This
5874        // isn't a problem in our current environment, but if we start running
5875        // into situations where we have more than 5 or 10 matches then this
5876        // should probably be changed to something smarter...
5877
5878        // First we go through and resolve each of the specific items
5879        // that were supplied, taking care of removing any corresponding
5880        // duplicate items in the generic resolve list.
5881        if (specifics != null) {
5882            for (int i=0; i<specifics.length; i++) {
5883                final Intent sintent = specifics[i];
5884                if (sintent == null) {
5885                    continue;
5886                }
5887
5888                if (DEBUG_INTENT_MATCHING) {
5889                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5890                }
5891
5892                String action = sintent.getAction();
5893                if (resultsAction != null && resultsAction.equals(action)) {
5894                    // If this action was explicitly requested, then don't
5895                    // remove things that have it.
5896                    action = null;
5897                }
5898
5899                ResolveInfo ri = null;
5900                ActivityInfo ai = null;
5901
5902                ComponentName comp = sintent.getComponent();
5903                if (comp == null) {
5904                    ri = resolveIntent(
5905                        sintent,
5906                        specificTypes != null ? specificTypes[i] : null,
5907                            flags, userId);
5908                    if (ri == null) {
5909                        continue;
5910                    }
5911                    if (ri == mResolveInfo) {
5912                        // ACK!  Must do something better with this.
5913                    }
5914                    ai = ri.activityInfo;
5915                    comp = new ComponentName(ai.applicationInfo.packageName,
5916                            ai.name);
5917                } else {
5918                    ai = getActivityInfo(comp, flags, userId);
5919                    if (ai == null) {
5920                        continue;
5921                    }
5922                }
5923
5924                // Look for any generic query activities that are duplicates
5925                // of this specific one, and remove them from the results.
5926                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5927                N = results.size();
5928                int j;
5929                for (j=specificsPos; j<N; j++) {
5930                    ResolveInfo sri = results.get(j);
5931                    if ((sri.activityInfo.name.equals(comp.getClassName())
5932                            && sri.activityInfo.applicationInfo.packageName.equals(
5933                                    comp.getPackageName()))
5934                        || (action != null && sri.filter.matchAction(action))) {
5935                        results.remove(j);
5936                        if (DEBUG_INTENT_MATCHING) Log.v(
5937                            TAG, "Removing duplicate item from " + j
5938                            + " due to specific " + specificsPos);
5939                        if (ri == null) {
5940                            ri = sri;
5941                        }
5942                        j--;
5943                        N--;
5944                    }
5945                }
5946
5947                // Add this specific item to its proper place.
5948                if (ri == null) {
5949                    ri = new ResolveInfo();
5950                    ri.activityInfo = ai;
5951                }
5952                results.add(specificsPos, ri);
5953                ri.specificIndex = i;
5954                specificsPos++;
5955            }
5956        }
5957
5958        // Now we go through the remaining generic results and remove any
5959        // duplicate actions that are found here.
5960        N = results.size();
5961        for (int i=specificsPos; i<N-1; i++) {
5962            final ResolveInfo rii = results.get(i);
5963            if (rii.filter == null) {
5964                continue;
5965            }
5966
5967            // Iterate over all of the actions of this result's intent
5968            // filter...  typically this should be just one.
5969            final Iterator<String> it = rii.filter.actionsIterator();
5970            if (it == null) {
5971                continue;
5972            }
5973            while (it.hasNext()) {
5974                final String action = it.next();
5975                if (resultsAction != null && resultsAction.equals(action)) {
5976                    // If this action was explicitly requested, then don't
5977                    // remove things that have it.
5978                    continue;
5979                }
5980                for (int j=i+1; j<N; j++) {
5981                    final ResolveInfo rij = results.get(j);
5982                    if (rij.filter != null && rij.filter.hasAction(action)) {
5983                        results.remove(j);
5984                        if (DEBUG_INTENT_MATCHING) Log.v(
5985                            TAG, "Removing duplicate item from " + j
5986                            + " due to action " + action + " at " + i);
5987                        j--;
5988                        N--;
5989                    }
5990                }
5991            }
5992
5993            // If the caller didn't request filter information, drop it now
5994            // so we don't have to marshall/unmarshall it.
5995            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5996                rii.filter = null;
5997            }
5998        }
5999
6000        // Filter out the caller activity if so requested.
6001        if (caller != null) {
6002            N = results.size();
6003            for (int i=0; i<N; i++) {
6004                ActivityInfo ainfo = results.get(i).activityInfo;
6005                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6006                        && caller.getClassName().equals(ainfo.name)) {
6007                    results.remove(i);
6008                    break;
6009                }
6010            }
6011        }
6012
6013        // If the caller didn't request filter information,
6014        // drop them now so we don't have to
6015        // marshall/unmarshall it.
6016        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6017            N = results.size();
6018            for (int i=0; i<N; i++) {
6019                results.get(i).filter = null;
6020            }
6021        }
6022
6023        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6024        return results;
6025    }
6026
6027    @Override
6028    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6029            String resolvedType, int flags, int userId) {
6030        return new ParceledListSlice<>(
6031                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6032    }
6033
6034    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6035            String resolvedType, int flags, int userId) {
6036        if (!sUserManager.exists(userId)) return Collections.emptyList();
6037        flags = updateFlagsForResolve(flags, userId, intent);
6038        ComponentName comp = intent.getComponent();
6039        if (comp == null) {
6040            if (intent.getSelector() != null) {
6041                intent = intent.getSelector();
6042                comp = intent.getComponent();
6043            }
6044        }
6045        if (comp != null) {
6046            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6047            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6048            if (ai != null) {
6049                ResolveInfo ri = new ResolveInfo();
6050                ri.activityInfo = ai;
6051                list.add(ri);
6052            }
6053            return list;
6054        }
6055
6056        // reader
6057        synchronized (mPackages) {
6058            String pkgName = intent.getPackage();
6059            if (pkgName == null) {
6060                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6061            }
6062            final PackageParser.Package pkg = mPackages.get(pkgName);
6063            if (pkg != null) {
6064                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6065                        userId);
6066            }
6067            return Collections.emptyList();
6068        }
6069    }
6070
6071    @Override
6072    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6073        if (!sUserManager.exists(userId)) return null;
6074        flags = updateFlagsForResolve(flags, userId, intent);
6075        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6076        if (query != null) {
6077            if (query.size() >= 1) {
6078                // If there is more than one service with the same priority,
6079                // just arbitrarily pick the first one.
6080                return query.get(0);
6081            }
6082        }
6083        return null;
6084    }
6085
6086    @Override
6087    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6088            String resolvedType, int flags, int userId) {
6089        return new ParceledListSlice<>(
6090                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6091    }
6092
6093    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6094            String resolvedType, int flags, int userId) {
6095        if (!sUserManager.exists(userId)) return Collections.emptyList();
6096        flags = updateFlagsForResolve(flags, userId, intent);
6097        ComponentName comp = intent.getComponent();
6098        if (comp == null) {
6099            if (intent.getSelector() != null) {
6100                intent = intent.getSelector();
6101                comp = intent.getComponent();
6102            }
6103        }
6104        if (comp != null) {
6105            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6106            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6107            if (si != null) {
6108                final ResolveInfo ri = new ResolveInfo();
6109                ri.serviceInfo = si;
6110                list.add(ri);
6111            }
6112            return list;
6113        }
6114
6115        // reader
6116        synchronized (mPackages) {
6117            String pkgName = intent.getPackage();
6118            if (pkgName == null) {
6119                return mServices.queryIntent(intent, resolvedType, flags, userId);
6120            }
6121            final PackageParser.Package pkg = mPackages.get(pkgName);
6122            if (pkg != null) {
6123                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6124                        userId);
6125            }
6126            return Collections.emptyList();
6127        }
6128    }
6129
6130    @Override
6131    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6132            String resolvedType, int flags, int userId) {
6133        return new ParceledListSlice<>(
6134                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6135    }
6136
6137    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6138            Intent intent, String resolvedType, int flags, int userId) {
6139        if (!sUserManager.exists(userId)) return Collections.emptyList();
6140        flags = updateFlagsForResolve(flags, userId, intent);
6141        ComponentName comp = intent.getComponent();
6142        if (comp == null) {
6143            if (intent.getSelector() != null) {
6144                intent = intent.getSelector();
6145                comp = intent.getComponent();
6146            }
6147        }
6148        if (comp != null) {
6149            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6150            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6151            if (pi != null) {
6152                final ResolveInfo ri = new ResolveInfo();
6153                ri.providerInfo = pi;
6154                list.add(ri);
6155            }
6156            return list;
6157        }
6158
6159        // reader
6160        synchronized (mPackages) {
6161            String pkgName = intent.getPackage();
6162            if (pkgName == null) {
6163                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6164            }
6165            final PackageParser.Package pkg = mPackages.get(pkgName);
6166            if (pkg != null) {
6167                return mProviders.queryIntentForPackage(
6168                        intent, resolvedType, flags, pkg.providers, userId);
6169            }
6170            return Collections.emptyList();
6171        }
6172    }
6173
6174    @Override
6175    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6176        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6177        flags = updateFlagsForPackage(flags, userId, null);
6178        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6179        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6180                true /* requireFullPermission */, false /* checkShell */,
6181                "get installed packages");
6182
6183        // writer
6184        synchronized (mPackages) {
6185            ArrayList<PackageInfo> list;
6186            if (listUninstalled) {
6187                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6188                for (PackageSetting ps : mSettings.mPackages.values()) {
6189                    final PackageInfo pi;
6190                    if (ps.pkg != null) {
6191                        pi = generatePackageInfo(ps, flags, userId);
6192                    } else {
6193                        pi = generatePackageInfo(ps, flags, userId);
6194                    }
6195                    if (pi != null) {
6196                        list.add(pi);
6197                    }
6198                }
6199            } else {
6200                list = new ArrayList<PackageInfo>(mPackages.size());
6201                for (PackageParser.Package p : mPackages.values()) {
6202                    final PackageInfo pi =
6203                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6204                    if (pi != null) {
6205                        list.add(pi);
6206                    }
6207                }
6208            }
6209
6210            return new ParceledListSlice<PackageInfo>(list);
6211        }
6212    }
6213
6214    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6215            String[] permissions, boolean[] tmp, int flags, int userId) {
6216        int numMatch = 0;
6217        final PermissionsState permissionsState = ps.getPermissionsState();
6218        for (int i=0; i<permissions.length; i++) {
6219            final String permission = permissions[i];
6220            if (permissionsState.hasPermission(permission, userId)) {
6221                tmp[i] = true;
6222                numMatch++;
6223            } else {
6224                tmp[i] = false;
6225            }
6226        }
6227        if (numMatch == 0) {
6228            return;
6229        }
6230        final PackageInfo pi;
6231        if (ps.pkg != null) {
6232            pi = generatePackageInfo(ps, flags, userId);
6233        } else {
6234            pi = generatePackageInfo(ps, flags, userId);
6235        }
6236        // The above might return null in cases of uninstalled apps or install-state
6237        // skew across users/profiles.
6238        if (pi != null) {
6239            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6240                if (numMatch == permissions.length) {
6241                    pi.requestedPermissions = permissions;
6242                } else {
6243                    pi.requestedPermissions = new String[numMatch];
6244                    numMatch = 0;
6245                    for (int i=0; i<permissions.length; i++) {
6246                        if (tmp[i]) {
6247                            pi.requestedPermissions[numMatch] = permissions[i];
6248                            numMatch++;
6249                        }
6250                    }
6251                }
6252            }
6253            list.add(pi);
6254        }
6255    }
6256
6257    @Override
6258    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6259            String[] permissions, int flags, int userId) {
6260        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6261        flags = updateFlagsForPackage(flags, userId, permissions);
6262        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6263
6264        // writer
6265        synchronized (mPackages) {
6266            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6267            boolean[] tmpBools = new boolean[permissions.length];
6268            if (listUninstalled) {
6269                for (PackageSetting ps : mSettings.mPackages.values()) {
6270                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6271                }
6272            } else {
6273                for (PackageParser.Package pkg : mPackages.values()) {
6274                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6275                    if (ps != null) {
6276                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6277                                userId);
6278                    }
6279                }
6280            }
6281
6282            return new ParceledListSlice<PackageInfo>(list);
6283        }
6284    }
6285
6286    @Override
6287    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6288        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6289        flags = updateFlagsForApplication(flags, userId, null);
6290        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6291
6292        // writer
6293        synchronized (mPackages) {
6294            ArrayList<ApplicationInfo> list;
6295            if (listUninstalled) {
6296                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6297                for (PackageSetting ps : mSettings.mPackages.values()) {
6298                    ApplicationInfo ai;
6299                    if (ps.pkg != null) {
6300                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6301                                ps.readUserState(userId), userId);
6302                    } else {
6303                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6304                    }
6305                    if (ai != null) {
6306                        list.add(ai);
6307                    }
6308                }
6309            } else {
6310                list = new ArrayList<ApplicationInfo>(mPackages.size());
6311                for (PackageParser.Package p : mPackages.values()) {
6312                    if (p.mExtras != null) {
6313                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6314                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6315                        if (ai != null) {
6316                            list.add(ai);
6317                        }
6318                    }
6319                }
6320            }
6321
6322            return new ParceledListSlice<ApplicationInfo>(list);
6323        }
6324    }
6325
6326    @Override
6327    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6328        if (DISABLE_EPHEMERAL_APPS) {
6329            return null;
6330        }
6331
6332        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6333                "getEphemeralApplications");
6334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6335                true /* requireFullPermission */, false /* checkShell */,
6336                "getEphemeralApplications");
6337        synchronized (mPackages) {
6338            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6339                    .getEphemeralApplicationsLPw(userId);
6340            if (ephemeralApps != null) {
6341                return new ParceledListSlice<>(ephemeralApps);
6342            }
6343        }
6344        return null;
6345    }
6346
6347    @Override
6348    public boolean isEphemeralApplication(String packageName, int userId) {
6349        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6350                true /* requireFullPermission */, false /* checkShell */,
6351                "isEphemeral");
6352        if (DISABLE_EPHEMERAL_APPS) {
6353            return false;
6354        }
6355
6356        if (!isCallerSameApp(packageName)) {
6357            return false;
6358        }
6359        synchronized (mPackages) {
6360            PackageParser.Package pkg = mPackages.get(packageName);
6361            if (pkg != null) {
6362                return pkg.applicationInfo.isEphemeralApp();
6363            }
6364        }
6365        return false;
6366    }
6367
6368    @Override
6369    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6370        if (DISABLE_EPHEMERAL_APPS) {
6371            return null;
6372        }
6373
6374        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6375                true /* requireFullPermission */, false /* checkShell */,
6376                "getCookie");
6377        if (!isCallerSameApp(packageName)) {
6378            return null;
6379        }
6380        synchronized (mPackages) {
6381            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6382                    packageName, userId);
6383        }
6384    }
6385
6386    @Override
6387    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6388        if (DISABLE_EPHEMERAL_APPS) {
6389            return true;
6390        }
6391
6392        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6393                true /* requireFullPermission */, true /* checkShell */,
6394                "setCookie");
6395        if (!isCallerSameApp(packageName)) {
6396            return false;
6397        }
6398        synchronized (mPackages) {
6399            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6400                    packageName, cookie, userId);
6401        }
6402    }
6403
6404    @Override
6405    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6406        if (DISABLE_EPHEMERAL_APPS) {
6407            return null;
6408        }
6409
6410        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6411                "getEphemeralApplicationIcon");
6412        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6413                true /* requireFullPermission */, false /* checkShell */,
6414                "getEphemeralApplicationIcon");
6415        synchronized (mPackages) {
6416            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6417                    packageName, userId);
6418        }
6419    }
6420
6421    private boolean isCallerSameApp(String packageName) {
6422        PackageParser.Package pkg = mPackages.get(packageName);
6423        return pkg != null
6424                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6425    }
6426
6427    @Override
6428    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6429        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6430    }
6431
6432    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6433        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6434
6435        // reader
6436        synchronized (mPackages) {
6437            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6438            final int userId = UserHandle.getCallingUserId();
6439            while (i.hasNext()) {
6440                final PackageParser.Package p = i.next();
6441                if (p.applicationInfo == null) continue;
6442
6443                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6444                        && !p.applicationInfo.isDirectBootAware();
6445                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6446                        && p.applicationInfo.isDirectBootAware();
6447
6448                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6449                        && (!mSafeMode || isSystemApp(p))
6450                        && (matchesUnaware || matchesAware)) {
6451                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6452                    if (ps != null) {
6453                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6454                                ps.readUserState(userId), userId);
6455                        if (ai != null) {
6456                            finalList.add(ai);
6457                        }
6458                    }
6459                }
6460            }
6461        }
6462
6463        return finalList;
6464    }
6465
6466    @Override
6467    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6468        if (!sUserManager.exists(userId)) return null;
6469        flags = updateFlagsForComponent(flags, userId, name);
6470        // reader
6471        synchronized (mPackages) {
6472            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6473            PackageSetting ps = provider != null
6474                    ? mSettings.mPackages.get(provider.owner.packageName)
6475                    : null;
6476            return ps != null
6477                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6478                    ? PackageParser.generateProviderInfo(provider, flags,
6479                            ps.readUserState(userId), userId)
6480                    : null;
6481        }
6482    }
6483
6484    /**
6485     * @deprecated
6486     */
6487    @Deprecated
6488    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6489        // reader
6490        synchronized (mPackages) {
6491            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6492                    .entrySet().iterator();
6493            final int userId = UserHandle.getCallingUserId();
6494            while (i.hasNext()) {
6495                Map.Entry<String, PackageParser.Provider> entry = i.next();
6496                PackageParser.Provider p = entry.getValue();
6497                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6498
6499                if (ps != null && p.syncable
6500                        && (!mSafeMode || (p.info.applicationInfo.flags
6501                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6502                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6503                            ps.readUserState(userId), userId);
6504                    if (info != null) {
6505                        outNames.add(entry.getKey());
6506                        outInfo.add(info);
6507                    }
6508                }
6509            }
6510        }
6511    }
6512
6513    @Override
6514    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6515            int uid, int flags) {
6516        final int userId = processName != null ? UserHandle.getUserId(uid)
6517                : UserHandle.getCallingUserId();
6518        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6519        flags = updateFlagsForComponent(flags, userId, processName);
6520
6521        ArrayList<ProviderInfo> finalList = null;
6522        // reader
6523        synchronized (mPackages) {
6524            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6525            while (i.hasNext()) {
6526                final PackageParser.Provider p = i.next();
6527                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6528                if (ps != null && p.info.authority != null
6529                        && (processName == null
6530                                || (p.info.processName.equals(processName)
6531                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6532                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6533                    if (finalList == null) {
6534                        finalList = new ArrayList<ProviderInfo>(3);
6535                    }
6536                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6537                            ps.readUserState(userId), userId);
6538                    if (info != null) {
6539                        finalList.add(info);
6540                    }
6541                }
6542            }
6543        }
6544
6545        if (finalList != null) {
6546            Collections.sort(finalList, mProviderInitOrderSorter);
6547            return new ParceledListSlice<ProviderInfo>(finalList);
6548        }
6549
6550        return ParceledListSlice.emptyList();
6551    }
6552
6553    @Override
6554    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6555        // reader
6556        synchronized (mPackages) {
6557            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6558            return PackageParser.generateInstrumentationInfo(i, flags);
6559        }
6560    }
6561
6562    @Override
6563    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6564            String targetPackage, int flags) {
6565        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6566    }
6567
6568    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6569            int flags) {
6570        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6571
6572        // reader
6573        synchronized (mPackages) {
6574            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6575            while (i.hasNext()) {
6576                final PackageParser.Instrumentation p = i.next();
6577                if (targetPackage == null
6578                        || targetPackage.equals(p.info.targetPackage)) {
6579                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6580                            flags);
6581                    if (ii != null) {
6582                        finalList.add(ii);
6583                    }
6584                }
6585            }
6586        }
6587
6588        return finalList;
6589    }
6590
6591    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6592        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6593        if (overlays == null) {
6594            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6595            return;
6596        }
6597        for (PackageParser.Package opkg : overlays.values()) {
6598            // Not much to do if idmap fails: we already logged the error
6599            // and we certainly don't want to abort installation of pkg simply
6600            // because an overlay didn't fit properly. For these reasons,
6601            // ignore the return value of createIdmapForPackagePairLI.
6602            createIdmapForPackagePairLI(pkg, opkg);
6603        }
6604    }
6605
6606    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6607            PackageParser.Package opkg) {
6608        if (!opkg.mTrustedOverlay) {
6609            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6610                    opkg.baseCodePath + ": overlay not trusted");
6611            return false;
6612        }
6613        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6614        if (overlaySet == null) {
6615            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6616                    opkg.baseCodePath + " but target package has no known overlays");
6617            return false;
6618        }
6619        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6620        // TODO: generate idmap for split APKs
6621        try {
6622            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6623        } catch (InstallerException e) {
6624            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6625                    + opkg.baseCodePath);
6626            return false;
6627        }
6628        PackageParser.Package[] overlayArray =
6629            overlaySet.values().toArray(new PackageParser.Package[0]);
6630        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6631            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6632                return p1.mOverlayPriority - p2.mOverlayPriority;
6633            }
6634        };
6635        Arrays.sort(overlayArray, cmp);
6636
6637        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6638        int i = 0;
6639        for (PackageParser.Package p : overlayArray) {
6640            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6641        }
6642        return true;
6643    }
6644
6645    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6646        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6647        try {
6648            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6649        } finally {
6650            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6651        }
6652    }
6653
6654    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6655        final File[] files = dir.listFiles();
6656        if (ArrayUtils.isEmpty(files)) {
6657            Log.d(TAG, "No files in app dir " + dir);
6658            return;
6659        }
6660
6661        if (DEBUG_PACKAGE_SCANNING) {
6662            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6663                    + " flags=0x" + Integer.toHexString(parseFlags));
6664        }
6665
6666        for (File file : files) {
6667            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6668                    && !PackageInstallerService.isStageName(file.getName());
6669            if (!isPackage) {
6670                // Ignore entries which are not packages
6671                continue;
6672            }
6673            try {
6674                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6675                        scanFlags, currentTime, null);
6676            } catch (PackageManagerException e) {
6677                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6678
6679                // Delete invalid userdata apps
6680                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6681                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6682                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6683                    removeCodePathLI(file);
6684                }
6685            }
6686        }
6687    }
6688
6689    private static File getSettingsProblemFile() {
6690        File dataDir = Environment.getDataDirectory();
6691        File systemDir = new File(dataDir, "system");
6692        File fname = new File(systemDir, "uiderrors.txt");
6693        return fname;
6694    }
6695
6696    static void reportSettingsProblem(int priority, String msg) {
6697        logCriticalInfo(priority, msg);
6698    }
6699
6700    static void logCriticalInfo(int priority, String msg) {
6701        Slog.println(priority, TAG, msg);
6702        EventLogTags.writePmCriticalInfo(msg);
6703        try {
6704            File fname = getSettingsProblemFile();
6705            FileOutputStream out = new FileOutputStream(fname, true);
6706            PrintWriter pw = new FastPrintWriter(out);
6707            SimpleDateFormat formatter = new SimpleDateFormat();
6708            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6709            pw.println(dateString + ": " + msg);
6710            pw.close();
6711            FileUtils.setPermissions(
6712                    fname.toString(),
6713                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6714                    -1, -1);
6715        } catch (java.io.IOException e) {
6716        }
6717    }
6718
6719    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6720            final int policyFlags) throws PackageManagerException {
6721        if (ps != null
6722                && ps.codePath.equals(srcFile)
6723                && ps.timeStamp == srcFile.lastModified()
6724                && !isCompatSignatureUpdateNeeded(pkg)
6725                && !isRecoverSignatureUpdateNeeded(pkg)) {
6726            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6727            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6728            ArraySet<PublicKey> signingKs;
6729            synchronized (mPackages) {
6730                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6731            }
6732            if (ps.signatures.mSignatures != null
6733                    && ps.signatures.mSignatures.length != 0
6734                    && signingKs != null) {
6735                // Optimization: reuse the existing cached certificates
6736                // if the package appears to be unchanged.
6737                pkg.mSignatures = ps.signatures.mSignatures;
6738                pkg.mSigningKeys = signingKs;
6739                return;
6740            }
6741
6742            Slog.w(TAG, "PackageSetting for " + ps.name
6743                    + " is missing signatures.  Collecting certs again to recover them.");
6744        } else {
6745            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6746        }
6747
6748        try {
6749            PackageParser.collectCertificates(pkg, policyFlags);
6750        } catch (PackageParserException e) {
6751            throw PackageManagerException.from(e);
6752        }
6753    }
6754
6755    /**
6756     *  Traces a package scan.
6757     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6758     */
6759    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6760            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6761        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6762        try {
6763            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6764        } finally {
6765            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6766        }
6767    }
6768
6769    /**
6770     *  Scans a package and returns the newly parsed package.
6771     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6772     */
6773    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6774            long currentTime, UserHandle user) throws PackageManagerException {
6775        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6776        PackageParser pp = new PackageParser();
6777        pp.setSeparateProcesses(mSeparateProcesses);
6778        pp.setOnlyCoreApps(mOnlyCore);
6779        pp.setDisplayMetrics(mMetrics);
6780
6781        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6782            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6783        }
6784
6785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6786        final PackageParser.Package pkg;
6787        try {
6788            pkg = pp.parsePackage(scanFile, parseFlags);
6789        } catch (PackageParserException e) {
6790            throw PackageManagerException.from(e);
6791        } finally {
6792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6793        }
6794
6795        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6796    }
6797
6798    /**
6799     *  Scans a package and returns the newly parsed package.
6800     *  @throws PackageManagerException on a parse error.
6801     */
6802    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6803            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6804            throws PackageManagerException {
6805        // If the package has children and this is the first dive in the function
6806        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6807        // packages (parent and children) would be successfully scanned before the
6808        // actual scan since scanning mutates internal state and we want to atomically
6809        // install the package and its children.
6810        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6811            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6812                scanFlags |= SCAN_CHECK_ONLY;
6813            }
6814        } else {
6815            scanFlags &= ~SCAN_CHECK_ONLY;
6816        }
6817
6818        // Scan the parent
6819        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6820                scanFlags, currentTime, user);
6821
6822        // Scan the children
6823        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6824        for (int i = 0; i < childCount; i++) {
6825            PackageParser.Package childPackage = pkg.childPackages.get(i);
6826            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6827                    currentTime, user);
6828        }
6829
6830
6831        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6832            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6833        }
6834
6835        return scannedPkg;
6836    }
6837
6838    /**
6839     *  Scans a package and returns the newly parsed package.
6840     *  @throws PackageManagerException on a parse error.
6841     */
6842    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6843            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6844            throws PackageManagerException {
6845        PackageSetting ps = null;
6846        PackageSetting updatedPkg;
6847        // reader
6848        synchronized (mPackages) {
6849            // Look to see if we already know about this package.
6850            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6851            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6852                // This package has been renamed to its original name.  Let's
6853                // use that.
6854                ps = mSettings.peekPackageLPr(oldName);
6855            }
6856            // If there was no original package, see one for the real package name.
6857            if (ps == null) {
6858                ps = mSettings.peekPackageLPr(pkg.packageName);
6859            }
6860            // Check to see if this package could be hiding/updating a system
6861            // package.  Must look for it either under the original or real
6862            // package name depending on our state.
6863            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6864            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6865
6866            // If this is a package we don't know about on the system partition, we
6867            // may need to remove disabled child packages on the system partition
6868            // or may need to not add child packages if the parent apk is updated
6869            // on the data partition and no longer defines this child package.
6870            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6871                // If this is a parent package for an updated system app and this system
6872                // app got an OTA update which no longer defines some of the child packages
6873                // we have to prune them from the disabled system packages.
6874                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6875                if (disabledPs != null) {
6876                    final int scannedChildCount = (pkg.childPackages != null)
6877                            ? pkg.childPackages.size() : 0;
6878                    final int disabledChildCount = disabledPs.childPackageNames != null
6879                            ? disabledPs.childPackageNames.size() : 0;
6880                    for (int i = 0; i < disabledChildCount; i++) {
6881                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6882                        boolean disabledPackageAvailable = false;
6883                        for (int j = 0; j < scannedChildCount; j++) {
6884                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6885                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6886                                disabledPackageAvailable = true;
6887                                break;
6888                            }
6889                         }
6890                         if (!disabledPackageAvailable) {
6891                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6892                         }
6893                    }
6894                }
6895            }
6896        }
6897
6898        boolean updatedPkgBetter = false;
6899        // First check if this is a system package that may involve an update
6900        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6901            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6902            // it needs to drop FLAG_PRIVILEGED.
6903            if (locationIsPrivileged(scanFile)) {
6904                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6905            } else {
6906                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6907            }
6908
6909            if (ps != null && !ps.codePath.equals(scanFile)) {
6910                // The path has changed from what was last scanned...  check the
6911                // version of the new path against what we have stored to determine
6912                // what to do.
6913                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6914                if (pkg.mVersionCode <= ps.versionCode) {
6915                    // The system package has been updated and the code path does not match
6916                    // Ignore entry. Skip it.
6917                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6918                            + " ignored: updated version " + ps.versionCode
6919                            + " better than this " + pkg.mVersionCode);
6920                    if (!updatedPkg.codePath.equals(scanFile)) {
6921                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6922                                + ps.name + " changing from " + updatedPkg.codePathString
6923                                + " to " + scanFile);
6924                        updatedPkg.codePath = scanFile;
6925                        updatedPkg.codePathString = scanFile.toString();
6926                        updatedPkg.resourcePath = scanFile;
6927                        updatedPkg.resourcePathString = scanFile.toString();
6928                    }
6929                    updatedPkg.pkg = pkg;
6930                    updatedPkg.versionCode = pkg.mVersionCode;
6931
6932                    // Update the disabled system child packages to point to the package too.
6933                    final int childCount = updatedPkg.childPackageNames != null
6934                            ? updatedPkg.childPackageNames.size() : 0;
6935                    for (int i = 0; i < childCount; i++) {
6936                        String childPackageName = updatedPkg.childPackageNames.get(i);
6937                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6938                                childPackageName);
6939                        if (updatedChildPkg != null) {
6940                            updatedChildPkg.pkg = pkg;
6941                            updatedChildPkg.versionCode = pkg.mVersionCode;
6942                        }
6943                    }
6944
6945                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6946                            + scanFile + " ignored: updated version " + ps.versionCode
6947                            + " better than this " + pkg.mVersionCode);
6948                } else {
6949                    // The current app on the system partition is better than
6950                    // what we have updated to on the data partition; switch
6951                    // back to the system partition version.
6952                    // At this point, its safely assumed that package installation for
6953                    // apps in system partition will go through. If not there won't be a working
6954                    // version of the app
6955                    // writer
6956                    synchronized (mPackages) {
6957                        // Just remove the loaded entries from package lists.
6958                        mPackages.remove(ps.name);
6959                    }
6960
6961                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6962                            + " reverting from " + ps.codePathString
6963                            + ": new version " + pkg.mVersionCode
6964                            + " better than installed " + ps.versionCode);
6965
6966                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6967                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6968                    synchronized (mInstallLock) {
6969                        args.cleanUpResourcesLI();
6970                    }
6971                    synchronized (mPackages) {
6972                        mSettings.enableSystemPackageLPw(ps.name);
6973                    }
6974                    updatedPkgBetter = true;
6975                }
6976            }
6977        }
6978
6979        if (updatedPkg != null) {
6980            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6981            // initially
6982            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6983
6984            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6985            // flag set initially
6986            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6987                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6988            }
6989        }
6990
6991        // Verify certificates against what was last scanned
6992        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6993
6994        /*
6995         * A new system app appeared, but we already had a non-system one of the
6996         * same name installed earlier.
6997         */
6998        boolean shouldHideSystemApp = false;
6999        if (updatedPkg == null && ps != null
7000                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7001            /*
7002             * Check to make sure the signatures match first. If they don't,
7003             * wipe the installed application and its data.
7004             */
7005            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7006                    != PackageManager.SIGNATURE_MATCH) {
7007                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7008                        + " signatures don't match existing userdata copy; removing");
7009                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7010                        "scanPackageInternalLI")) {
7011                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7012                }
7013                ps = null;
7014            } else {
7015                /*
7016                 * If the newly-added system app is an older version than the
7017                 * already installed version, hide it. It will be scanned later
7018                 * and re-added like an update.
7019                 */
7020                if (pkg.mVersionCode <= ps.versionCode) {
7021                    shouldHideSystemApp = true;
7022                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7023                            + " but new version " + pkg.mVersionCode + " better than installed "
7024                            + ps.versionCode + "; hiding system");
7025                } else {
7026                    /*
7027                     * The newly found system app is a newer version that the
7028                     * one previously installed. Simply remove the
7029                     * already-installed application and replace it with our own
7030                     * while keeping the application data.
7031                     */
7032                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7033                            + " reverting from " + ps.codePathString + ": new version "
7034                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7035                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7036                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7037                    synchronized (mInstallLock) {
7038                        args.cleanUpResourcesLI();
7039                    }
7040                }
7041            }
7042        }
7043
7044        // The apk is forward locked (not public) if its code and resources
7045        // are kept in different files. (except for app in either system or
7046        // vendor path).
7047        // TODO grab this value from PackageSettings
7048        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7049            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7050                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7051            }
7052        }
7053
7054        // TODO: extend to support forward-locked splits
7055        String resourcePath = null;
7056        String baseResourcePath = null;
7057        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7058            if (ps != null && ps.resourcePathString != null) {
7059                resourcePath = ps.resourcePathString;
7060                baseResourcePath = ps.resourcePathString;
7061            } else {
7062                // Should not happen at all. Just log an error.
7063                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7064            }
7065        } else {
7066            resourcePath = pkg.codePath;
7067            baseResourcePath = pkg.baseCodePath;
7068        }
7069
7070        // Set application objects path explicitly.
7071        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7072        pkg.setApplicationInfoCodePath(pkg.codePath);
7073        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7074        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7075        pkg.setApplicationInfoResourcePath(resourcePath);
7076        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7077        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7078
7079        // Note that we invoke the following method only if we are about to unpack an application
7080        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7081                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7082
7083        /*
7084         * If the system app should be overridden by a previously installed
7085         * data, hide the system app now and let the /data/app scan pick it up
7086         * again.
7087         */
7088        if (shouldHideSystemApp) {
7089            synchronized (mPackages) {
7090                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7091            }
7092        }
7093
7094        return scannedPkg;
7095    }
7096
7097    private static String fixProcessName(String defProcessName,
7098            String processName, int uid) {
7099        if (processName == null) {
7100            return defProcessName;
7101        }
7102        return processName;
7103    }
7104
7105    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7106            throws PackageManagerException {
7107        if (pkgSetting.signatures.mSignatures != null) {
7108            // Already existing package. Make sure signatures match
7109            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7110                    == PackageManager.SIGNATURE_MATCH;
7111            if (!match) {
7112                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7113                        == PackageManager.SIGNATURE_MATCH;
7114            }
7115            if (!match) {
7116                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7117                        == PackageManager.SIGNATURE_MATCH;
7118            }
7119            if (!match) {
7120                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7121                        + pkg.packageName + " signatures do not match the "
7122                        + "previously installed version; ignoring!");
7123            }
7124        }
7125
7126        // Check for shared user signatures
7127        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7128            // Already existing package. Make sure signatures match
7129            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7130                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7131            if (!match) {
7132                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7133                        == PackageManager.SIGNATURE_MATCH;
7134            }
7135            if (!match) {
7136                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7137                        == PackageManager.SIGNATURE_MATCH;
7138            }
7139            if (!match) {
7140                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7141                        "Package " + pkg.packageName
7142                        + " has no signatures that match those in shared user "
7143                        + pkgSetting.sharedUser.name + "; ignoring!");
7144            }
7145        }
7146    }
7147
7148    /**
7149     * Enforces that only the system UID or root's UID can call a method exposed
7150     * via Binder.
7151     *
7152     * @param message used as message if SecurityException is thrown
7153     * @throws SecurityException if the caller is not system or root
7154     */
7155    private static final void enforceSystemOrRoot(String message) {
7156        final int uid = Binder.getCallingUid();
7157        if (uid != Process.SYSTEM_UID && uid != 0) {
7158            throw new SecurityException(message);
7159        }
7160    }
7161
7162    @Override
7163    public void performFstrimIfNeeded() {
7164        enforceSystemOrRoot("Only the system can request fstrim");
7165
7166        // Before everything else, see whether we need to fstrim.
7167        try {
7168            IMountService ms = PackageHelper.getMountService();
7169            if (ms != null) {
7170                final boolean isUpgrade = isUpgrade();
7171                boolean doTrim = isUpgrade;
7172                if (doTrim) {
7173                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7174                } else {
7175                    final long interval = android.provider.Settings.Global.getLong(
7176                            mContext.getContentResolver(),
7177                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7178                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7179                    if (interval > 0) {
7180                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7181                        if (timeSinceLast > interval) {
7182                            doTrim = true;
7183                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7184                                    + "; running immediately");
7185                        }
7186                    }
7187                }
7188                if (doTrim) {
7189                    if (!isFirstBoot()) {
7190                        try {
7191                            ActivityManagerNative.getDefault().showBootMessage(
7192                                    mContext.getResources().getString(
7193                                            R.string.android_upgrading_fstrim), true);
7194                        } catch (RemoteException e) {
7195                        }
7196                    }
7197                    ms.runMaintenance();
7198                }
7199            } else {
7200                Slog.e(TAG, "Mount service unavailable!");
7201            }
7202        } catch (RemoteException e) {
7203            // Can't happen; MountService is local
7204        }
7205    }
7206
7207    @Override
7208    public void updatePackagesIfNeeded() {
7209        enforceSystemOrRoot("Only the system can request package update");
7210
7211        // We need to re-extract after an OTA.
7212        boolean causeUpgrade = isUpgrade();
7213
7214        // First boot or factory reset.
7215        // Note: we also handle devices that are upgrading to N right now as if it is their
7216        //       first boot, as they do not have profile data.
7217        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7218
7219        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7220        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7221
7222        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7223            return;
7224        }
7225
7226        List<PackageParser.Package> pkgs;
7227        synchronized (mPackages) {
7228            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7229        }
7230
7231        int numberOfPackagesVisited = 0;
7232        int numberOfPackagesOptimized = 0;
7233        int numberOfPackagesSkipped = 0;
7234        int numberOfPackagesFailed = 0;
7235        final int numberOfPackagesToDexopt = pkgs.size();
7236        final long startTime = System.nanoTime();
7237
7238        for (PackageParser.Package pkg : pkgs) {
7239            numberOfPackagesVisited++;
7240
7241            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7242                if (DEBUG_DEXOPT) {
7243                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7244                }
7245                numberOfPackagesSkipped++;
7246                continue;
7247            }
7248
7249            if (DEBUG_DEXOPT) {
7250                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7251                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7252            }
7253
7254            if (mIsPreNUpgrade) {
7255                try {
7256                    ActivityManagerNative.getDefault().showBootMessage(
7257                            mContext.getResources().getString(R.string.android_upgrading_apk,
7258                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7259                } catch (RemoteException e) {
7260                }
7261            }
7262
7263            // checkProfiles is false to avoid merging profiles during boot which
7264            // might interfere with background compilation (b/28612421).
7265            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7266            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7267            // trade-off worth doing to save boot time work.
7268            int dexOptStatus = performDexOptTraced(pkg.packageName,
7269                    false /* checkProfiles */,
7270                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
7271                    false /* force */);
7272            switch (dexOptStatus) {
7273                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7274                    numberOfPackagesOptimized++;
7275                    break;
7276                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7277                    numberOfPackagesSkipped++;
7278                    break;
7279                case PackageDexOptimizer.DEX_OPT_FAILED:
7280                    numberOfPackagesFailed++;
7281                    break;
7282                default:
7283                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7284                    break;
7285            }
7286        }
7287
7288        final int elapsedTimeSeconds =
7289                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7290        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized);
7291        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped);
7292        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed);
7293        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7294        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7295    }
7296
7297    @Override
7298    public void notifyPackageUse(String packageName, int reason) {
7299        synchronized (mPackages) {
7300            PackageParser.Package p = mPackages.get(packageName);
7301            if (p == null) {
7302                return;
7303            }
7304            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7305        }
7306    }
7307
7308    // TODO: this is not used nor needed. Delete it.
7309    @Override
7310    public boolean performDexOptIfNeeded(String packageName) {
7311        int dexOptStatus = performDexOptTraced(packageName,
7312                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7313        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7314    }
7315
7316    @Override
7317    public boolean performDexOpt(String packageName,
7318            boolean checkProfiles, int compileReason, boolean force) {
7319        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7320                getCompilerFilterForReason(compileReason), force);
7321        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7322    }
7323
7324    @Override
7325    public boolean performDexOptMode(String packageName,
7326            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7327        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7328                targetCompilerFilter, force);
7329        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7330    }
7331
7332    private int performDexOptTraced(String packageName,
7333                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7334        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7335        try {
7336            return performDexOptInternal(packageName, checkProfiles,
7337                    targetCompilerFilter, force);
7338        } finally {
7339            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7340        }
7341    }
7342
7343    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7344    // if the package can now be considered up to date for the given filter.
7345    private int performDexOptInternal(String packageName,
7346                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7347        PackageParser.Package p;
7348        synchronized (mPackages) {
7349            p = mPackages.get(packageName);
7350            if (p == null) {
7351                // Package could not be found. Report failure.
7352                return PackageDexOptimizer.DEX_OPT_FAILED;
7353            }
7354            mPackageUsage.write(false);
7355        }
7356        long callingId = Binder.clearCallingIdentity();
7357        try {
7358            synchronized (mInstallLock) {
7359                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7360                        targetCompilerFilter, force);
7361            }
7362        } finally {
7363            Binder.restoreCallingIdentity(callingId);
7364        }
7365    }
7366
7367    public ArraySet<String> getOptimizablePackages() {
7368        ArraySet<String> pkgs = new ArraySet<String>();
7369        synchronized (mPackages) {
7370            for (PackageParser.Package p : mPackages.values()) {
7371                if (PackageDexOptimizer.canOptimizePackage(p)) {
7372                    pkgs.add(p.packageName);
7373                }
7374            }
7375        }
7376        return pkgs;
7377    }
7378
7379    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7380            boolean checkProfiles, String targetCompilerFilter,
7381            boolean force) {
7382        // Select the dex optimizer based on the force parameter.
7383        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7384        //       allocate an object here.
7385        PackageDexOptimizer pdo = force
7386                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7387                : mPackageDexOptimizer;
7388
7389        // Optimize all dependencies first. Note: we ignore the return value and march on
7390        // on errors.
7391        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7392        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7393        if (!deps.isEmpty()) {
7394            for (PackageParser.Package depPackage : deps) {
7395                // TODO: Analyze and investigate if we (should) profile libraries.
7396                // Currently this will do a full compilation of the library by default.
7397                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7398                        false /* checkProfiles */,
7399                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7400            }
7401        }
7402        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7403                targetCompilerFilter);
7404    }
7405
7406    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7407        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7408            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7409            Set<String> collectedNames = new HashSet<>();
7410            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7411
7412            retValue.remove(p);
7413
7414            return retValue;
7415        } else {
7416            return Collections.emptyList();
7417        }
7418    }
7419
7420    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7421            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7422        if (!collectedNames.contains(p.packageName)) {
7423            collectedNames.add(p.packageName);
7424            collected.add(p);
7425
7426            if (p.usesLibraries != null) {
7427                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7428            }
7429            if (p.usesOptionalLibraries != null) {
7430                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7431                        collectedNames);
7432            }
7433        }
7434    }
7435
7436    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7437            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7438        for (String libName : libs) {
7439            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7440            if (libPkg != null) {
7441                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7442            }
7443        }
7444    }
7445
7446    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7447        synchronized (mPackages) {
7448            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7449            if (lib != null && lib.apk != null) {
7450                return mPackages.get(lib.apk);
7451            }
7452        }
7453        return null;
7454    }
7455
7456    public void shutdown() {
7457        mPackageUsage.write(true);
7458    }
7459
7460    @Override
7461    public void forceDexOpt(String packageName) {
7462        enforceSystemOrRoot("forceDexOpt");
7463
7464        PackageParser.Package pkg;
7465        synchronized (mPackages) {
7466            pkg = mPackages.get(packageName);
7467            if (pkg == null) {
7468                throw new IllegalArgumentException("Unknown package: " + packageName);
7469            }
7470        }
7471
7472        synchronized (mInstallLock) {
7473            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7474
7475            // Whoever is calling forceDexOpt wants a fully compiled package.
7476            // Don't use profiles since that may cause compilation to be skipped.
7477            final int res = performDexOptInternalWithDependenciesLI(pkg,
7478                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7479                    true /* force */);
7480
7481            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7482            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7483                throw new IllegalStateException("Failed to dexopt: " + res);
7484            }
7485        }
7486    }
7487
7488    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7489        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7490            Slog.w(TAG, "Unable to update from " + oldPkg.name
7491                    + " to " + newPkg.packageName
7492                    + ": old package not in system partition");
7493            return false;
7494        } else if (mPackages.get(oldPkg.name) != null) {
7495            Slog.w(TAG, "Unable to update from " + oldPkg.name
7496                    + " to " + newPkg.packageName
7497                    + ": old package still exists");
7498            return false;
7499        }
7500        return true;
7501    }
7502
7503    void removeCodePathLI(File codePath) {
7504        if (codePath.isDirectory()) {
7505            try {
7506                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7507            } catch (InstallerException e) {
7508                Slog.w(TAG, "Failed to remove code path", e);
7509            }
7510        } else {
7511            codePath.delete();
7512        }
7513    }
7514
7515    private int[] resolveUserIds(int userId) {
7516        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7517    }
7518
7519    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7520        if (pkg == null) {
7521            Slog.wtf(TAG, "Package was null!", new Throwable());
7522            return;
7523        }
7524        clearAppDataLeafLIF(pkg, userId, flags);
7525        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7526        for (int i = 0; i < childCount; i++) {
7527            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7528        }
7529    }
7530
7531    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7532        final PackageSetting ps;
7533        synchronized (mPackages) {
7534            ps = mSettings.mPackages.get(pkg.packageName);
7535        }
7536        for (int realUserId : resolveUserIds(userId)) {
7537            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7538            try {
7539                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7540                        ceDataInode);
7541            } catch (InstallerException e) {
7542                Slog.w(TAG, String.valueOf(e));
7543            }
7544        }
7545    }
7546
7547    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7548        if (pkg == null) {
7549            Slog.wtf(TAG, "Package was null!", new Throwable());
7550            return;
7551        }
7552        destroyAppDataLeafLIF(pkg, userId, flags);
7553        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7554        for (int i = 0; i < childCount; i++) {
7555            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7556        }
7557    }
7558
7559    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7560        final PackageSetting ps;
7561        synchronized (mPackages) {
7562            ps = mSettings.mPackages.get(pkg.packageName);
7563        }
7564        for (int realUserId : resolveUserIds(userId)) {
7565            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7566            try {
7567                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7568                        ceDataInode);
7569            } catch (InstallerException e) {
7570                Slog.w(TAG, String.valueOf(e));
7571            }
7572        }
7573    }
7574
7575    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7576        if (pkg == null) {
7577            Slog.wtf(TAG, "Package was null!", new Throwable());
7578            return;
7579        }
7580        destroyAppProfilesLeafLIF(pkg);
7581        destroyAppReferenceProfileLeafLIF(pkg, userId);
7582        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7583        for (int i = 0; i < childCount; i++) {
7584            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7585            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId);
7586        }
7587    }
7588
7589    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) {
7590        if (pkg.isForwardLocked()) {
7591            return;
7592        }
7593
7594        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7595            try {
7596                path = PackageManagerServiceUtils.realpath(new File(path));
7597            } catch (IOException e) {
7598                // TODO: Should we return early here ?
7599                Slog.w(TAG, "Failed to get canonical path", e);
7600                continue;
7601            }
7602
7603            final String useMarker = path.replace('/', '@');
7604            for (int realUserId : resolveUserIds(userId)) {
7605                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7606                File foreignUseMark = new File(profileDir, useMarker);
7607                if (foreignUseMark.exists()) {
7608                    if (!foreignUseMark.delete()) {
7609                        Slog.w(TAG, "Unable to delete foreign user mark for package: "
7610                            + pkg.packageName);
7611                    }
7612                }
7613
7614                File[] markers = profileDir.listFiles();
7615                if (markers != null) {
7616                    final String searchString = "@" + pkg.packageName + "@";
7617                    // We also delete all markers that contain the package name we're
7618                    // uninstalling. These are associated with secondary dex-files belonging
7619                    // to the package. Reconstructing the path of these dex files is messy
7620                    // in general.
7621                    for (File marker : markers) {
7622                        if (marker.getName().indexOf(searchString) > 0) {
7623                            if (!marker.delete()) {
7624                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7625                                    + pkg.packageName);
7626                            }
7627                        }
7628                    }
7629                }
7630            }
7631        }
7632    }
7633
7634    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7635        try {
7636            mInstaller.destroyAppProfiles(pkg.packageName);
7637        } catch (InstallerException e) {
7638            Slog.w(TAG, String.valueOf(e));
7639        }
7640    }
7641
7642    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7643        if (pkg == null) {
7644            Slog.wtf(TAG, "Package was null!", new Throwable());
7645            return;
7646        }
7647        clearAppProfilesLeafLIF(pkg);
7648        destroyAppReferenceProfileLeafLIF(pkg, userId);
7649        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7650        for (int i = 0; i < childCount; i++) {
7651            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7652        }
7653    }
7654
7655    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7656        try {
7657            mInstaller.clearAppProfiles(pkg.packageName);
7658        } catch (InstallerException e) {
7659            Slog.w(TAG, String.valueOf(e));
7660        }
7661    }
7662
7663    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7664            long lastUpdateTime) {
7665        // Set parent install/update time
7666        PackageSetting ps = (PackageSetting) pkg.mExtras;
7667        if (ps != null) {
7668            ps.firstInstallTime = firstInstallTime;
7669            ps.lastUpdateTime = lastUpdateTime;
7670        }
7671        // Set children install/update time
7672        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7673        for (int i = 0; i < childCount; i++) {
7674            PackageParser.Package childPkg = pkg.childPackages.get(i);
7675            ps = (PackageSetting) childPkg.mExtras;
7676            if (ps != null) {
7677                ps.firstInstallTime = firstInstallTime;
7678                ps.lastUpdateTime = lastUpdateTime;
7679            }
7680        }
7681    }
7682
7683    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7684            PackageParser.Package changingLib) {
7685        if (file.path != null) {
7686            usesLibraryFiles.add(file.path);
7687            return;
7688        }
7689        PackageParser.Package p = mPackages.get(file.apk);
7690        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7691            // If we are doing this while in the middle of updating a library apk,
7692            // then we need to make sure to use that new apk for determining the
7693            // dependencies here.  (We haven't yet finished committing the new apk
7694            // to the package manager state.)
7695            if (p == null || p.packageName.equals(changingLib.packageName)) {
7696                p = changingLib;
7697            }
7698        }
7699        if (p != null) {
7700            usesLibraryFiles.addAll(p.getAllCodePaths());
7701        }
7702    }
7703
7704    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7705            PackageParser.Package changingLib) throws PackageManagerException {
7706        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7707            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7708            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7709            for (int i=0; i<N; i++) {
7710                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7711                if (file == null) {
7712                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7713                            "Package " + pkg.packageName + " requires unavailable shared library "
7714                            + pkg.usesLibraries.get(i) + "; failing!");
7715                }
7716                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7717            }
7718            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7719            for (int i=0; i<N; i++) {
7720                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7721                if (file == null) {
7722                    Slog.w(TAG, "Package " + pkg.packageName
7723                            + " desires unavailable shared library "
7724                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7725                } else {
7726                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7727                }
7728            }
7729            N = usesLibraryFiles.size();
7730            if (N > 0) {
7731                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7732            } else {
7733                pkg.usesLibraryFiles = null;
7734            }
7735        }
7736    }
7737
7738    private static boolean hasString(List<String> list, List<String> which) {
7739        if (list == null) {
7740            return false;
7741        }
7742        for (int i=list.size()-1; i>=0; i--) {
7743            for (int j=which.size()-1; j>=0; j--) {
7744                if (which.get(j).equals(list.get(i))) {
7745                    return true;
7746                }
7747            }
7748        }
7749        return false;
7750    }
7751
7752    private void updateAllSharedLibrariesLPw() {
7753        for (PackageParser.Package pkg : mPackages.values()) {
7754            try {
7755                updateSharedLibrariesLPw(pkg, null);
7756            } catch (PackageManagerException e) {
7757                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7758            }
7759        }
7760    }
7761
7762    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7763            PackageParser.Package changingPkg) {
7764        ArrayList<PackageParser.Package> res = null;
7765        for (PackageParser.Package pkg : mPackages.values()) {
7766            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7767                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7768                if (res == null) {
7769                    res = new ArrayList<PackageParser.Package>();
7770                }
7771                res.add(pkg);
7772                try {
7773                    updateSharedLibrariesLPw(pkg, changingPkg);
7774                } catch (PackageManagerException e) {
7775                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7776                }
7777            }
7778        }
7779        return res;
7780    }
7781
7782    /**
7783     * Derive the value of the {@code cpuAbiOverride} based on the provided
7784     * value and an optional stored value from the package settings.
7785     */
7786    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7787        String cpuAbiOverride = null;
7788
7789        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7790            cpuAbiOverride = null;
7791        } else if (abiOverride != null) {
7792            cpuAbiOverride = abiOverride;
7793        } else if (settings != null) {
7794            cpuAbiOverride = settings.cpuAbiOverrideString;
7795        }
7796
7797        return cpuAbiOverride;
7798    }
7799
7800    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7801            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7802                    throws PackageManagerException {
7803        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7804        // If the package has children and this is the first dive in the function
7805        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7806        // whether all packages (parent and children) would be successfully scanned
7807        // before the actual scan since scanning mutates internal state and we want
7808        // to atomically install the package and its children.
7809        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7810            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7811                scanFlags |= SCAN_CHECK_ONLY;
7812            }
7813        } else {
7814            scanFlags &= ~SCAN_CHECK_ONLY;
7815        }
7816
7817        final PackageParser.Package scannedPkg;
7818        try {
7819            // Scan the parent
7820            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7821            // Scan the children
7822            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7823            for (int i = 0; i < childCount; i++) {
7824                PackageParser.Package childPkg = pkg.childPackages.get(i);
7825                scanPackageLI(childPkg, policyFlags,
7826                        scanFlags, currentTime, user);
7827            }
7828        } finally {
7829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7830        }
7831
7832        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7833            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7834        }
7835
7836        return scannedPkg;
7837    }
7838
7839    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7840            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7841        boolean success = false;
7842        try {
7843            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7844                    currentTime, user);
7845            success = true;
7846            return res;
7847        } finally {
7848            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7849                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7850                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7851                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7852                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7853            }
7854        }
7855    }
7856
7857    /**
7858     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7859     */
7860    private static boolean apkHasCode(String fileName) {
7861        StrictJarFile jarFile = null;
7862        try {
7863            jarFile = new StrictJarFile(fileName,
7864                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7865            return jarFile.findEntry("classes.dex") != null;
7866        } catch (IOException ignore) {
7867        } finally {
7868            try {
7869                jarFile.close();
7870            } catch (IOException ignore) {}
7871        }
7872        return false;
7873    }
7874
7875    /**
7876     * Enforces code policy for the package. This ensures that if an APK has
7877     * declared hasCode="true" in its manifest that the APK actually contains
7878     * code.
7879     *
7880     * @throws PackageManagerException If bytecode could not be found when it should exist
7881     */
7882    private static void enforceCodePolicy(PackageParser.Package pkg)
7883            throws PackageManagerException {
7884        final boolean shouldHaveCode =
7885                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7886        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7887            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7888                    "Package " + pkg.baseCodePath + " code is missing");
7889        }
7890
7891        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7892            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7893                final boolean splitShouldHaveCode =
7894                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7895                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7896                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7897                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7898                }
7899            }
7900        }
7901    }
7902
7903    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7904            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7905            throws PackageManagerException {
7906        final File scanFile = new File(pkg.codePath);
7907        if (pkg.applicationInfo.getCodePath() == null ||
7908                pkg.applicationInfo.getResourcePath() == null) {
7909            // Bail out. The resource and code paths haven't been set.
7910            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7911                    "Code and resource paths haven't been set correctly");
7912        }
7913
7914        // Apply policy
7915        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7916            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7917            if (pkg.applicationInfo.isDirectBootAware()) {
7918                // we're direct boot aware; set for all components
7919                for (PackageParser.Service s : pkg.services) {
7920                    s.info.encryptionAware = s.info.directBootAware = true;
7921                }
7922                for (PackageParser.Provider p : pkg.providers) {
7923                    p.info.encryptionAware = p.info.directBootAware = true;
7924                }
7925                for (PackageParser.Activity a : pkg.activities) {
7926                    a.info.encryptionAware = a.info.directBootAware = true;
7927                }
7928                for (PackageParser.Activity r : pkg.receivers) {
7929                    r.info.encryptionAware = r.info.directBootAware = true;
7930                }
7931            }
7932        } else {
7933            // Only allow system apps to be flagged as core apps.
7934            pkg.coreApp = false;
7935            // clear flags not applicable to regular apps
7936            pkg.applicationInfo.privateFlags &=
7937                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7938            pkg.applicationInfo.privateFlags &=
7939                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7940        }
7941        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7942
7943        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7944            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7945        }
7946
7947        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7948            enforceCodePolicy(pkg);
7949        }
7950
7951        if (mCustomResolverComponentName != null &&
7952                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7953            setUpCustomResolverActivity(pkg);
7954        }
7955
7956        if (pkg.packageName.equals("android")) {
7957            synchronized (mPackages) {
7958                if (mAndroidApplication != null) {
7959                    Slog.w(TAG, "*************************************************");
7960                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7961                    Slog.w(TAG, " file=" + scanFile);
7962                    Slog.w(TAG, "*************************************************");
7963                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7964                            "Core android package being redefined.  Skipping.");
7965                }
7966
7967                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7968                    // Set up information for our fall-back user intent resolution activity.
7969                    mPlatformPackage = pkg;
7970                    pkg.mVersionCode = mSdkVersion;
7971                    mAndroidApplication = pkg.applicationInfo;
7972
7973                    if (!mResolverReplaced) {
7974                        mResolveActivity.applicationInfo = mAndroidApplication;
7975                        mResolveActivity.name = ResolverActivity.class.getName();
7976                        mResolveActivity.packageName = mAndroidApplication.packageName;
7977                        mResolveActivity.processName = "system:ui";
7978                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7979                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7980                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7981                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7982                        mResolveActivity.exported = true;
7983                        mResolveActivity.enabled = true;
7984                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7985                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7986                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7987                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7988                                | ActivityInfo.CONFIG_ORIENTATION
7989                                | ActivityInfo.CONFIG_KEYBOARD
7990                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7991                        mResolveInfo.activityInfo = mResolveActivity;
7992                        mResolveInfo.priority = 0;
7993                        mResolveInfo.preferredOrder = 0;
7994                        mResolveInfo.match = 0;
7995                        mResolveComponentName = new ComponentName(
7996                                mAndroidApplication.packageName, mResolveActivity.name);
7997                    }
7998                }
7999            }
8000        }
8001
8002        if (DEBUG_PACKAGE_SCANNING) {
8003            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8004                Log.d(TAG, "Scanning package " + pkg.packageName);
8005        }
8006
8007        synchronized (mPackages) {
8008            if (mPackages.containsKey(pkg.packageName)
8009                    || mSharedLibraries.containsKey(pkg.packageName)) {
8010                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8011                        "Application package " + pkg.packageName
8012                                + " already installed.  Skipping duplicate.");
8013            }
8014
8015            // If we're only installing presumed-existing packages, require that the
8016            // scanned APK is both already known and at the path previously established
8017            // for it.  Previously unknown packages we pick up normally, but if we have an
8018            // a priori expectation about this package's install presence, enforce it.
8019            // With a singular exception for new system packages. When an OTA contains
8020            // a new system package, we allow the codepath to change from a system location
8021            // to the user-installed location. If we don't allow this change, any newer,
8022            // user-installed version of the application will be ignored.
8023            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8024                if (mExpectingBetter.containsKey(pkg.packageName)) {
8025                    logCriticalInfo(Log.WARN,
8026                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8027                } else {
8028                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8029                    if (known != null) {
8030                        if (DEBUG_PACKAGE_SCANNING) {
8031                            Log.d(TAG, "Examining " + pkg.codePath
8032                                    + " and requiring known paths " + known.codePathString
8033                                    + " & " + known.resourcePathString);
8034                        }
8035                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8036                                || !pkg.applicationInfo.getResourcePath().equals(
8037                                known.resourcePathString)) {
8038                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8039                                    "Application package " + pkg.packageName
8040                                            + " found at " + pkg.applicationInfo.getCodePath()
8041                                            + " but expected at " + known.codePathString
8042                                            + "; ignoring.");
8043                        }
8044                    }
8045                }
8046            }
8047        }
8048
8049        // Initialize package source and resource directories
8050        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8051        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8052
8053        SharedUserSetting suid = null;
8054        PackageSetting pkgSetting = null;
8055
8056        if (!isSystemApp(pkg)) {
8057            // Only system apps can use these features.
8058            pkg.mOriginalPackages = null;
8059            pkg.mRealPackage = null;
8060            pkg.mAdoptPermissions = null;
8061        }
8062
8063        // Getting the package setting may have a side-effect, so if we
8064        // are only checking if scan would succeed, stash a copy of the
8065        // old setting to restore at the end.
8066        PackageSetting nonMutatedPs = null;
8067
8068        // writer
8069        synchronized (mPackages) {
8070            if (pkg.mSharedUserId != null) {
8071                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8072                if (suid == null) {
8073                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8074                            "Creating application package " + pkg.packageName
8075                            + " for shared user failed");
8076                }
8077                if (DEBUG_PACKAGE_SCANNING) {
8078                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8079                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8080                                + "): packages=" + suid.packages);
8081                }
8082            }
8083
8084            // Check if we are renaming from an original package name.
8085            PackageSetting origPackage = null;
8086            String realName = null;
8087            if (pkg.mOriginalPackages != null) {
8088                // This package may need to be renamed to a previously
8089                // installed name.  Let's check on that...
8090                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8091                if (pkg.mOriginalPackages.contains(renamed)) {
8092                    // This package had originally been installed as the
8093                    // original name, and we have already taken care of
8094                    // transitioning to the new one.  Just update the new
8095                    // one to continue using the old name.
8096                    realName = pkg.mRealPackage;
8097                    if (!pkg.packageName.equals(renamed)) {
8098                        // Callers into this function may have already taken
8099                        // care of renaming the package; only do it here if
8100                        // it is not already done.
8101                        pkg.setPackageName(renamed);
8102                    }
8103
8104                } else {
8105                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8106                        if ((origPackage = mSettings.peekPackageLPr(
8107                                pkg.mOriginalPackages.get(i))) != null) {
8108                            // We do have the package already installed under its
8109                            // original name...  should we use it?
8110                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8111                                // New package is not compatible with original.
8112                                origPackage = null;
8113                                continue;
8114                            } else if (origPackage.sharedUser != null) {
8115                                // Make sure uid is compatible between packages.
8116                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8117                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8118                                            + " to " + pkg.packageName + ": old uid "
8119                                            + origPackage.sharedUser.name
8120                                            + " differs from " + pkg.mSharedUserId);
8121                                    origPackage = null;
8122                                    continue;
8123                                }
8124                                // TODO: Add case when shared user id is added [b/28144775]
8125                            } else {
8126                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8127                                        + pkg.packageName + " to old name " + origPackage.name);
8128                            }
8129                            break;
8130                        }
8131                    }
8132                }
8133            }
8134
8135            if (mTransferedPackages.contains(pkg.packageName)) {
8136                Slog.w(TAG, "Package " + pkg.packageName
8137                        + " was transferred to another, but its .apk remains");
8138            }
8139
8140            // See comments in nonMutatedPs declaration
8141            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8142                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8143                if (foundPs != null) {
8144                    nonMutatedPs = new PackageSetting(foundPs);
8145                }
8146            }
8147
8148            // Just create the setting, don't add it yet. For already existing packages
8149            // the PkgSetting exists already and doesn't have to be created.
8150            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8151                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8152                    pkg.applicationInfo.primaryCpuAbi,
8153                    pkg.applicationInfo.secondaryCpuAbi,
8154                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8155                    user, false);
8156            if (pkgSetting == null) {
8157                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8158                        "Creating application package " + pkg.packageName + " failed");
8159            }
8160
8161            if (pkgSetting.origPackage != null) {
8162                // If we are first transitioning from an original package,
8163                // fix up the new package's name now.  We need to do this after
8164                // looking up the package under its new name, so getPackageLP
8165                // can take care of fiddling things correctly.
8166                pkg.setPackageName(origPackage.name);
8167
8168                // File a report about this.
8169                String msg = "New package " + pkgSetting.realName
8170                        + " renamed to replace old package " + pkgSetting.name;
8171                reportSettingsProblem(Log.WARN, msg);
8172
8173                // Make a note of it.
8174                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8175                    mTransferedPackages.add(origPackage.name);
8176                }
8177
8178                // No longer need to retain this.
8179                pkgSetting.origPackage = null;
8180            }
8181
8182            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8183                // Make a note of it.
8184                mTransferedPackages.add(pkg.packageName);
8185            }
8186
8187            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8188                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8189            }
8190
8191            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8192                // Check all shared libraries and map to their actual file path.
8193                // We only do this here for apps not on a system dir, because those
8194                // are the only ones that can fail an install due to this.  We
8195                // will take care of the system apps by updating all of their
8196                // library paths after the scan is done.
8197                updateSharedLibrariesLPw(pkg, null);
8198            }
8199
8200            if (mFoundPolicyFile) {
8201                SELinuxMMAC.assignSeinfoValue(pkg);
8202            }
8203
8204            pkg.applicationInfo.uid = pkgSetting.appId;
8205            pkg.mExtras = pkgSetting;
8206            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8207                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8208                    // We just determined the app is signed correctly, so bring
8209                    // over the latest parsed certs.
8210                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8211                } else {
8212                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8213                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8214                                "Package " + pkg.packageName + " upgrade keys do not match the "
8215                                + "previously installed version");
8216                    } else {
8217                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8218                        String msg = "System package " + pkg.packageName
8219                            + " signature changed; retaining data.";
8220                        reportSettingsProblem(Log.WARN, msg);
8221                    }
8222                }
8223            } else {
8224                try {
8225                    verifySignaturesLP(pkgSetting, pkg);
8226                    // We just determined the app is signed correctly, so bring
8227                    // over the latest parsed certs.
8228                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8229                } catch (PackageManagerException e) {
8230                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8231                        throw e;
8232                    }
8233                    // The signature has changed, but this package is in the system
8234                    // image...  let's recover!
8235                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8236                    // However...  if this package is part of a shared user, but it
8237                    // doesn't match the signature of the shared user, let's fail.
8238                    // What this means is that you can't change the signatures
8239                    // associated with an overall shared user, which doesn't seem all
8240                    // that unreasonable.
8241                    if (pkgSetting.sharedUser != null) {
8242                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8243                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8244                            throw new PackageManagerException(
8245                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8246                                            "Signature mismatch for shared user: "
8247                                            + pkgSetting.sharedUser);
8248                        }
8249                    }
8250                    // File a report about this.
8251                    String msg = "System package " + pkg.packageName
8252                        + " signature changed; retaining data.";
8253                    reportSettingsProblem(Log.WARN, msg);
8254                }
8255            }
8256            // Verify that this new package doesn't have any content providers
8257            // that conflict with existing packages.  Only do this if the
8258            // package isn't already installed, since we don't want to break
8259            // things that are installed.
8260            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8261                final int N = pkg.providers.size();
8262                int i;
8263                for (i=0; i<N; i++) {
8264                    PackageParser.Provider p = pkg.providers.get(i);
8265                    if (p.info.authority != null) {
8266                        String names[] = p.info.authority.split(";");
8267                        for (int j = 0; j < names.length; j++) {
8268                            if (mProvidersByAuthority.containsKey(names[j])) {
8269                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8270                                final String otherPackageName =
8271                                        ((other != null && other.getComponentName() != null) ?
8272                                                other.getComponentName().getPackageName() : "?");
8273                                throw new PackageManagerException(
8274                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8275                                                "Can't install because provider name " + names[j]
8276                                                + " (in package " + pkg.applicationInfo.packageName
8277                                                + ") is already used by " + otherPackageName);
8278                            }
8279                        }
8280                    }
8281                }
8282            }
8283
8284            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8285                // This package wants to adopt ownership of permissions from
8286                // another package.
8287                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8288                    final String origName = pkg.mAdoptPermissions.get(i);
8289                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8290                    if (orig != null) {
8291                        if (verifyPackageUpdateLPr(orig, pkg)) {
8292                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8293                                    + pkg.packageName);
8294                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8295                        }
8296                    }
8297                }
8298            }
8299        }
8300
8301        final String pkgName = pkg.packageName;
8302
8303        final long scanFileTime = scanFile.lastModified();
8304        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8305        pkg.applicationInfo.processName = fixProcessName(
8306                pkg.applicationInfo.packageName,
8307                pkg.applicationInfo.processName,
8308                pkg.applicationInfo.uid);
8309
8310        if (pkg != mPlatformPackage) {
8311            // Get all of our default paths setup
8312            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8313        }
8314
8315        final String path = scanFile.getPath();
8316        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8317
8318        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8319            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8320
8321            // Some system apps still use directory structure for native libraries
8322            // in which case we might end up not detecting abi solely based on apk
8323            // structure. Try to detect abi based on directory structure.
8324            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8325                    pkg.applicationInfo.primaryCpuAbi == null) {
8326                setBundledAppAbisAndRoots(pkg, pkgSetting);
8327                setNativeLibraryPaths(pkg);
8328            }
8329
8330        } else {
8331            if ((scanFlags & SCAN_MOVE) != 0) {
8332                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8333                // but we already have this packages package info in the PackageSetting. We just
8334                // use that and derive the native library path based on the new codepath.
8335                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8336                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8337            }
8338
8339            // Set native library paths again. For moves, the path will be updated based on the
8340            // ABIs we've determined above. For non-moves, the path will be updated based on the
8341            // ABIs we determined during compilation, but the path will depend on the final
8342            // package path (after the rename away from the stage path).
8343            setNativeLibraryPaths(pkg);
8344        }
8345
8346        // This is a special case for the "system" package, where the ABI is
8347        // dictated by the zygote configuration (and init.rc). We should keep track
8348        // of this ABI so that we can deal with "normal" applications that run under
8349        // the same UID correctly.
8350        if (mPlatformPackage == pkg) {
8351            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8352                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8353        }
8354
8355        // If there's a mismatch between the abi-override in the package setting
8356        // and the abiOverride specified for the install. Warn about this because we
8357        // would've already compiled the app without taking the package setting into
8358        // account.
8359        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8360            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8361                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8362                        " for package " + pkg.packageName);
8363            }
8364        }
8365
8366        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8367        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8368        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8369
8370        // Copy the derived override back to the parsed package, so that we can
8371        // update the package settings accordingly.
8372        pkg.cpuAbiOverride = cpuAbiOverride;
8373
8374        if (DEBUG_ABI_SELECTION) {
8375            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8376                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8377                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8378        }
8379
8380        // Push the derived path down into PackageSettings so we know what to
8381        // clean up at uninstall time.
8382        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8383
8384        if (DEBUG_ABI_SELECTION) {
8385            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8386                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8387                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8388        }
8389
8390        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8391            // We don't do this here during boot because we can do it all
8392            // at once after scanning all existing packages.
8393            //
8394            // We also do this *before* we perform dexopt on this package, so that
8395            // we can avoid redundant dexopts, and also to make sure we've got the
8396            // code and package path correct.
8397            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8398                    pkg, true /* boot complete */);
8399        }
8400
8401        if (mFactoryTest && pkg.requestedPermissions.contains(
8402                android.Manifest.permission.FACTORY_TEST)) {
8403            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8404        }
8405
8406        ArrayList<PackageParser.Package> clientLibPkgs = null;
8407
8408        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8409            if (nonMutatedPs != null) {
8410                synchronized (mPackages) {
8411                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8412                }
8413            }
8414            return pkg;
8415        }
8416
8417        // Only privileged apps and updated privileged apps can add child packages.
8418        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8419            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8420                throw new PackageManagerException("Only privileged apps and updated "
8421                        + "privileged apps can add child packages. Ignoring package "
8422                        + pkg.packageName);
8423            }
8424            final int childCount = pkg.childPackages.size();
8425            for (int i = 0; i < childCount; i++) {
8426                PackageParser.Package childPkg = pkg.childPackages.get(i);
8427                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8428                        childPkg.packageName)) {
8429                    throw new PackageManagerException("Cannot override a child package of "
8430                            + "another disabled system app. Ignoring package " + pkg.packageName);
8431                }
8432            }
8433        }
8434
8435        // writer
8436        synchronized (mPackages) {
8437            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8438                // Only system apps can add new shared libraries.
8439                if (pkg.libraryNames != null) {
8440                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8441                        String name = pkg.libraryNames.get(i);
8442                        boolean allowed = false;
8443                        if (pkg.isUpdatedSystemApp()) {
8444                            // New library entries can only be added through the
8445                            // system image.  This is important to get rid of a lot
8446                            // of nasty edge cases: for example if we allowed a non-
8447                            // system update of the app to add a library, then uninstalling
8448                            // the update would make the library go away, and assumptions
8449                            // we made such as through app install filtering would now
8450                            // have allowed apps on the device which aren't compatible
8451                            // with it.  Better to just have the restriction here, be
8452                            // conservative, and create many fewer cases that can negatively
8453                            // impact the user experience.
8454                            final PackageSetting sysPs = mSettings
8455                                    .getDisabledSystemPkgLPr(pkg.packageName);
8456                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8457                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8458                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8459                                        allowed = true;
8460                                        break;
8461                                    }
8462                                }
8463                            }
8464                        } else {
8465                            allowed = true;
8466                        }
8467                        if (allowed) {
8468                            if (!mSharedLibraries.containsKey(name)) {
8469                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8470                            } else if (!name.equals(pkg.packageName)) {
8471                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8472                                        + name + " already exists; skipping");
8473                            }
8474                        } else {
8475                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8476                                    + name + " that is not declared on system image; skipping");
8477                        }
8478                    }
8479                    if ((scanFlags & SCAN_BOOTING) == 0) {
8480                        // If we are not booting, we need to update any applications
8481                        // that are clients of our shared library.  If we are booting,
8482                        // this will all be done once the scan is complete.
8483                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8484                    }
8485                }
8486            }
8487        }
8488
8489        if ((scanFlags & SCAN_BOOTING) != 0) {
8490            // No apps can run during boot scan, so they don't need to be frozen
8491        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8492            // Caller asked to not kill app, so it's probably not frozen
8493        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8494            // Caller asked us to ignore frozen check for some reason; they
8495            // probably didn't know the package name
8496        } else {
8497            // We're doing major surgery on this package, so it better be frozen
8498            // right now to keep it from launching
8499            checkPackageFrozen(pkgName);
8500        }
8501
8502        // Also need to kill any apps that are dependent on the library.
8503        if (clientLibPkgs != null) {
8504            for (int i=0; i<clientLibPkgs.size(); i++) {
8505                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8506                killApplication(clientPkg.applicationInfo.packageName,
8507                        clientPkg.applicationInfo.uid, "update lib");
8508            }
8509        }
8510
8511        // Make sure we're not adding any bogus keyset info
8512        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8513        ksms.assertScannedPackageValid(pkg);
8514
8515        // writer
8516        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8517
8518        boolean createIdmapFailed = false;
8519        synchronized (mPackages) {
8520            // We don't expect installation to fail beyond this point
8521
8522            // Add the new setting to mSettings
8523            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8524            // Add the new setting to mPackages
8525            mPackages.put(pkg.applicationInfo.packageName, pkg);
8526            // Make sure we don't accidentally delete its data.
8527            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8528            while (iter.hasNext()) {
8529                PackageCleanItem item = iter.next();
8530                if (pkgName.equals(item.packageName)) {
8531                    iter.remove();
8532                }
8533            }
8534
8535            // Take care of first install / last update times.
8536            if (currentTime != 0) {
8537                if (pkgSetting.firstInstallTime == 0) {
8538                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8539                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8540                    pkgSetting.lastUpdateTime = currentTime;
8541                }
8542            } else if (pkgSetting.firstInstallTime == 0) {
8543                // We need *something*.  Take time time stamp of the file.
8544                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8545            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8546                if (scanFileTime != pkgSetting.timeStamp) {
8547                    // A package on the system image has changed; consider this
8548                    // to be an update.
8549                    pkgSetting.lastUpdateTime = scanFileTime;
8550                }
8551            }
8552
8553            // Add the package's KeySets to the global KeySetManagerService
8554            ksms.addScannedPackageLPw(pkg);
8555
8556            int N = pkg.providers.size();
8557            StringBuilder r = null;
8558            int i;
8559            for (i=0; i<N; i++) {
8560                PackageParser.Provider p = pkg.providers.get(i);
8561                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8562                        p.info.processName, pkg.applicationInfo.uid);
8563                mProviders.addProvider(p);
8564                p.syncable = p.info.isSyncable;
8565                if (p.info.authority != null) {
8566                    String names[] = p.info.authority.split(";");
8567                    p.info.authority = null;
8568                    for (int j = 0; j < names.length; j++) {
8569                        if (j == 1 && p.syncable) {
8570                            // We only want the first authority for a provider to possibly be
8571                            // syncable, so if we already added this provider using a different
8572                            // authority clear the syncable flag. We copy the provider before
8573                            // changing it because the mProviders object contains a reference
8574                            // to a provider that we don't want to change.
8575                            // Only do this for the second authority since the resulting provider
8576                            // object can be the same for all future authorities for this provider.
8577                            p = new PackageParser.Provider(p);
8578                            p.syncable = false;
8579                        }
8580                        if (!mProvidersByAuthority.containsKey(names[j])) {
8581                            mProvidersByAuthority.put(names[j], p);
8582                            if (p.info.authority == null) {
8583                                p.info.authority = names[j];
8584                            } else {
8585                                p.info.authority = p.info.authority + ";" + names[j];
8586                            }
8587                            if (DEBUG_PACKAGE_SCANNING) {
8588                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8589                                    Log.d(TAG, "Registered content provider: " + names[j]
8590                                            + ", className = " + p.info.name + ", isSyncable = "
8591                                            + p.info.isSyncable);
8592                            }
8593                        } else {
8594                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8595                            Slog.w(TAG, "Skipping provider name " + names[j] +
8596                                    " (in package " + pkg.applicationInfo.packageName +
8597                                    "): name already used by "
8598                                    + ((other != null && other.getComponentName() != null)
8599                                            ? other.getComponentName().getPackageName() : "?"));
8600                        }
8601                    }
8602                }
8603                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8604                    if (r == null) {
8605                        r = new StringBuilder(256);
8606                    } else {
8607                        r.append(' ');
8608                    }
8609                    r.append(p.info.name);
8610                }
8611            }
8612            if (r != null) {
8613                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8614            }
8615
8616            N = pkg.services.size();
8617            r = null;
8618            for (i=0; i<N; i++) {
8619                PackageParser.Service s = pkg.services.get(i);
8620                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8621                        s.info.processName, pkg.applicationInfo.uid);
8622                mServices.addService(s);
8623                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8624                    if (r == null) {
8625                        r = new StringBuilder(256);
8626                    } else {
8627                        r.append(' ');
8628                    }
8629                    r.append(s.info.name);
8630                }
8631            }
8632            if (r != null) {
8633                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8634            }
8635
8636            N = pkg.receivers.size();
8637            r = null;
8638            for (i=0; i<N; i++) {
8639                PackageParser.Activity a = pkg.receivers.get(i);
8640                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8641                        a.info.processName, pkg.applicationInfo.uid);
8642                mReceivers.addActivity(a, "receiver");
8643                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8644                    if (r == null) {
8645                        r = new StringBuilder(256);
8646                    } else {
8647                        r.append(' ');
8648                    }
8649                    r.append(a.info.name);
8650                }
8651            }
8652            if (r != null) {
8653                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8654            }
8655
8656            N = pkg.activities.size();
8657            r = null;
8658            for (i=0; i<N; i++) {
8659                PackageParser.Activity a = pkg.activities.get(i);
8660                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8661                        a.info.processName, pkg.applicationInfo.uid);
8662                mActivities.addActivity(a, "activity");
8663                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8664                    if (r == null) {
8665                        r = new StringBuilder(256);
8666                    } else {
8667                        r.append(' ');
8668                    }
8669                    r.append(a.info.name);
8670                }
8671            }
8672            if (r != null) {
8673                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8674            }
8675
8676            N = pkg.permissionGroups.size();
8677            r = null;
8678            for (i=0; i<N; i++) {
8679                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8680                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8681                if (cur == null) {
8682                    mPermissionGroups.put(pg.info.name, pg);
8683                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8684                        if (r == null) {
8685                            r = new StringBuilder(256);
8686                        } else {
8687                            r.append(' ');
8688                        }
8689                        r.append(pg.info.name);
8690                    }
8691                } else {
8692                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8693                            + pg.info.packageName + " ignored: original from "
8694                            + cur.info.packageName);
8695                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8696                        if (r == null) {
8697                            r = new StringBuilder(256);
8698                        } else {
8699                            r.append(' ');
8700                        }
8701                        r.append("DUP:");
8702                        r.append(pg.info.name);
8703                    }
8704                }
8705            }
8706            if (r != null) {
8707                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8708            }
8709
8710            N = pkg.permissions.size();
8711            r = null;
8712            for (i=0; i<N; i++) {
8713                PackageParser.Permission p = pkg.permissions.get(i);
8714
8715                // Assume by default that we did not install this permission into the system.
8716                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8717
8718                // Now that permission groups have a special meaning, we ignore permission
8719                // groups for legacy apps to prevent unexpected behavior. In particular,
8720                // permissions for one app being granted to someone just becase they happen
8721                // to be in a group defined by another app (before this had no implications).
8722                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8723                    p.group = mPermissionGroups.get(p.info.group);
8724                    // Warn for a permission in an unknown group.
8725                    if (p.info.group != null && p.group == null) {
8726                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8727                                + p.info.packageName + " in an unknown group " + p.info.group);
8728                    }
8729                }
8730
8731                ArrayMap<String, BasePermission> permissionMap =
8732                        p.tree ? mSettings.mPermissionTrees
8733                                : mSettings.mPermissions;
8734                BasePermission bp = permissionMap.get(p.info.name);
8735
8736                // Allow system apps to redefine non-system permissions
8737                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8738                    final boolean currentOwnerIsSystem = (bp.perm != null
8739                            && isSystemApp(bp.perm.owner));
8740                    if (isSystemApp(p.owner)) {
8741                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8742                            // It's a built-in permission and no owner, take ownership now
8743                            bp.packageSetting = pkgSetting;
8744                            bp.perm = p;
8745                            bp.uid = pkg.applicationInfo.uid;
8746                            bp.sourcePackage = p.info.packageName;
8747                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8748                        } else if (!currentOwnerIsSystem) {
8749                            String msg = "New decl " + p.owner + " of permission  "
8750                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8751                            reportSettingsProblem(Log.WARN, msg);
8752                            bp = null;
8753                        }
8754                    }
8755                }
8756
8757                if (bp == null) {
8758                    bp = new BasePermission(p.info.name, p.info.packageName,
8759                            BasePermission.TYPE_NORMAL);
8760                    permissionMap.put(p.info.name, bp);
8761                }
8762
8763                if (bp.perm == null) {
8764                    if (bp.sourcePackage == null
8765                            || bp.sourcePackage.equals(p.info.packageName)) {
8766                        BasePermission tree = findPermissionTreeLP(p.info.name);
8767                        if (tree == null
8768                                || tree.sourcePackage.equals(p.info.packageName)) {
8769                            bp.packageSetting = pkgSetting;
8770                            bp.perm = p;
8771                            bp.uid = pkg.applicationInfo.uid;
8772                            bp.sourcePackage = p.info.packageName;
8773                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8774                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8775                                if (r == null) {
8776                                    r = new StringBuilder(256);
8777                                } else {
8778                                    r.append(' ');
8779                                }
8780                                r.append(p.info.name);
8781                            }
8782                        } else {
8783                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8784                                    + p.info.packageName + " ignored: base tree "
8785                                    + tree.name + " is from package "
8786                                    + tree.sourcePackage);
8787                        }
8788                    } else {
8789                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8790                                + p.info.packageName + " ignored: original from "
8791                                + bp.sourcePackage);
8792                    }
8793                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8794                    if (r == null) {
8795                        r = new StringBuilder(256);
8796                    } else {
8797                        r.append(' ');
8798                    }
8799                    r.append("DUP:");
8800                    r.append(p.info.name);
8801                }
8802                if (bp.perm == p) {
8803                    bp.protectionLevel = p.info.protectionLevel;
8804                }
8805            }
8806
8807            if (r != null) {
8808                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8809            }
8810
8811            N = pkg.instrumentation.size();
8812            r = null;
8813            for (i=0; i<N; i++) {
8814                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8815                a.info.packageName = pkg.applicationInfo.packageName;
8816                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8817                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8818                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8819                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8820                a.info.dataDir = pkg.applicationInfo.dataDir;
8821                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8822                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8823
8824                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8825                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8826                mInstrumentation.put(a.getComponentName(), a);
8827                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8828                    if (r == null) {
8829                        r = new StringBuilder(256);
8830                    } else {
8831                        r.append(' ');
8832                    }
8833                    r.append(a.info.name);
8834                }
8835            }
8836            if (r != null) {
8837                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8838            }
8839
8840            if (pkg.protectedBroadcasts != null) {
8841                N = pkg.protectedBroadcasts.size();
8842                for (i=0; i<N; i++) {
8843                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8844                }
8845            }
8846
8847            pkgSetting.setTimeStamp(scanFileTime);
8848
8849            // Create idmap files for pairs of (packages, overlay packages).
8850            // Note: "android", ie framework-res.apk, is handled by native layers.
8851            if (pkg.mOverlayTarget != null) {
8852                // This is an overlay package.
8853                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8854                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8855                        mOverlays.put(pkg.mOverlayTarget,
8856                                new ArrayMap<String, PackageParser.Package>());
8857                    }
8858                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8859                    map.put(pkg.packageName, pkg);
8860                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8861                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8862                        createIdmapFailed = true;
8863                    }
8864                }
8865            } else if (mOverlays.containsKey(pkg.packageName) &&
8866                    !pkg.packageName.equals("android")) {
8867                // This is a regular package, with one or more known overlay packages.
8868                createIdmapsForPackageLI(pkg);
8869            }
8870        }
8871
8872        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8873
8874        if (createIdmapFailed) {
8875            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8876                    "scanPackageLI failed to createIdmap");
8877        }
8878        return pkg;
8879    }
8880
8881    /**
8882     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8883     * is derived purely on the basis of the contents of {@code scanFile} and
8884     * {@code cpuAbiOverride}.
8885     *
8886     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8887     */
8888    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8889                                 String cpuAbiOverride, boolean extractLibs)
8890            throws PackageManagerException {
8891        // TODO: We can probably be smarter about this stuff. For installed apps,
8892        // we can calculate this information at install time once and for all. For
8893        // system apps, we can probably assume that this information doesn't change
8894        // after the first boot scan. As things stand, we do lots of unnecessary work.
8895
8896        // Give ourselves some initial paths; we'll come back for another
8897        // pass once we've determined ABI below.
8898        setNativeLibraryPaths(pkg);
8899
8900        // We would never need to extract libs for forward-locked and external packages,
8901        // since the container service will do it for us. We shouldn't attempt to
8902        // extract libs from system app when it was not updated.
8903        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8904                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8905            extractLibs = false;
8906        }
8907
8908        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8909        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8910
8911        NativeLibraryHelper.Handle handle = null;
8912        try {
8913            handle = NativeLibraryHelper.Handle.create(pkg);
8914            // TODO(multiArch): This can be null for apps that didn't go through the
8915            // usual installation process. We can calculate it again, like we
8916            // do during install time.
8917            //
8918            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8919            // unnecessary.
8920            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8921
8922            // Null out the abis so that they can be recalculated.
8923            pkg.applicationInfo.primaryCpuAbi = null;
8924            pkg.applicationInfo.secondaryCpuAbi = null;
8925            if (isMultiArch(pkg.applicationInfo)) {
8926                // Warn if we've set an abiOverride for multi-lib packages..
8927                // By definition, we need to copy both 32 and 64 bit libraries for
8928                // such packages.
8929                if (pkg.cpuAbiOverride != null
8930                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8931                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8932                }
8933
8934                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8935                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8936                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8937                    if (extractLibs) {
8938                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8939                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8940                                useIsaSpecificSubdirs);
8941                    } else {
8942                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8943                    }
8944                }
8945
8946                maybeThrowExceptionForMultiArchCopy(
8947                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8948
8949                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8950                    if (extractLibs) {
8951                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8952                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8953                                useIsaSpecificSubdirs);
8954                    } else {
8955                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8956                    }
8957                }
8958
8959                maybeThrowExceptionForMultiArchCopy(
8960                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8961
8962                if (abi64 >= 0) {
8963                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8964                }
8965
8966                if (abi32 >= 0) {
8967                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8968                    if (abi64 >= 0) {
8969                        if (pkg.use32bitAbi) {
8970                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8971                            pkg.applicationInfo.primaryCpuAbi = abi;
8972                        } else {
8973                            pkg.applicationInfo.secondaryCpuAbi = abi;
8974                        }
8975                    } else {
8976                        pkg.applicationInfo.primaryCpuAbi = abi;
8977                    }
8978                }
8979
8980            } else {
8981                String[] abiList = (cpuAbiOverride != null) ?
8982                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8983
8984                // Enable gross and lame hacks for apps that are built with old
8985                // SDK tools. We must scan their APKs for renderscript bitcode and
8986                // not launch them if it's present. Don't bother checking on devices
8987                // that don't have 64 bit support.
8988                boolean needsRenderScriptOverride = false;
8989                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8990                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8991                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8992                    needsRenderScriptOverride = true;
8993                }
8994
8995                final int copyRet;
8996                if (extractLibs) {
8997                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8998                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8999                } else {
9000                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9001                }
9002
9003                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9004                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9005                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9006                }
9007
9008                if (copyRet >= 0) {
9009                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9010                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9011                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9012                } else if (needsRenderScriptOverride) {
9013                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9014                }
9015            }
9016        } catch (IOException ioe) {
9017            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9018        } finally {
9019            IoUtils.closeQuietly(handle);
9020        }
9021
9022        // Now that we've calculated the ABIs and determined if it's an internal app,
9023        // we will go ahead and populate the nativeLibraryPath.
9024        setNativeLibraryPaths(pkg);
9025    }
9026
9027    /**
9028     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9029     * i.e, so that all packages can be run inside a single process if required.
9030     *
9031     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9032     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9033     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9034     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9035     * updating a package that belongs to a shared user.
9036     *
9037     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9038     * adds unnecessary complexity.
9039     */
9040    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9041            PackageParser.Package scannedPackage, boolean bootComplete) {
9042        String requiredInstructionSet = null;
9043        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9044            requiredInstructionSet = VMRuntime.getInstructionSet(
9045                     scannedPackage.applicationInfo.primaryCpuAbi);
9046        }
9047
9048        PackageSetting requirer = null;
9049        for (PackageSetting ps : packagesForUser) {
9050            // If packagesForUser contains scannedPackage, we skip it. This will happen
9051            // when scannedPackage is an update of an existing package. Without this check,
9052            // we will never be able to change the ABI of any package belonging to a shared
9053            // user, even if it's compatible with other packages.
9054            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9055                if (ps.primaryCpuAbiString == null) {
9056                    continue;
9057                }
9058
9059                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9060                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9061                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9062                    // this but there's not much we can do.
9063                    String errorMessage = "Instruction set mismatch, "
9064                            + ((requirer == null) ? "[caller]" : requirer)
9065                            + " requires " + requiredInstructionSet + " whereas " + ps
9066                            + " requires " + instructionSet;
9067                    Slog.w(TAG, errorMessage);
9068                }
9069
9070                if (requiredInstructionSet == null) {
9071                    requiredInstructionSet = instructionSet;
9072                    requirer = ps;
9073                }
9074            }
9075        }
9076
9077        if (requiredInstructionSet != null) {
9078            String adjustedAbi;
9079            if (requirer != null) {
9080                // requirer != null implies that either scannedPackage was null or that scannedPackage
9081                // did not require an ABI, in which case we have to adjust scannedPackage to match
9082                // the ABI of the set (which is the same as requirer's ABI)
9083                adjustedAbi = requirer.primaryCpuAbiString;
9084                if (scannedPackage != null) {
9085                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9086                }
9087            } else {
9088                // requirer == null implies that we're updating all ABIs in the set to
9089                // match scannedPackage.
9090                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9091            }
9092
9093            for (PackageSetting ps : packagesForUser) {
9094                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9095                    if (ps.primaryCpuAbiString != null) {
9096                        continue;
9097                    }
9098
9099                    ps.primaryCpuAbiString = adjustedAbi;
9100                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9101                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9102                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9103                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9104                                + " (requirer="
9105                                + (requirer == null ? "null" : requirer.pkg.packageName)
9106                                + ", scannedPackage="
9107                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9108                                + ")");
9109                        try {
9110                            mInstaller.rmdex(ps.codePathString,
9111                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9112                        } catch (InstallerException ignored) {
9113                        }
9114                    }
9115                }
9116            }
9117        }
9118    }
9119
9120    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9121        synchronized (mPackages) {
9122            mResolverReplaced = true;
9123            // Set up information for custom user intent resolution activity.
9124            mResolveActivity.applicationInfo = pkg.applicationInfo;
9125            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9126            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9127            mResolveActivity.processName = pkg.applicationInfo.packageName;
9128            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9129            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9130                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9131            mResolveActivity.theme = 0;
9132            mResolveActivity.exported = true;
9133            mResolveActivity.enabled = true;
9134            mResolveInfo.activityInfo = mResolveActivity;
9135            mResolveInfo.priority = 0;
9136            mResolveInfo.preferredOrder = 0;
9137            mResolveInfo.match = 0;
9138            mResolveComponentName = mCustomResolverComponentName;
9139            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9140                    mResolveComponentName);
9141        }
9142    }
9143
9144    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9145        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9146
9147        // Set up information for ephemeral installer activity
9148        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9149        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9150        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9151        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9152        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9153        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9154                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9155        mEphemeralInstallerActivity.theme = 0;
9156        mEphemeralInstallerActivity.exported = true;
9157        mEphemeralInstallerActivity.enabled = true;
9158        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9159        mEphemeralInstallerInfo.priority = 0;
9160        mEphemeralInstallerInfo.preferredOrder = 0;
9161        mEphemeralInstallerInfo.match = 0;
9162
9163        if (DEBUG_EPHEMERAL) {
9164            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9165        }
9166    }
9167
9168    private static String calculateBundledApkRoot(final String codePathString) {
9169        final File codePath = new File(codePathString);
9170        final File codeRoot;
9171        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9172            codeRoot = Environment.getRootDirectory();
9173        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9174            codeRoot = Environment.getOemDirectory();
9175        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9176            codeRoot = Environment.getVendorDirectory();
9177        } else {
9178            // Unrecognized code path; take its top real segment as the apk root:
9179            // e.g. /something/app/blah.apk => /something
9180            try {
9181                File f = codePath.getCanonicalFile();
9182                File parent = f.getParentFile();    // non-null because codePath is a file
9183                File tmp;
9184                while ((tmp = parent.getParentFile()) != null) {
9185                    f = parent;
9186                    parent = tmp;
9187                }
9188                codeRoot = f;
9189                Slog.w(TAG, "Unrecognized code path "
9190                        + codePath + " - using " + codeRoot);
9191            } catch (IOException e) {
9192                // Can't canonicalize the code path -- shenanigans?
9193                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9194                return Environment.getRootDirectory().getPath();
9195            }
9196        }
9197        return codeRoot.getPath();
9198    }
9199
9200    /**
9201     * Derive and set the location of native libraries for the given package,
9202     * which varies depending on where and how the package was installed.
9203     */
9204    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9205        final ApplicationInfo info = pkg.applicationInfo;
9206        final String codePath = pkg.codePath;
9207        final File codeFile = new File(codePath);
9208        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9209        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9210
9211        info.nativeLibraryRootDir = null;
9212        info.nativeLibraryRootRequiresIsa = false;
9213        info.nativeLibraryDir = null;
9214        info.secondaryNativeLibraryDir = null;
9215
9216        if (isApkFile(codeFile)) {
9217            // Monolithic install
9218            if (bundledApp) {
9219                // If "/system/lib64/apkname" exists, assume that is the per-package
9220                // native library directory to use; otherwise use "/system/lib/apkname".
9221                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9222                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9223                        getPrimaryInstructionSet(info));
9224
9225                // This is a bundled system app so choose the path based on the ABI.
9226                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9227                // is just the default path.
9228                final String apkName = deriveCodePathName(codePath);
9229                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9230                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9231                        apkName).getAbsolutePath();
9232
9233                if (info.secondaryCpuAbi != null) {
9234                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9235                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9236                            secondaryLibDir, apkName).getAbsolutePath();
9237                }
9238            } else if (asecApp) {
9239                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9240                        .getAbsolutePath();
9241            } else {
9242                final String apkName = deriveCodePathName(codePath);
9243                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9244                        .getAbsolutePath();
9245            }
9246
9247            info.nativeLibraryRootRequiresIsa = false;
9248            info.nativeLibraryDir = info.nativeLibraryRootDir;
9249        } else {
9250            // Cluster install
9251            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9252            info.nativeLibraryRootRequiresIsa = true;
9253
9254            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9255                    getPrimaryInstructionSet(info)).getAbsolutePath();
9256
9257            if (info.secondaryCpuAbi != null) {
9258                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9259                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9260            }
9261        }
9262    }
9263
9264    /**
9265     * Calculate the abis and roots for a bundled app. These can uniquely
9266     * be determined from the contents of the system partition, i.e whether
9267     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9268     * of this information, and instead assume that the system was built
9269     * sensibly.
9270     */
9271    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9272                                           PackageSetting pkgSetting) {
9273        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9274
9275        // If "/system/lib64/apkname" exists, assume that is the per-package
9276        // native library directory to use; otherwise use "/system/lib/apkname".
9277        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9278        setBundledAppAbi(pkg, apkRoot, apkName);
9279        // pkgSetting might be null during rescan following uninstall of updates
9280        // to a bundled app, so accommodate that possibility.  The settings in
9281        // that case will be established later from the parsed package.
9282        //
9283        // If the settings aren't null, sync them up with what we've just derived.
9284        // note that apkRoot isn't stored in the package settings.
9285        if (pkgSetting != null) {
9286            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9287            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9288        }
9289    }
9290
9291    /**
9292     * Deduces the ABI of a bundled app and sets the relevant fields on the
9293     * parsed pkg object.
9294     *
9295     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9296     *        under which system libraries are installed.
9297     * @param apkName the name of the installed package.
9298     */
9299    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9300        final File codeFile = new File(pkg.codePath);
9301
9302        final boolean has64BitLibs;
9303        final boolean has32BitLibs;
9304        if (isApkFile(codeFile)) {
9305            // Monolithic install
9306            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9307            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9308        } else {
9309            // Cluster install
9310            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9311            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9312                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9313                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9314                has64BitLibs = (new File(rootDir, isa)).exists();
9315            } else {
9316                has64BitLibs = false;
9317            }
9318            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9319                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9320                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9321                has32BitLibs = (new File(rootDir, isa)).exists();
9322            } else {
9323                has32BitLibs = false;
9324            }
9325        }
9326
9327        if (has64BitLibs && !has32BitLibs) {
9328            // The package has 64 bit libs, but not 32 bit libs. Its primary
9329            // ABI should be 64 bit. We can safely assume here that the bundled
9330            // native libraries correspond to the most preferred ABI in the list.
9331
9332            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9333            pkg.applicationInfo.secondaryCpuAbi = null;
9334        } else if (has32BitLibs && !has64BitLibs) {
9335            // The package has 32 bit libs but not 64 bit libs. Its primary
9336            // ABI should be 32 bit.
9337
9338            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9339            pkg.applicationInfo.secondaryCpuAbi = null;
9340        } else if (has32BitLibs && has64BitLibs) {
9341            // The application has both 64 and 32 bit bundled libraries. We check
9342            // here that the app declares multiArch support, and warn if it doesn't.
9343            //
9344            // We will be lenient here and record both ABIs. The primary will be the
9345            // ABI that's higher on the list, i.e, a device that's configured to prefer
9346            // 64 bit apps will see a 64 bit primary ABI,
9347
9348            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9349                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9350            }
9351
9352            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9353                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9354                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9355            } else {
9356                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9357                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9358            }
9359        } else {
9360            pkg.applicationInfo.primaryCpuAbi = null;
9361            pkg.applicationInfo.secondaryCpuAbi = null;
9362        }
9363    }
9364
9365    private void killApplication(String pkgName, int appId, String reason) {
9366        // Request the ActivityManager to kill the process(only for existing packages)
9367        // so that we do not end up in a confused state while the user is still using the older
9368        // version of the application while the new one gets installed.
9369        final long token = Binder.clearCallingIdentity();
9370        try {
9371            IActivityManager am = ActivityManagerNative.getDefault();
9372            if (am != null) {
9373                try {
9374                    am.killApplicationWithAppId(pkgName, appId, reason);
9375                } catch (RemoteException e) {
9376                }
9377            }
9378        } finally {
9379            Binder.restoreCallingIdentity(token);
9380        }
9381    }
9382
9383    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9384        // Remove the parent package setting
9385        PackageSetting ps = (PackageSetting) pkg.mExtras;
9386        if (ps != null) {
9387            removePackageLI(ps, chatty);
9388        }
9389        // Remove the child package setting
9390        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9391        for (int i = 0; i < childCount; i++) {
9392            PackageParser.Package childPkg = pkg.childPackages.get(i);
9393            ps = (PackageSetting) childPkg.mExtras;
9394            if (ps != null) {
9395                removePackageLI(ps, chatty);
9396            }
9397        }
9398    }
9399
9400    void removePackageLI(PackageSetting ps, boolean chatty) {
9401        if (DEBUG_INSTALL) {
9402            if (chatty)
9403                Log.d(TAG, "Removing package " + ps.name);
9404        }
9405
9406        // writer
9407        synchronized (mPackages) {
9408            mPackages.remove(ps.name);
9409            final PackageParser.Package pkg = ps.pkg;
9410            if (pkg != null) {
9411                cleanPackageDataStructuresLILPw(pkg, chatty);
9412            }
9413        }
9414    }
9415
9416    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9417        if (DEBUG_INSTALL) {
9418            if (chatty)
9419                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9420        }
9421
9422        // writer
9423        synchronized (mPackages) {
9424            // Remove the parent package
9425            mPackages.remove(pkg.applicationInfo.packageName);
9426            cleanPackageDataStructuresLILPw(pkg, chatty);
9427
9428            // Remove the child packages
9429            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9430            for (int i = 0; i < childCount; i++) {
9431                PackageParser.Package childPkg = pkg.childPackages.get(i);
9432                mPackages.remove(childPkg.applicationInfo.packageName);
9433                cleanPackageDataStructuresLILPw(childPkg, chatty);
9434            }
9435        }
9436    }
9437
9438    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9439        int N = pkg.providers.size();
9440        StringBuilder r = null;
9441        int i;
9442        for (i=0; i<N; i++) {
9443            PackageParser.Provider p = pkg.providers.get(i);
9444            mProviders.removeProvider(p);
9445            if (p.info.authority == null) {
9446
9447                /* There was another ContentProvider with this authority when
9448                 * this app was installed so this authority is null,
9449                 * Ignore it as we don't have to unregister the provider.
9450                 */
9451                continue;
9452            }
9453            String names[] = p.info.authority.split(";");
9454            for (int j = 0; j < names.length; j++) {
9455                if (mProvidersByAuthority.get(names[j]) == p) {
9456                    mProvidersByAuthority.remove(names[j]);
9457                    if (DEBUG_REMOVE) {
9458                        if (chatty)
9459                            Log.d(TAG, "Unregistered content provider: " + names[j]
9460                                    + ", className = " + p.info.name + ", isSyncable = "
9461                                    + p.info.isSyncable);
9462                    }
9463                }
9464            }
9465            if (DEBUG_REMOVE && chatty) {
9466                if (r == null) {
9467                    r = new StringBuilder(256);
9468                } else {
9469                    r.append(' ');
9470                }
9471                r.append(p.info.name);
9472            }
9473        }
9474        if (r != null) {
9475            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9476        }
9477
9478        N = pkg.services.size();
9479        r = null;
9480        for (i=0; i<N; i++) {
9481            PackageParser.Service s = pkg.services.get(i);
9482            mServices.removeService(s);
9483            if (chatty) {
9484                if (r == null) {
9485                    r = new StringBuilder(256);
9486                } else {
9487                    r.append(' ');
9488                }
9489                r.append(s.info.name);
9490            }
9491        }
9492        if (r != null) {
9493            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9494        }
9495
9496        N = pkg.receivers.size();
9497        r = null;
9498        for (i=0; i<N; i++) {
9499            PackageParser.Activity a = pkg.receivers.get(i);
9500            mReceivers.removeActivity(a, "receiver");
9501            if (DEBUG_REMOVE && chatty) {
9502                if (r == null) {
9503                    r = new StringBuilder(256);
9504                } else {
9505                    r.append(' ');
9506                }
9507                r.append(a.info.name);
9508            }
9509        }
9510        if (r != null) {
9511            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9512        }
9513
9514        N = pkg.activities.size();
9515        r = null;
9516        for (i=0; i<N; i++) {
9517            PackageParser.Activity a = pkg.activities.get(i);
9518            mActivities.removeActivity(a, "activity");
9519            if (DEBUG_REMOVE && chatty) {
9520                if (r == null) {
9521                    r = new StringBuilder(256);
9522                } else {
9523                    r.append(' ');
9524                }
9525                r.append(a.info.name);
9526            }
9527        }
9528        if (r != null) {
9529            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9530        }
9531
9532        N = pkg.permissions.size();
9533        r = null;
9534        for (i=0; i<N; i++) {
9535            PackageParser.Permission p = pkg.permissions.get(i);
9536            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9537            if (bp == null) {
9538                bp = mSettings.mPermissionTrees.get(p.info.name);
9539            }
9540            if (bp != null && bp.perm == p) {
9541                bp.perm = null;
9542                if (DEBUG_REMOVE && chatty) {
9543                    if (r == null) {
9544                        r = new StringBuilder(256);
9545                    } else {
9546                        r.append(' ');
9547                    }
9548                    r.append(p.info.name);
9549                }
9550            }
9551            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9552                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9553                if (appOpPkgs != null) {
9554                    appOpPkgs.remove(pkg.packageName);
9555                }
9556            }
9557        }
9558        if (r != null) {
9559            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9560        }
9561
9562        N = pkg.requestedPermissions.size();
9563        r = null;
9564        for (i=0; i<N; i++) {
9565            String perm = pkg.requestedPermissions.get(i);
9566            BasePermission bp = mSettings.mPermissions.get(perm);
9567            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9568                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9569                if (appOpPkgs != null) {
9570                    appOpPkgs.remove(pkg.packageName);
9571                    if (appOpPkgs.isEmpty()) {
9572                        mAppOpPermissionPackages.remove(perm);
9573                    }
9574                }
9575            }
9576        }
9577        if (r != null) {
9578            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9579        }
9580
9581        N = pkg.instrumentation.size();
9582        r = null;
9583        for (i=0; i<N; i++) {
9584            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9585            mInstrumentation.remove(a.getComponentName());
9586            if (DEBUG_REMOVE && chatty) {
9587                if (r == null) {
9588                    r = new StringBuilder(256);
9589                } else {
9590                    r.append(' ');
9591                }
9592                r.append(a.info.name);
9593            }
9594        }
9595        if (r != null) {
9596            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9597        }
9598
9599        r = null;
9600        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9601            // Only system apps can hold shared libraries.
9602            if (pkg.libraryNames != null) {
9603                for (i=0; i<pkg.libraryNames.size(); i++) {
9604                    String name = pkg.libraryNames.get(i);
9605                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9606                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9607                        mSharedLibraries.remove(name);
9608                        if (DEBUG_REMOVE && chatty) {
9609                            if (r == null) {
9610                                r = new StringBuilder(256);
9611                            } else {
9612                                r.append(' ');
9613                            }
9614                            r.append(name);
9615                        }
9616                    }
9617                }
9618            }
9619        }
9620        if (r != null) {
9621            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9622        }
9623    }
9624
9625    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9626        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9627            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9628                return true;
9629            }
9630        }
9631        return false;
9632    }
9633
9634    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9635    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9636    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9637
9638    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9639        // Update the parent permissions
9640        updatePermissionsLPw(pkg.packageName, pkg, flags);
9641        // Update the child permissions
9642        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9643        for (int i = 0; i < childCount; i++) {
9644            PackageParser.Package childPkg = pkg.childPackages.get(i);
9645            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9646        }
9647    }
9648
9649    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9650            int flags) {
9651        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9652        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9653    }
9654
9655    private void updatePermissionsLPw(String changingPkg,
9656            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9657        // Make sure there are no dangling permission trees.
9658        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9659        while (it.hasNext()) {
9660            final BasePermission bp = it.next();
9661            if (bp.packageSetting == null) {
9662                // We may not yet have parsed the package, so just see if
9663                // we still know about its settings.
9664                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9665            }
9666            if (bp.packageSetting == null) {
9667                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9668                        + " from package " + bp.sourcePackage);
9669                it.remove();
9670            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9671                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9672                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9673                            + " from package " + bp.sourcePackage);
9674                    flags |= UPDATE_PERMISSIONS_ALL;
9675                    it.remove();
9676                }
9677            }
9678        }
9679
9680        // Make sure all dynamic permissions have been assigned to a package,
9681        // and make sure there are no dangling permissions.
9682        it = mSettings.mPermissions.values().iterator();
9683        while (it.hasNext()) {
9684            final BasePermission bp = it.next();
9685            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9686                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9687                        + bp.name + " pkg=" + bp.sourcePackage
9688                        + " info=" + bp.pendingInfo);
9689                if (bp.packageSetting == null && bp.pendingInfo != null) {
9690                    final BasePermission tree = findPermissionTreeLP(bp.name);
9691                    if (tree != null && tree.perm != null) {
9692                        bp.packageSetting = tree.packageSetting;
9693                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9694                                new PermissionInfo(bp.pendingInfo));
9695                        bp.perm.info.packageName = tree.perm.info.packageName;
9696                        bp.perm.info.name = bp.name;
9697                        bp.uid = tree.uid;
9698                    }
9699                }
9700            }
9701            if (bp.packageSetting == null) {
9702                // We may not yet have parsed the package, so just see if
9703                // we still know about its settings.
9704                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9705            }
9706            if (bp.packageSetting == null) {
9707                Slog.w(TAG, "Removing dangling permission: " + bp.name
9708                        + " from package " + bp.sourcePackage);
9709                it.remove();
9710            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9711                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9712                    Slog.i(TAG, "Removing old permission: " + bp.name
9713                            + " from package " + bp.sourcePackage);
9714                    flags |= UPDATE_PERMISSIONS_ALL;
9715                    it.remove();
9716                }
9717            }
9718        }
9719
9720        // Now update the permissions for all packages, in particular
9721        // replace the granted permissions of the system packages.
9722        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9723            for (PackageParser.Package pkg : mPackages.values()) {
9724                if (pkg != pkgInfo) {
9725                    // Only replace for packages on requested volume
9726                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9727                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9728                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9729                    grantPermissionsLPw(pkg, replace, changingPkg);
9730                }
9731            }
9732        }
9733
9734        if (pkgInfo != null) {
9735            // Only replace for packages on requested volume
9736            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9737            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9738                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9739            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9740        }
9741    }
9742
9743    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9744            String packageOfInterest) {
9745        // IMPORTANT: There are two types of permissions: install and runtime.
9746        // Install time permissions are granted when the app is installed to
9747        // all device users and users added in the future. Runtime permissions
9748        // are granted at runtime explicitly to specific users. Normal and signature
9749        // protected permissions are install time permissions. Dangerous permissions
9750        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9751        // otherwise they are runtime permissions. This function does not manage
9752        // runtime permissions except for the case an app targeting Lollipop MR1
9753        // being upgraded to target a newer SDK, in which case dangerous permissions
9754        // are transformed from install time to runtime ones.
9755
9756        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9757        if (ps == null) {
9758            return;
9759        }
9760
9761        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9762
9763        PermissionsState permissionsState = ps.getPermissionsState();
9764        PermissionsState origPermissions = permissionsState;
9765
9766        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9767
9768        boolean runtimePermissionsRevoked = false;
9769        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9770
9771        boolean changedInstallPermission = false;
9772
9773        if (replace) {
9774            ps.installPermissionsFixed = false;
9775            if (!ps.isSharedUser()) {
9776                origPermissions = new PermissionsState(permissionsState);
9777                permissionsState.reset();
9778            } else {
9779                // We need to know only about runtime permission changes since the
9780                // calling code always writes the install permissions state but
9781                // the runtime ones are written only if changed. The only cases of
9782                // changed runtime permissions here are promotion of an install to
9783                // runtime and revocation of a runtime from a shared user.
9784                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9785                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9786                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9787                    runtimePermissionsRevoked = true;
9788                }
9789            }
9790        }
9791
9792        permissionsState.setGlobalGids(mGlobalGids);
9793
9794        final int N = pkg.requestedPermissions.size();
9795        for (int i=0; i<N; i++) {
9796            final String name = pkg.requestedPermissions.get(i);
9797            final BasePermission bp = mSettings.mPermissions.get(name);
9798
9799            if (DEBUG_INSTALL) {
9800                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9801            }
9802
9803            if (bp == null || bp.packageSetting == null) {
9804                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9805                    Slog.w(TAG, "Unknown permission " + name
9806                            + " in package " + pkg.packageName);
9807                }
9808                continue;
9809            }
9810
9811            final String perm = bp.name;
9812            boolean allowedSig = false;
9813            int grant = GRANT_DENIED;
9814
9815            // Keep track of app op permissions.
9816            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9817                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9818                if (pkgs == null) {
9819                    pkgs = new ArraySet<>();
9820                    mAppOpPermissionPackages.put(bp.name, pkgs);
9821                }
9822                pkgs.add(pkg.packageName);
9823            }
9824
9825            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9826            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9827                    >= Build.VERSION_CODES.M;
9828            switch (level) {
9829                case PermissionInfo.PROTECTION_NORMAL: {
9830                    // For all apps normal permissions are install time ones.
9831                    grant = GRANT_INSTALL;
9832                } break;
9833
9834                case PermissionInfo.PROTECTION_DANGEROUS: {
9835                    // If a permission review is required for legacy apps we represent
9836                    // their permissions as always granted runtime ones since we need
9837                    // to keep the review required permission flag per user while an
9838                    // install permission's state is shared across all users.
9839                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9840                        // For legacy apps dangerous permissions are install time ones.
9841                        grant = GRANT_INSTALL;
9842                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9843                        // For legacy apps that became modern, install becomes runtime.
9844                        grant = GRANT_UPGRADE;
9845                    } else if (mPromoteSystemApps
9846                            && isSystemApp(ps)
9847                            && mExistingSystemPackages.contains(ps.name)) {
9848                        // For legacy system apps, install becomes runtime.
9849                        // We cannot check hasInstallPermission() for system apps since those
9850                        // permissions were granted implicitly and not persisted pre-M.
9851                        grant = GRANT_UPGRADE;
9852                    } else {
9853                        // For modern apps keep runtime permissions unchanged.
9854                        grant = GRANT_RUNTIME;
9855                    }
9856                } break;
9857
9858                case PermissionInfo.PROTECTION_SIGNATURE: {
9859                    // For all apps signature permissions are install time ones.
9860                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9861                    if (allowedSig) {
9862                        grant = GRANT_INSTALL;
9863                    }
9864                } break;
9865            }
9866
9867            if (DEBUG_INSTALL) {
9868                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9869            }
9870
9871            if (grant != GRANT_DENIED) {
9872                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9873                    // If this is an existing, non-system package, then
9874                    // we can't add any new permissions to it.
9875                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9876                        // Except...  if this is a permission that was added
9877                        // to the platform (note: need to only do this when
9878                        // updating the platform).
9879                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9880                            grant = GRANT_DENIED;
9881                        }
9882                    }
9883                }
9884
9885                switch (grant) {
9886                    case GRANT_INSTALL: {
9887                        // Revoke this as runtime permission to handle the case of
9888                        // a runtime permission being downgraded to an install one.
9889                        // Also in permission review mode we keep dangerous permissions
9890                        // for legacy apps
9891                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9892                            if (origPermissions.getRuntimePermissionState(
9893                                    bp.name, userId) != null) {
9894                                // Revoke the runtime permission and clear the flags.
9895                                origPermissions.revokeRuntimePermission(bp, userId);
9896                                origPermissions.updatePermissionFlags(bp, userId,
9897                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9898                                // If we revoked a permission permission, we have to write.
9899                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9900                                        changedRuntimePermissionUserIds, userId);
9901                            }
9902                        }
9903                        // Grant an install permission.
9904                        if (permissionsState.grantInstallPermission(bp) !=
9905                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9906                            changedInstallPermission = true;
9907                        }
9908                    } break;
9909
9910                    case GRANT_RUNTIME: {
9911                        // Grant previously granted runtime permissions.
9912                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9913                            PermissionState permissionState = origPermissions
9914                                    .getRuntimePermissionState(bp.name, userId);
9915                            int flags = permissionState != null
9916                                    ? permissionState.getFlags() : 0;
9917                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9918                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9919                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9920                                    // If we cannot put the permission as it was, we have to write.
9921                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9922                                            changedRuntimePermissionUserIds, userId);
9923                                }
9924                                // If the app supports runtime permissions no need for a review.
9925                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9926                                        && appSupportsRuntimePermissions
9927                                        && (flags & PackageManager
9928                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9929                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9930                                    // Since we changed the flags, we have to write.
9931                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9932                                            changedRuntimePermissionUserIds, userId);
9933                                }
9934                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9935                                    && !appSupportsRuntimePermissions) {
9936                                // For legacy apps that need a permission review, every new
9937                                // runtime permission is granted but it is pending a review.
9938                                // We also need to review only platform defined runtime
9939                                // permissions as these are the only ones the platform knows
9940                                // how to disable the API to simulate revocation as legacy
9941                                // apps don't expect to run with revoked permissions.
9942                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9943                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9944                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9945                                        // We changed the flags, hence have to write.
9946                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9947                                                changedRuntimePermissionUserIds, userId);
9948                                    }
9949                                }
9950                                if (permissionsState.grantRuntimePermission(bp, userId)
9951                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9952                                    // We changed the permission, hence have to write.
9953                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9954                                            changedRuntimePermissionUserIds, userId);
9955                                }
9956                            }
9957                            // Propagate the permission flags.
9958                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9959                        }
9960                    } break;
9961
9962                    case GRANT_UPGRADE: {
9963                        // Grant runtime permissions for a previously held install permission.
9964                        PermissionState permissionState = origPermissions
9965                                .getInstallPermissionState(bp.name);
9966                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9967
9968                        if (origPermissions.revokeInstallPermission(bp)
9969                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9970                            // We will be transferring the permission flags, so clear them.
9971                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9972                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9973                            changedInstallPermission = true;
9974                        }
9975
9976                        // If the permission is not to be promoted to runtime we ignore it and
9977                        // also its other flags as they are not applicable to install permissions.
9978                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9979                            for (int userId : currentUserIds) {
9980                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9981                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9982                                    // Transfer the permission flags.
9983                                    permissionsState.updatePermissionFlags(bp, userId,
9984                                            flags, flags);
9985                                    // If we granted the permission, we have to write.
9986                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9987                                            changedRuntimePermissionUserIds, userId);
9988                                }
9989                            }
9990                        }
9991                    } break;
9992
9993                    default: {
9994                        if (packageOfInterest == null
9995                                || packageOfInterest.equals(pkg.packageName)) {
9996                            Slog.w(TAG, "Not granting permission " + perm
9997                                    + " to package " + pkg.packageName
9998                                    + " because it was previously installed without");
9999                        }
10000                    } break;
10001                }
10002            } else {
10003                if (permissionsState.revokeInstallPermission(bp) !=
10004                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10005                    // Also drop the permission flags.
10006                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10007                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10008                    changedInstallPermission = true;
10009                    Slog.i(TAG, "Un-granting permission " + perm
10010                            + " from package " + pkg.packageName
10011                            + " (protectionLevel=" + bp.protectionLevel
10012                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10013                            + ")");
10014                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10015                    // Don't print warning for app op permissions, since it is fine for them
10016                    // not to be granted, there is a UI for the user to decide.
10017                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10018                        Slog.w(TAG, "Not granting permission " + perm
10019                                + " to package " + pkg.packageName
10020                                + " (protectionLevel=" + bp.protectionLevel
10021                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10022                                + ")");
10023                    }
10024                }
10025            }
10026        }
10027
10028        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10029                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10030            // This is the first that we have heard about this package, so the
10031            // permissions we have now selected are fixed until explicitly
10032            // changed.
10033            ps.installPermissionsFixed = true;
10034        }
10035
10036        // Persist the runtime permissions state for users with changes. If permissions
10037        // were revoked because no app in the shared user declares them we have to
10038        // write synchronously to avoid losing runtime permissions state.
10039        for (int userId : changedRuntimePermissionUserIds) {
10040            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10041        }
10042
10043        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10044    }
10045
10046    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10047        boolean allowed = false;
10048        final int NP = PackageParser.NEW_PERMISSIONS.length;
10049        for (int ip=0; ip<NP; ip++) {
10050            final PackageParser.NewPermissionInfo npi
10051                    = PackageParser.NEW_PERMISSIONS[ip];
10052            if (npi.name.equals(perm)
10053                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10054                allowed = true;
10055                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10056                        + pkg.packageName);
10057                break;
10058            }
10059        }
10060        return allowed;
10061    }
10062
10063    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10064            BasePermission bp, PermissionsState origPermissions) {
10065        boolean allowed;
10066        allowed = (compareSignatures(
10067                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10068                        == PackageManager.SIGNATURE_MATCH)
10069                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10070                        == PackageManager.SIGNATURE_MATCH);
10071        if (!allowed && (bp.protectionLevel
10072                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10073            if (isSystemApp(pkg)) {
10074                // For updated system applications, a system permission
10075                // is granted only if it had been defined by the original application.
10076                if (pkg.isUpdatedSystemApp()) {
10077                    final PackageSetting sysPs = mSettings
10078                            .getDisabledSystemPkgLPr(pkg.packageName);
10079                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10080                        // If the original was granted this permission, we take
10081                        // that grant decision as read and propagate it to the
10082                        // update.
10083                        if (sysPs.isPrivileged()) {
10084                            allowed = true;
10085                        }
10086                    } else {
10087                        // The system apk may have been updated with an older
10088                        // version of the one on the data partition, but which
10089                        // granted a new system permission that it didn't have
10090                        // before.  In this case we do want to allow the app to
10091                        // now get the new permission if the ancestral apk is
10092                        // privileged to get it.
10093                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10094                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10095                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10096                                    allowed = true;
10097                                    break;
10098                                }
10099                            }
10100                        }
10101                        // Also if a privileged parent package on the system image or any of
10102                        // its children requested a privileged permission, the updated child
10103                        // packages can also get the permission.
10104                        if (pkg.parentPackage != null) {
10105                            final PackageSetting disabledSysParentPs = mSettings
10106                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10107                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10108                                    && disabledSysParentPs.isPrivileged()) {
10109                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10110                                    allowed = true;
10111                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10112                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10113                                    for (int i = 0; i < count; i++) {
10114                                        PackageParser.Package disabledSysChildPkg =
10115                                                disabledSysParentPs.pkg.childPackages.get(i);
10116                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10117                                                perm)) {
10118                                            allowed = true;
10119                                            break;
10120                                        }
10121                                    }
10122                                }
10123                            }
10124                        }
10125                    }
10126                } else {
10127                    allowed = isPrivilegedApp(pkg);
10128                }
10129            }
10130        }
10131        if (!allowed) {
10132            if (!allowed && (bp.protectionLevel
10133                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10134                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10135                // If this was a previously normal/dangerous permission that got moved
10136                // to a system permission as part of the runtime permission redesign, then
10137                // we still want to blindly grant it to old apps.
10138                allowed = true;
10139            }
10140            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10141                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10142                // If this permission is to be granted to the system installer and
10143                // this app is an installer, then it gets the permission.
10144                allowed = true;
10145            }
10146            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10147                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10148                // If this permission is to be granted to the system verifier and
10149                // this app is a verifier, then it gets the permission.
10150                allowed = true;
10151            }
10152            if (!allowed && (bp.protectionLevel
10153                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10154                    && isSystemApp(pkg)) {
10155                // Any pre-installed system app is allowed to get this permission.
10156                allowed = true;
10157            }
10158            if (!allowed && (bp.protectionLevel
10159                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10160                // For development permissions, a development permission
10161                // is granted only if it was already granted.
10162                allowed = origPermissions.hasInstallPermission(perm);
10163            }
10164            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10165                    && pkg.packageName.equals(mSetupWizardPackage)) {
10166                // If this permission is to be granted to the system setup wizard and
10167                // this app is a setup wizard, then it gets the permission.
10168                allowed = true;
10169            }
10170        }
10171        return allowed;
10172    }
10173
10174    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10175        final int permCount = pkg.requestedPermissions.size();
10176        for (int j = 0; j < permCount; j++) {
10177            String requestedPermission = pkg.requestedPermissions.get(j);
10178            if (permission.equals(requestedPermission)) {
10179                return true;
10180            }
10181        }
10182        return false;
10183    }
10184
10185    final class ActivityIntentResolver
10186            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10187        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10188                boolean defaultOnly, int userId) {
10189            if (!sUserManager.exists(userId)) return null;
10190            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10191            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10192        }
10193
10194        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10195                int userId) {
10196            if (!sUserManager.exists(userId)) return null;
10197            mFlags = flags;
10198            return super.queryIntent(intent, resolvedType,
10199                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10200        }
10201
10202        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10203                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10204            if (!sUserManager.exists(userId)) return null;
10205            if (packageActivities == null) {
10206                return null;
10207            }
10208            mFlags = flags;
10209            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10210            final int N = packageActivities.size();
10211            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10212                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10213
10214            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10215            for (int i = 0; i < N; ++i) {
10216                intentFilters = packageActivities.get(i).intents;
10217                if (intentFilters != null && intentFilters.size() > 0) {
10218                    PackageParser.ActivityIntentInfo[] array =
10219                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10220                    intentFilters.toArray(array);
10221                    listCut.add(array);
10222                }
10223            }
10224            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10225        }
10226
10227        /**
10228         * Finds a privileged activity that matches the specified activity names.
10229         */
10230        private PackageParser.Activity findMatchingActivity(
10231                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10232            for (PackageParser.Activity sysActivity : activityList) {
10233                if (sysActivity.info.name.equals(activityInfo.name)) {
10234                    return sysActivity;
10235                }
10236                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10237                    return sysActivity;
10238                }
10239                if (sysActivity.info.targetActivity != null) {
10240                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10241                        return sysActivity;
10242                    }
10243                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10244                        return sysActivity;
10245                    }
10246                }
10247            }
10248            return null;
10249        }
10250
10251        public class IterGenerator<E> {
10252            public Iterator<E> generate(ActivityIntentInfo info) {
10253                return null;
10254            }
10255        }
10256
10257        public class ActionIterGenerator extends IterGenerator<String> {
10258            @Override
10259            public Iterator<String> generate(ActivityIntentInfo info) {
10260                return info.actionsIterator();
10261            }
10262        }
10263
10264        public class CategoriesIterGenerator extends IterGenerator<String> {
10265            @Override
10266            public Iterator<String> generate(ActivityIntentInfo info) {
10267                return info.categoriesIterator();
10268            }
10269        }
10270
10271        public class SchemesIterGenerator extends IterGenerator<String> {
10272            @Override
10273            public Iterator<String> generate(ActivityIntentInfo info) {
10274                return info.schemesIterator();
10275            }
10276        }
10277
10278        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10279            @Override
10280            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10281                return info.authoritiesIterator();
10282            }
10283        }
10284
10285        /**
10286         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10287         * MODIFIED. Do not pass in a list that should not be changed.
10288         */
10289        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10290                IterGenerator<T> generator, Iterator<T> searchIterator) {
10291            // loop through the set of actions; every one must be found in the intent filter
10292            while (searchIterator.hasNext()) {
10293                // we must have at least one filter in the list to consider a match
10294                if (intentList.size() == 0) {
10295                    break;
10296                }
10297
10298                final T searchAction = searchIterator.next();
10299
10300                // loop through the set of intent filters
10301                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10302                while (intentIter.hasNext()) {
10303                    final ActivityIntentInfo intentInfo = intentIter.next();
10304                    boolean selectionFound = false;
10305
10306                    // loop through the intent filter's selection criteria; at least one
10307                    // of them must match the searched criteria
10308                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10309                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10310                        final T intentSelection = intentSelectionIter.next();
10311                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10312                            selectionFound = true;
10313                            break;
10314                        }
10315                    }
10316
10317                    // the selection criteria wasn't found in this filter's set; this filter
10318                    // is not a potential match
10319                    if (!selectionFound) {
10320                        intentIter.remove();
10321                    }
10322                }
10323            }
10324        }
10325
10326        private boolean isProtectedAction(ActivityIntentInfo filter) {
10327            final Iterator<String> actionsIter = filter.actionsIterator();
10328            while (actionsIter != null && actionsIter.hasNext()) {
10329                final String filterAction = actionsIter.next();
10330                if (PROTECTED_ACTIONS.contains(filterAction)) {
10331                    return true;
10332                }
10333            }
10334            return false;
10335        }
10336
10337        /**
10338         * Adjusts the priority of the given intent filter according to policy.
10339         * <p>
10340         * <ul>
10341         * <li>The priority for non privileged applications is capped to '0'</li>
10342         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10343         * <li>The priority for unbundled updates to privileged applications is capped to the
10344         *      priority defined on the system partition</li>
10345         * </ul>
10346         * <p>
10347         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10348         * allowed to obtain any priority on any action.
10349         */
10350        private void adjustPriority(
10351                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10352            // nothing to do; priority is fine as-is
10353            if (intent.getPriority() <= 0) {
10354                return;
10355            }
10356
10357            final ActivityInfo activityInfo = intent.activity.info;
10358            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10359
10360            final boolean privilegedApp =
10361                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10362            if (!privilegedApp) {
10363                // non-privileged applications can never define a priority >0
10364                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10365                        + " package: " + applicationInfo.packageName
10366                        + " activity: " + intent.activity.className
10367                        + " origPrio: " + intent.getPriority());
10368                intent.setPriority(0);
10369                return;
10370            }
10371
10372            if (systemActivities == null) {
10373                // the system package is not disabled; we're parsing the system partition
10374                if (isProtectedAction(intent)) {
10375                    if (mDeferProtectedFilters) {
10376                        // We can't deal with these just yet. No component should ever obtain a
10377                        // >0 priority for a protected actions, with ONE exception -- the setup
10378                        // wizard. The setup wizard, however, cannot be known until we're able to
10379                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10380                        // until all intent filters have been processed. Chicken, meet egg.
10381                        // Let the filter temporarily have a high priority and rectify the
10382                        // priorities after all system packages have been scanned.
10383                        mProtectedFilters.add(intent);
10384                        if (DEBUG_FILTERS) {
10385                            Slog.i(TAG, "Protected action; save for later;"
10386                                    + " package: " + applicationInfo.packageName
10387                                    + " activity: " + intent.activity.className
10388                                    + " origPrio: " + intent.getPriority());
10389                        }
10390                        return;
10391                    } else {
10392                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10393                            Slog.i(TAG, "No setup wizard;"
10394                                + " All protected intents capped to priority 0");
10395                        }
10396                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10397                            if (DEBUG_FILTERS) {
10398                                Slog.i(TAG, "Found setup wizard;"
10399                                    + " allow priority " + intent.getPriority() + ";"
10400                                    + " package: " + intent.activity.info.packageName
10401                                    + " activity: " + intent.activity.className
10402                                    + " priority: " + intent.getPriority());
10403                            }
10404                            // setup wizard gets whatever it wants
10405                            return;
10406                        }
10407                        Slog.w(TAG, "Protected action; cap priority to 0;"
10408                                + " package: " + intent.activity.info.packageName
10409                                + " activity: " + intent.activity.className
10410                                + " origPrio: " + intent.getPriority());
10411                        intent.setPriority(0);
10412                        return;
10413                    }
10414                }
10415                // privileged apps on the system image get whatever priority they request
10416                return;
10417            }
10418
10419            // privileged app unbundled update ... try to find the same activity
10420            final PackageParser.Activity foundActivity =
10421                    findMatchingActivity(systemActivities, activityInfo);
10422            if (foundActivity == null) {
10423                // this is a new activity; it cannot obtain >0 priority
10424                if (DEBUG_FILTERS) {
10425                    Slog.i(TAG, "New activity; cap priority to 0;"
10426                            + " package: " + applicationInfo.packageName
10427                            + " activity: " + intent.activity.className
10428                            + " origPrio: " + intent.getPriority());
10429                }
10430                intent.setPriority(0);
10431                return;
10432            }
10433
10434            // found activity, now check for filter equivalence
10435
10436            // a shallow copy is enough; we modify the list, not its contents
10437            final List<ActivityIntentInfo> intentListCopy =
10438                    new ArrayList<>(foundActivity.intents);
10439            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10440
10441            // find matching action subsets
10442            final Iterator<String> actionsIterator = intent.actionsIterator();
10443            if (actionsIterator != null) {
10444                getIntentListSubset(
10445                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10446                if (intentListCopy.size() == 0) {
10447                    // no more intents to match; we're not equivalent
10448                    if (DEBUG_FILTERS) {
10449                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10450                                + " package: " + applicationInfo.packageName
10451                                + " activity: " + intent.activity.className
10452                                + " origPrio: " + intent.getPriority());
10453                    }
10454                    intent.setPriority(0);
10455                    return;
10456                }
10457            }
10458
10459            // find matching category subsets
10460            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10461            if (categoriesIterator != null) {
10462                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10463                        categoriesIterator);
10464                if (intentListCopy.size() == 0) {
10465                    // no more intents to match; we're not equivalent
10466                    if (DEBUG_FILTERS) {
10467                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10468                                + " package: " + applicationInfo.packageName
10469                                + " activity: " + intent.activity.className
10470                                + " origPrio: " + intent.getPriority());
10471                    }
10472                    intent.setPriority(0);
10473                    return;
10474                }
10475            }
10476
10477            // find matching schemes subsets
10478            final Iterator<String> schemesIterator = intent.schemesIterator();
10479            if (schemesIterator != null) {
10480                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10481                        schemesIterator);
10482                if (intentListCopy.size() == 0) {
10483                    // no more intents to match; we're not equivalent
10484                    if (DEBUG_FILTERS) {
10485                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10486                                + " package: " + applicationInfo.packageName
10487                                + " activity: " + intent.activity.className
10488                                + " origPrio: " + intent.getPriority());
10489                    }
10490                    intent.setPriority(0);
10491                    return;
10492                }
10493            }
10494
10495            // find matching authorities subsets
10496            final Iterator<IntentFilter.AuthorityEntry>
10497                    authoritiesIterator = intent.authoritiesIterator();
10498            if (authoritiesIterator != null) {
10499                getIntentListSubset(intentListCopy,
10500                        new AuthoritiesIterGenerator(),
10501                        authoritiesIterator);
10502                if (intentListCopy.size() == 0) {
10503                    // no more intents to match; we're not equivalent
10504                    if (DEBUG_FILTERS) {
10505                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10506                                + " package: " + applicationInfo.packageName
10507                                + " activity: " + intent.activity.className
10508                                + " origPrio: " + intent.getPriority());
10509                    }
10510                    intent.setPriority(0);
10511                    return;
10512                }
10513            }
10514
10515            // we found matching filter(s); app gets the max priority of all intents
10516            int cappedPriority = 0;
10517            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10518                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10519            }
10520            if (intent.getPriority() > cappedPriority) {
10521                if (DEBUG_FILTERS) {
10522                    Slog.i(TAG, "Found matching filter(s);"
10523                            + " cap priority to " + cappedPriority + ";"
10524                            + " package: " + applicationInfo.packageName
10525                            + " activity: " + intent.activity.className
10526                            + " origPrio: " + intent.getPriority());
10527                }
10528                intent.setPriority(cappedPriority);
10529                return;
10530            }
10531            // all this for nothing; the requested priority was <= what was on the system
10532        }
10533
10534        public final void addActivity(PackageParser.Activity a, String type) {
10535            mActivities.put(a.getComponentName(), a);
10536            if (DEBUG_SHOW_INFO)
10537                Log.v(
10538                TAG, "  " + type + " " +
10539                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10540            if (DEBUG_SHOW_INFO)
10541                Log.v(TAG, "    Class=" + a.info.name);
10542            final int NI = a.intents.size();
10543            for (int j=0; j<NI; j++) {
10544                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10545                if ("activity".equals(type)) {
10546                    final PackageSetting ps =
10547                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10548                    final List<PackageParser.Activity> systemActivities =
10549                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10550                    adjustPriority(systemActivities, intent);
10551                }
10552                if (DEBUG_SHOW_INFO) {
10553                    Log.v(TAG, "    IntentFilter:");
10554                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10555                }
10556                if (!intent.debugCheck()) {
10557                    Log.w(TAG, "==> For Activity " + a.info.name);
10558                }
10559                addFilter(intent);
10560            }
10561        }
10562
10563        public final void removeActivity(PackageParser.Activity a, String type) {
10564            mActivities.remove(a.getComponentName());
10565            if (DEBUG_SHOW_INFO) {
10566                Log.v(TAG, "  " + type + " "
10567                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10568                                : a.info.name) + ":");
10569                Log.v(TAG, "    Class=" + a.info.name);
10570            }
10571            final int NI = a.intents.size();
10572            for (int j=0; j<NI; j++) {
10573                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10574                if (DEBUG_SHOW_INFO) {
10575                    Log.v(TAG, "    IntentFilter:");
10576                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10577                }
10578                removeFilter(intent);
10579            }
10580        }
10581
10582        @Override
10583        protected boolean allowFilterResult(
10584                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10585            ActivityInfo filterAi = filter.activity.info;
10586            for (int i=dest.size()-1; i>=0; i--) {
10587                ActivityInfo destAi = dest.get(i).activityInfo;
10588                if (destAi.name == filterAi.name
10589                        && destAi.packageName == filterAi.packageName) {
10590                    return false;
10591                }
10592            }
10593            return true;
10594        }
10595
10596        @Override
10597        protected ActivityIntentInfo[] newArray(int size) {
10598            return new ActivityIntentInfo[size];
10599        }
10600
10601        @Override
10602        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10603            if (!sUserManager.exists(userId)) return true;
10604            PackageParser.Package p = filter.activity.owner;
10605            if (p != null) {
10606                PackageSetting ps = (PackageSetting)p.mExtras;
10607                if (ps != null) {
10608                    // System apps are never considered stopped for purposes of
10609                    // filtering, because there may be no way for the user to
10610                    // actually re-launch them.
10611                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10612                            && ps.getStopped(userId);
10613                }
10614            }
10615            return false;
10616        }
10617
10618        @Override
10619        protected boolean isPackageForFilter(String packageName,
10620                PackageParser.ActivityIntentInfo info) {
10621            return packageName.equals(info.activity.owner.packageName);
10622        }
10623
10624        @Override
10625        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10626                int match, int userId) {
10627            if (!sUserManager.exists(userId)) return null;
10628            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10629                return null;
10630            }
10631            final PackageParser.Activity activity = info.activity;
10632            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10633            if (ps == null) {
10634                return null;
10635            }
10636            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10637                    ps.readUserState(userId), userId);
10638            if (ai == null) {
10639                return null;
10640            }
10641            final ResolveInfo res = new ResolveInfo();
10642            res.activityInfo = ai;
10643            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10644                res.filter = info;
10645            }
10646            if (info != null) {
10647                res.handleAllWebDataURI = info.handleAllWebDataURI();
10648            }
10649            res.priority = info.getPriority();
10650            res.preferredOrder = activity.owner.mPreferredOrder;
10651            //System.out.println("Result: " + res.activityInfo.className +
10652            //                   " = " + res.priority);
10653            res.match = match;
10654            res.isDefault = info.hasDefault;
10655            res.labelRes = info.labelRes;
10656            res.nonLocalizedLabel = info.nonLocalizedLabel;
10657            if (userNeedsBadging(userId)) {
10658                res.noResourceId = true;
10659            } else {
10660                res.icon = info.icon;
10661            }
10662            res.iconResourceId = info.icon;
10663            res.system = res.activityInfo.applicationInfo.isSystemApp();
10664            return res;
10665        }
10666
10667        @Override
10668        protected void sortResults(List<ResolveInfo> results) {
10669            Collections.sort(results, mResolvePrioritySorter);
10670        }
10671
10672        @Override
10673        protected void dumpFilter(PrintWriter out, String prefix,
10674                PackageParser.ActivityIntentInfo filter) {
10675            out.print(prefix); out.print(
10676                    Integer.toHexString(System.identityHashCode(filter.activity)));
10677                    out.print(' ');
10678                    filter.activity.printComponentShortName(out);
10679                    out.print(" filter ");
10680                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10681        }
10682
10683        @Override
10684        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10685            return filter.activity;
10686        }
10687
10688        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10689            PackageParser.Activity activity = (PackageParser.Activity)label;
10690            out.print(prefix); out.print(
10691                    Integer.toHexString(System.identityHashCode(activity)));
10692                    out.print(' ');
10693                    activity.printComponentShortName(out);
10694            if (count > 1) {
10695                out.print(" ("); out.print(count); out.print(" filters)");
10696            }
10697            out.println();
10698        }
10699
10700        // Keys are String (activity class name), values are Activity.
10701        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10702                = new ArrayMap<ComponentName, PackageParser.Activity>();
10703        private int mFlags;
10704    }
10705
10706    private final class ServiceIntentResolver
10707            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10708        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10709                boolean defaultOnly, int userId) {
10710            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10711            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10712        }
10713
10714        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10715                int userId) {
10716            if (!sUserManager.exists(userId)) return null;
10717            mFlags = flags;
10718            return super.queryIntent(intent, resolvedType,
10719                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10720        }
10721
10722        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10723                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10724            if (!sUserManager.exists(userId)) return null;
10725            if (packageServices == null) {
10726                return null;
10727            }
10728            mFlags = flags;
10729            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10730            final int N = packageServices.size();
10731            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10732                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10733
10734            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10735            for (int i = 0; i < N; ++i) {
10736                intentFilters = packageServices.get(i).intents;
10737                if (intentFilters != null && intentFilters.size() > 0) {
10738                    PackageParser.ServiceIntentInfo[] array =
10739                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10740                    intentFilters.toArray(array);
10741                    listCut.add(array);
10742                }
10743            }
10744            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10745        }
10746
10747        public final void addService(PackageParser.Service s) {
10748            mServices.put(s.getComponentName(), s);
10749            if (DEBUG_SHOW_INFO) {
10750                Log.v(TAG, "  "
10751                        + (s.info.nonLocalizedLabel != null
10752                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10753                Log.v(TAG, "    Class=" + s.info.name);
10754            }
10755            final int NI = s.intents.size();
10756            int j;
10757            for (j=0; j<NI; j++) {
10758                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10759                if (DEBUG_SHOW_INFO) {
10760                    Log.v(TAG, "    IntentFilter:");
10761                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10762                }
10763                if (!intent.debugCheck()) {
10764                    Log.w(TAG, "==> For Service " + s.info.name);
10765                }
10766                addFilter(intent);
10767            }
10768        }
10769
10770        public final void removeService(PackageParser.Service s) {
10771            mServices.remove(s.getComponentName());
10772            if (DEBUG_SHOW_INFO) {
10773                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10774                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10775                Log.v(TAG, "    Class=" + s.info.name);
10776            }
10777            final int NI = s.intents.size();
10778            int j;
10779            for (j=0; j<NI; j++) {
10780                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10781                if (DEBUG_SHOW_INFO) {
10782                    Log.v(TAG, "    IntentFilter:");
10783                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10784                }
10785                removeFilter(intent);
10786            }
10787        }
10788
10789        @Override
10790        protected boolean allowFilterResult(
10791                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10792            ServiceInfo filterSi = filter.service.info;
10793            for (int i=dest.size()-1; i>=0; i--) {
10794                ServiceInfo destAi = dest.get(i).serviceInfo;
10795                if (destAi.name == filterSi.name
10796                        && destAi.packageName == filterSi.packageName) {
10797                    return false;
10798                }
10799            }
10800            return true;
10801        }
10802
10803        @Override
10804        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10805            return new PackageParser.ServiceIntentInfo[size];
10806        }
10807
10808        @Override
10809        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10810            if (!sUserManager.exists(userId)) return true;
10811            PackageParser.Package p = filter.service.owner;
10812            if (p != null) {
10813                PackageSetting ps = (PackageSetting)p.mExtras;
10814                if (ps != null) {
10815                    // System apps are never considered stopped for purposes of
10816                    // filtering, because there may be no way for the user to
10817                    // actually re-launch them.
10818                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10819                            && ps.getStopped(userId);
10820                }
10821            }
10822            return false;
10823        }
10824
10825        @Override
10826        protected boolean isPackageForFilter(String packageName,
10827                PackageParser.ServiceIntentInfo info) {
10828            return packageName.equals(info.service.owner.packageName);
10829        }
10830
10831        @Override
10832        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10833                int match, int userId) {
10834            if (!sUserManager.exists(userId)) return null;
10835            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10836            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10837                return null;
10838            }
10839            final PackageParser.Service service = info.service;
10840            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10841            if (ps == null) {
10842                return null;
10843            }
10844            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10845                    ps.readUserState(userId), userId);
10846            if (si == null) {
10847                return null;
10848            }
10849            final ResolveInfo res = new ResolveInfo();
10850            res.serviceInfo = si;
10851            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10852                res.filter = filter;
10853            }
10854            res.priority = info.getPriority();
10855            res.preferredOrder = service.owner.mPreferredOrder;
10856            res.match = match;
10857            res.isDefault = info.hasDefault;
10858            res.labelRes = info.labelRes;
10859            res.nonLocalizedLabel = info.nonLocalizedLabel;
10860            res.icon = info.icon;
10861            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10862            return res;
10863        }
10864
10865        @Override
10866        protected void sortResults(List<ResolveInfo> results) {
10867            Collections.sort(results, mResolvePrioritySorter);
10868        }
10869
10870        @Override
10871        protected void dumpFilter(PrintWriter out, String prefix,
10872                PackageParser.ServiceIntentInfo filter) {
10873            out.print(prefix); out.print(
10874                    Integer.toHexString(System.identityHashCode(filter.service)));
10875                    out.print(' ');
10876                    filter.service.printComponentShortName(out);
10877                    out.print(" filter ");
10878                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10879        }
10880
10881        @Override
10882        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10883            return filter.service;
10884        }
10885
10886        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10887            PackageParser.Service service = (PackageParser.Service)label;
10888            out.print(prefix); out.print(
10889                    Integer.toHexString(System.identityHashCode(service)));
10890                    out.print(' ');
10891                    service.printComponentShortName(out);
10892            if (count > 1) {
10893                out.print(" ("); out.print(count); out.print(" filters)");
10894            }
10895            out.println();
10896        }
10897
10898//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10899//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10900//            final List<ResolveInfo> retList = Lists.newArrayList();
10901//            while (i.hasNext()) {
10902//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10903//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10904//                    retList.add(resolveInfo);
10905//                }
10906//            }
10907//            return retList;
10908//        }
10909
10910        // Keys are String (activity class name), values are Activity.
10911        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10912                = new ArrayMap<ComponentName, PackageParser.Service>();
10913        private int mFlags;
10914    };
10915
10916    private final class ProviderIntentResolver
10917            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10918        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10919                boolean defaultOnly, int userId) {
10920            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10921            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10922        }
10923
10924        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10925                int userId) {
10926            if (!sUserManager.exists(userId))
10927                return null;
10928            mFlags = flags;
10929            return super.queryIntent(intent, resolvedType,
10930                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10931        }
10932
10933        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10934                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10935            if (!sUserManager.exists(userId))
10936                return null;
10937            if (packageProviders == null) {
10938                return null;
10939            }
10940            mFlags = flags;
10941            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10942            final int N = packageProviders.size();
10943            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10944                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10945
10946            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10947            for (int i = 0; i < N; ++i) {
10948                intentFilters = packageProviders.get(i).intents;
10949                if (intentFilters != null && intentFilters.size() > 0) {
10950                    PackageParser.ProviderIntentInfo[] array =
10951                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10952                    intentFilters.toArray(array);
10953                    listCut.add(array);
10954                }
10955            }
10956            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10957        }
10958
10959        public final void addProvider(PackageParser.Provider p) {
10960            if (mProviders.containsKey(p.getComponentName())) {
10961                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10962                return;
10963            }
10964
10965            mProviders.put(p.getComponentName(), p);
10966            if (DEBUG_SHOW_INFO) {
10967                Log.v(TAG, "  "
10968                        + (p.info.nonLocalizedLabel != null
10969                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10970                Log.v(TAG, "    Class=" + p.info.name);
10971            }
10972            final int NI = p.intents.size();
10973            int j;
10974            for (j = 0; j < NI; j++) {
10975                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10976                if (DEBUG_SHOW_INFO) {
10977                    Log.v(TAG, "    IntentFilter:");
10978                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10979                }
10980                if (!intent.debugCheck()) {
10981                    Log.w(TAG, "==> For Provider " + p.info.name);
10982                }
10983                addFilter(intent);
10984            }
10985        }
10986
10987        public final void removeProvider(PackageParser.Provider p) {
10988            mProviders.remove(p.getComponentName());
10989            if (DEBUG_SHOW_INFO) {
10990                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10991                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10992                Log.v(TAG, "    Class=" + p.info.name);
10993            }
10994            final int NI = p.intents.size();
10995            int j;
10996            for (j = 0; j < NI; j++) {
10997                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10998                if (DEBUG_SHOW_INFO) {
10999                    Log.v(TAG, "    IntentFilter:");
11000                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11001                }
11002                removeFilter(intent);
11003            }
11004        }
11005
11006        @Override
11007        protected boolean allowFilterResult(
11008                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11009            ProviderInfo filterPi = filter.provider.info;
11010            for (int i = dest.size() - 1; i >= 0; i--) {
11011                ProviderInfo destPi = dest.get(i).providerInfo;
11012                if (destPi.name == filterPi.name
11013                        && destPi.packageName == filterPi.packageName) {
11014                    return false;
11015                }
11016            }
11017            return true;
11018        }
11019
11020        @Override
11021        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11022            return new PackageParser.ProviderIntentInfo[size];
11023        }
11024
11025        @Override
11026        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11027            if (!sUserManager.exists(userId))
11028                return true;
11029            PackageParser.Package p = filter.provider.owner;
11030            if (p != null) {
11031                PackageSetting ps = (PackageSetting) p.mExtras;
11032                if (ps != null) {
11033                    // System apps are never considered stopped for purposes of
11034                    // filtering, because there may be no way for the user to
11035                    // actually re-launch them.
11036                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11037                            && ps.getStopped(userId);
11038                }
11039            }
11040            return false;
11041        }
11042
11043        @Override
11044        protected boolean isPackageForFilter(String packageName,
11045                PackageParser.ProviderIntentInfo info) {
11046            return packageName.equals(info.provider.owner.packageName);
11047        }
11048
11049        @Override
11050        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11051                int match, int userId) {
11052            if (!sUserManager.exists(userId))
11053                return null;
11054            final PackageParser.ProviderIntentInfo info = filter;
11055            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11056                return null;
11057            }
11058            final PackageParser.Provider provider = info.provider;
11059            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11060            if (ps == null) {
11061                return null;
11062            }
11063            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11064                    ps.readUserState(userId), userId);
11065            if (pi == null) {
11066                return null;
11067            }
11068            final ResolveInfo res = new ResolveInfo();
11069            res.providerInfo = pi;
11070            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11071                res.filter = filter;
11072            }
11073            res.priority = info.getPriority();
11074            res.preferredOrder = provider.owner.mPreferredOrder;
11075            res.match = match;
11076            res.isDefault = info.hasDefault;
11077            res.labelRes = info.labelRes;
11078            res.nonLocalizedLabel = info.nonLocalizedLabel;
11079            res.icon = info.icon;
11080            res.system = res.providerInfo.applicationInfo.isSystemApp();
11081            return res;
11082        }
11083
11084        @Override
11085        protected void sortResults(List<ResolveInfo> results) {
11086            Collections.sort(results, mResolvePrioritySorter);
11087        }
11088
11089        @Override
11090        protected void dumpFilter(PrintWriter out, String prefix,
11091                PackageParser.ProviderIntentInfo filter) {
11092            out.print(prefix);
11093            out.print(
11094                    Integer.toHexString(System.identityHashCode(filter.provider)));
11095            out.print(' ');
11096            filter.provider.printComponentShortName(out);
11097            out.print(" filter ");
11098            out.println(Integer.toHexString(System.identityHashCode(filter)));
11099        }
11100
11101        @Override
11102        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11103            return filter.provider;
11104        }
11105
11106        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11107            PackageParser.Provider provider = (PackageParser.Provider)label;
11108            out.print(prefix); out.print(
11109                    Integer.toHexString(System.identityHashCode(provider)));
11110                    out.print(' ');
11111                    provider.printComponentShortName(out);
11112            if (count > 1) {
11113                out.print(" ("); out.print(count); out.print(" filters)");
11114            }
11115            out.println();
11116        }
11117
11118        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11119                = new ArrayMap<ComponentName, PackageParser.Provider>();
11120        private int mFlags;
11121    }
11122
11123    private static final class EphemeralIntentResolver
11124            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11125        @Override
11126        protected EphemeralResolveIntentInfo[] newArray(int size) {
11127            return new EphemeralResolveIntentInfo[size];
11128        }
11129
11130        @Override
11131        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11132            return true;
11133        }
11134
11135        @Override
11136        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11137                int userId) {
11138            if (!sUserManager.exists(userId)) {
11139                return null;
11140            }
11141            return info.getEphemeralResolveInfo();
11142        }
11143    }
11144
11145    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11146            new Comparator<ResolveInfo>() {
11147        public int compare(ResolveInfo r1, ResolveInfo r2) {
11148            int v1 = r1.priority;
11149            int v2 = r2.priority;
11150            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11151            if (v1 != v2) {
11152                return (v1 > v2) ? -1 : 1;
11153            }
11154            v1 = r1.preferredOrder;
11155            v2 = r2.preferredOrder;
11156            if (v1 != v2) {
11157                return (v1 > v2) ? -1 : 1;
11158            }
11159            if (r1.isDefault != r2.isDefault) {
11160                return r1.isDefault ? -1 : 1;
11161            }
11162            v1 = r1.match;
11163            v2 = r2.match;
11164            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11165            if (v1 != v2) {
11166                return (v1 > v2) ? -1 : 1;
11167            }
11168            if (r1.system != r2.system) {
11169                return r1.system ? -1 : 1;
11170            }
11171            if (r1.activityInfo != null) {
11172                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11173            }
11174            if (r1.serviceInfo != null) {
11175                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11176            }
11177            if (r1.providerInfo != null) {
11178                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11179            }
11180            return 0;
11181        }
11182    };
11183
11184    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11185            new Comparator<ProviderInfo>() {
11186        public int compare(ProviderInfo p1, ProviderInfo p2) {
11187            final int v1 = p1.initOrder;
11188            final int v2 = p2.initOrder;
11189            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11190        }
11191    };
11192
11193    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11194            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11195            final int[] userIds) {
11196        mHandler.post(new Runnable() {
11197            @Override
11198            public void run() {
11199                try {
11200                    final IActivityManager am = ActivityManagerNative.getDefault();
11201                    if (am == null) return;
11202                    final int[] resolvedUserIds;
11203                    if (userIds == null) {
11204                        resolvedUserIds = am.getRunningUserIds();
11205                    } else {
11206                        resolvedUserIds = userIds;
11207                    }
11208                    for (int id : resolvedUserIds) {
11209                        final Intent intent = new Intent(action,
11210                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11211                        if (extras != null) {
11212                            intent.putExtras(extras);
11213                        }
11214                        if (targetPkg != null) {
11215                            intent.setPackage(targetPkg);
11216                        }
11217                        // Modify the UID when posting to other users
11218                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11219                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11220                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11221                            intent.putExtra(Intent.EXTRA_UID, uid);
11222                        }
11223                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11224                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11225                        if (DEBUG_BROADCASTS) {
11226                            RuntimeException here = new RuntimeException("here");
11227                            here.fillInStackTrace();
11228                            Slog.d(TAG, "Sending to user " + id + ": "
11229                                    + intent.toShortString(false, true, false, false)
11230                                    + " " + intent.getExtras(), here);
11231                        }
11232                        am.broadcastIntent(null, intent, null, finishedReceiver,
11233                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11234                                null, finishedReceiver != null, false, id);
11235                    }
11236                } catch (RemoteException ex) {
11237                }
11238            }
11239        });
11240    }
11241
11242    /**
11243     * Check if the external storage media is available. This is true if there
11244     * is a mounted external storage medium or if the external storage is
11245     * emulated.
11246     */
11247    private boolean isExternalMediaAvailable() {
11248        return mMediaMounted || Environment.isExternalStorageEmulated();
11249    }
11250
11251    @Override
11252    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11253        // writer
11254        synchronized (mPackages) {
11255            if (!isExternalMediaAvailable()) {
11256                // If the external storage is no longer mounted at this point,
11257                // the caller may not have been able to delete all of this
11258                // packages files and can not delete any more.  Bail.
11259                return null;
11260            }
11261            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11262            if (lastPackage != null) {
11263                pkgs.remove(lastPackage);
11264            }
11265            if (pkgs.size() > 0) {
11266                return pkgs.get(0);
11267            }
11268        }
11269        return null;
11270    }
11271
11272    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11273        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11274                userId, andCode ? 1 : 0, packageName);
11275        if (mSystemReady) {
11276            msg.sendToTarget();
11277        } else {
11278            if (mPostSystemReadyMessages == null) {
11279                mPostSystemReadyMessages = new ArrayList<>();
11280            }
11281            mPostSystemReadyMessages.add(msg);
11282        }
11283    }
11284
11285    void startCleaningPackages() {
11286        // reader
11287        if (!isExternalMediaAvailable()) {
11288            return;
11289        }
11290        synchronized (mPackages) {
11291            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11292                return;
11293            }
11294        }
11295        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11296        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11297        IActivityManager am = ActivityManagerNative.getDefault();
11298        if (am != null) {
11299            try {
11300                am.startService(null, intent, null, mContext.getOpPackageName(),
11301                        UserHandle.USER_SYSTEM);
11302            } catch (RemoteException e) {
11303            }
11304        }
11305    }
11306
11307    @Override
11308    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11309            int installFlags, String installerPackageName, int userId) {
11310        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11311
11312        final int callingUid = Binder.getCallingUid();
11313        enforceCrossUserPermission(callingUid, userId,
11314                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11315
11316        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11317            try {
11318                if (observer != null) {
11319                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11320                }
11321            } catch (RemoteException re) {
11322            }
11323            return;
11324        }
11325
11326        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11327            installFlags |= PackageManager.INSTALL_FROM_ADB;
11328
11329        } else {
11330            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11331            // about installerPackageName.
11332
11333            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11334            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11335        }
11336
11337        UserHandle user;
11338        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11339            user = UserHandle.ALL;
11340        } else {
11341            user = new UserHandle(userId);
11342        }
11343
11344        // Only system components can circumvent runtime permissions when installing.
11345        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11346                && mContext.checkCallingOrSelfPermission(Manifest.permission
11347                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11348            throw new SecurityException("You need the "
11349                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11350                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11351        }
11352
11353        final File originFile = new File(originPath);
11354        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11355
11356        final Message msg = mHandler.obtainMessage(INIT_COPY);
11357        final VerificationInfo verificationInfo = new VerificationInfo(
11358                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11359        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11360                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11361                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11362                null /*certificates*/);
11363        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11364        msg.obj = params;
11365
11366        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11367                System.identityHashCode(msg.obj));
11368        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11369                System.identityHashCode(msg.obj));
11370
11371        mHandler.sendMessage(msg);
11372    }
11373
11374    void installStage(String packageName, File stagedDir, String stagedCid,
11375            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11376            String installerPackageName, int installerUid, UserHandle user,
11377            Certificate[][] certificates) {
11378        if (DEBUG_EPHEMERAL) {
11379            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11380                Slog.d(TAG, "Ephemeral install of " + packageName);
11381            }
11382        }
11383        final VerificationInfo verificationInfo = new VerificationInfo(
11384                sessionParams.originatingUri, sessionParams.referrerUri,
11385                sessionParams.originatingUid, installerUid);
11386
11387        final OriginInfo origin;
11388        if (stagedDir != null) {
11389            origin = OriginInfo.fromStagedFile(stagedDir);
11390        } else {
11391            origin = OriginInfo.fromStagedContainer(stagedCid);
11392        }
11393
11394        final Message msg = mHandler.obtainMessage(INIT_COPY);
11395        final InstallParams params = new InstallParams(origin, null, observer,
11396                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11397                verificationInfo, user, sessionParams.abiOverride,
11398                sessionParams.grantedRuntimePermissions, certificates);
11399        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11400        msg.obj = params;
11401
11402        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11403                System.identityHashCode(msg.obj));
11404        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11405                System.identityHashCode(msg.obj));
11406
11407        mHandler.sendMessage(msg);
11408    }
11409
11410    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11411            int userId) {
11412        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11413        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11414    }
11415
11416    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11417            int appId, int userId) {
11418        Bundle extras = new Bundle(1);
11419        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11420
11421        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11422                packageName, extras, 0, null, null, new int[] {userId});
11423        try {
11424            IActivityManager am = ActivityManagerNative.getDefault();
11425            if (isSystem && am.isUserRunning(userId, 0)) {
11426                // The just-installed/enabled app is bundled on the system, so presumed
11427                // to be able to run automatically without needing an explicit launch.
11428                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11429                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11430                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11431                        .setPackage(packageName);
11432                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11433                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11434            }
11435        } catch (RemoteException e) {
11436            // shouldn't happen
11437            Slog.w(TAG, "Unable to bootstrap installed package", e);
11438        }
11439    }
11440
11441    @Override
11442    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11443            int userId) {
11444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11445        PackageSetting pkgSetting;
11446        final int uid = Binder.getCallingUid();
11447        enforceCrossUserPermission(uid, userId,
11448                true /* requireFullPermission */, true /* checkShell */,
11449                "setApplicationHiddenSetting for user " + userId);
11450
11451        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11452            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11453            return false;
11454        }
11455
11456        long callingId = Binder.clearCallingIdentity();
11457        try {
11458            boolean sendAdded = false;
11459            boolean sendRemoved = false;
11460            // writer
11461            synchronized (mPackages) {
11462                pkgSetting = mSettings.mPackages.get(packageName);
11463                if (pkgSetting == null) {
11464                    return false;
11465                }
11466                if (pkgSetting.getHidden(userId) != hidden) {
11467                    pkgSetting.setHidden(hidden, userId);
11468                    mSettings.writePackageRestrictionsLPr(userId);
11469                    if (hidden) {
11470                        sendRemoved = true;
11471                    } else {
11472                        sendAdded = true;
11473                    }
11474                }
11475            }
11476            if (sendAdded) {
11477                sendPackageAddedForUser(packageName, pkgSetting, userId);
11478                return true;
11479            }
11480            if (sendRemoved) {
11481                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11482                        "hiding pkg");
11483                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11484                return true;
11485            }
11486        } finally {
11487            Binder.restoreCallingIdentity(callingId);
11488        }
11489        return false;
11490    }
11491
11492    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11493            int userId) {
11494        final PackageRemovedInfo info = new PackageRemovedInfo();
11495        info.removedPackage = packageName;
11496        info.removedUsers = new int[] {userId};
11497        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11498        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11499    }
11500
11501    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11502        if (pkgList.length > 0) {
11503            Bundle extras = new Bundle(1);
11504            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11505
11506            sendPackageBroadcast(
11507                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11508                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11509                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11510                    new int[] {userId});
11511        }
11512    }
11513
11514    /**
11515     * Returns true if application is not found or there was an error. Otherwise it returns
11516     * the hidden state of the package for the given user.
11517     */
11518    @Override
11519    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11520        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11521        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11522                true /* requireFullPermission */, false /* checkShell */,
11523                "getApplicationHidden for user " + userId);
11524        PackageSetting pkgSetting;
11525        long callingId = Binder.clearCallingIdentity();
11526        try {
11527            // writer
11528            synchronized (mPackages) {
11529                pkgSetting = mSettings.mPackages.get(packageName);
11530                if (pkgSetting == null) {
11531                    return true;
11532                }
11533                return pkgSetting.getHidden(userId);
11534            }
11535        } finally {
11536            Binder.restoreCallingIdentity(callingId);
11537        }
11538    }
11539
11540    /**
11541     * @hide
11542     */
11543    @Override
11544    public int installExistingPackageAsUser(String packageName, int userId) {
11545        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11546                null);
11547        PackageSetting pkgSetting;
11548        final int uid = Binder.getCallingUid();
11549        enforceCrossUserPermission(uid, userId,
11550                true /* requireFullPermission */, true /* checkShell */,
11551                "installExistingPackage for user " + userId);
11552        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11553            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11554        }
11555
11556        long callingId = Binder.clearCallingIdentity();
11557        try {
11558            boolean installed = false;
11559
11560            // writer
11561            synchronized (mPackages) {
11562                pkgSetting = mSettings.mPackages.get(packageName);
11563                if (pkgSetting == null) {
11564                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11565                }
11566                if (!pkgSetting.getInstalled(userId)) {
11567                    pkgSetting.setInstalled(true, userId);
11568                    pkgSetting.setHidden(false, userId);
11569                    mSettings.writePackageRestrictionsLPr(userId);
11570                    installed = true;
11571                }
11572            }
11573
11574            if (installed) {
11575                if (pkgSetting.pkg != null) {
11576                    synchronized (mInstallLock) {
11577                        // We don't need to freeze for a brand new install
11578                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11579                    }
11580                }
11581                sendPackageAddedForUser(packageName, pkgSetting, userId);
11582            }
11583        } finally {
11584            Binder.restoreCallingIdentity(callingId);
11585        }
11586
11587        return PackageManager.INSTALL_SUCCEEDED;
11588    }
11589
11590    boolean isUserRestricted(int userId, String restrictionKey) {
11591        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11592        if (restrictions.getBoolean(restrictionKey, false)) {
11593            Log.w(TAG, "User is restricted: " + restrictionKey);
11594            return true;
11595        }
11596        return false;
11597    }
11598
11599    @Override
11600    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11601            int userId) {
11602        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11603        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11604                true /* requireFullPermission */, true /* checkShell */,
11605                "setPackagesSuspended for user " + userId);
11606
11607        if (ArrayUtils.isEmpty(packageNames)) {
11608            return packageNames;
11609        }
11610
11611        // List of package names for whom the suspended state has changed.
11612        List<String> changedPackages = new ArrayList<>(packageNames.length);
11613        // List of package names for whom the suspended state is not set as requested in this
11614        // method.
11615        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11616        long callingId = Binder.clearCallingIdentity();
11617        try {
11618            for (int i = 0; i < packageNames.length; i++) {
11619                String packageName = packageNames[i];
11620                boolean changed = false;
11621                final int appId;
11622                synchronized (mPackages) {
11623                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11624                    if (pkgSetting == null) {
11625                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11626                                + "\". Skipping suspending/un-suspending.");
11627                        unactionedPackages.add(packageName);
11628                        continue;
11629                    }
11630                    appId = pkgSetting.appId;
11631                    if (pkgSetting.getSuspended(userId) != suspended) {
11632                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11633                            unactionedPackages.add(packageName);
11634                            continue;
11635                        }
11636                        pkgSetting.setSuspended(suspended, userId);
11637                        mSettings.writePackageRestrictionsLPr(userId);
11638                        changed = true;
11639                        changedPackages.add(packageName);
11640                    }
11641                }
11642
11643                if (changed && suspended) {
11644                    killApplication(packageName, UserHandle.getUid(userId, appId),
11645                            "suspending package");
11646                }
11647            }
11648        } finally {
11649            Binder.restoreCallingIdentity(callingId);
11650        }
11651
11652        if (!changedPackages.isEmpty()) {
11653            sendPackagesSuspendedForUser(changedPackages.toArray(
11654                    new String[changedPackages.size()]), userId, suspended);
11655        }
11656
11657        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11658    }
11659
11660    @Override
11661    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11662        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11663                true /* requireFullPermission */, false /* checkShell */,
11664                "isPackageSuspendedForUser for user " + userId);
11665        synchronized (mPackages) {
11666            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11667            if (pkgSetting == null) {
11668                throw new IllegalArgumentException("Unknown target package: " + packageName);
11669            }
11670            return pkgSetting.getSuspended(userId);
11671        }
11672    }
11673
11674    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11675        if (isPackageDeviceAdmin(packageName, userId)) {
11676            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11677                    + "\": has an active device admin");
11678            return false;
11679        }
11680
11681        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11682        if (packageName.equals(activeLauncherPackageName)) {
11683            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11684                    + "\": contains the active launcher");
11685            return false;
11686        }
11687
11688        if (packageName.equals(mRequiredInstallerPackage)) {
11689            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11690                    + "\": required for package installation");
11691            return false;
11692        }
11693
11694        if (packageName.equals(mRequiredVerifierPackage)) {
11695            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11696                    + "\": required for package verification");
11697            return false;
11698        }
11699
11700        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11701            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11702                    + "\": is the default dialer");
11703            return false;
11704        }
11705
11706        return true;
11707    }
11708
11709    private String getActiveLauncherPackageName(int userId) {
11710        Intent intent = new Intent(Intent.ACTION_MAIN);
11711        intent.addCategory(Intent.CATEGORY_HOME);
11712        ResolveInfo resolveInfo = resolveIntent(
11713                intent,
11714                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11715                PackageManager.MATCH_DEFAULT_ONLY,
11716                userId);
11717
11718        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11719    }
11720
11721    private String getDefaultDialerPackageName(int userId) {
11722        synchronized (mPackages) {
11723            return mSettings.getDefaultDialerPackageNameLPw(userId);
11724        }
11725    }
11726
11727    @Override
11728    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11729        mContext.enforceCallingOrSelfPermission(
11730                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11731                "Only package verification agents can verify applications");
11732
11733        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11734        final PackageVerificationResponse response = new PackageVerificationResponse(
11735                verificationCode, Binder.getCallingUid());
11736        msg.arg1 = id;
11737        msg.obj = response;
11738        mHandler.sendMessage(msg);
11739    }
11740
11741    @Override
11742    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11743            long millisecondsToDelay) {
11744        mContext.enforceCallingOrSelfPermission(
11745                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11746                "Only package verification agents can extend verification timeouts");
11747
11748        final PackageVerificationState state = mPendingVerification.get(id);
11749        final PackageVerificationResponse response = new PackageVerificationResponse(
11750                verificationCodeAtTimeout, Binder.getCallingUid());
11751
11752        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11753            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11754        }
11755        if (millisecondsToDelay < 0) {
11756            millisecondsToDelay = 0;
11757        }
11758        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11759                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11760            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11761        }
11762
11763        if ((state != null) && !state.timeoutExtended()) {
11764            state.extendTimeout();
11765
11766            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11767            msg.arg1 = id;
11768            msg.obj = response;
11769            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11770        }
11771    }
11772
11773    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11774            int verificationCode, UserHandle user) {
11775        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11776        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11777        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11778        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11779        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11780
11781        mContext.sendBroadcastAsUser(intent, user,
11782                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11783    }
11784
11785    private ComponentName matchComponentForVerifier(String packageName,
11786            List<ResolveInfo> receivers) {
11787        ActivityInfo targetReceiver = null;
11788
11789        final int NR = receivers.size();
11790        for (int i = 0; i < NR; i++) {
11791            final ResolveInfo info = receivers.get(i);
11792            if (info.activityInfo == null) {
11793                continue;
11794            }
11795
11796            if (packageName.equals(info.activityInfo.packageName)) {
11797                targetReceiver = info.activityInfo;
11798                break;
11799            }
11800        }
11801
11802        if (targetReceiver == null) {
11803            return null;
11804        }
11805
11806        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11807    }
11808
11809    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11810            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11811        if (pkgInfo.verifiers.length == 0) {
11812            return null;
11813        }
11814
11815        final int N = pkgInfo.verifiers.length;
11816        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11817        for (int i = 0; i < N; i++) {
11818            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11819
11820            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11821                    receivers);
11822            if (comp == null) {
11823                continue;
11824            }
11825
11826            final int verifierUid = getUidForVerifier(verifierInfo);
11827            if (verifierUid == -1) {
11828                continue;
11829            }
11830
11831            if (DEBUG_VERIFY) {
11832                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11833                        + " with the correct signature");
11834            }
11835            sufficientVerifiers.add(comp);
11836            verificationState.addSufficientVerifier(verifierUid);
11837        }
11838
11839        return sufficientVerifiers;
11840    }
11841
11842    private int getUidForVerifier(VerifierInfo verifierInfo) {
11843        synchronized (mPackages) {
11844            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11845            if (pkg == null) {
11846                return -1;
11847            } else if (pkg.mSignatures.length != 1) {
11848                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11849                        + " has more than one signature; ignoring");
11850                return -1;
11851            }
11852
11853            /*
11854             * If the public key of the package's signature does not match
11855             * our expected public key, then this is a different package and
11856             * we should skip.
11857             */
11858
11859            final byte[] expectedPublicKey;
11860            try {
11861                final Signature verifierSig = pkg.mSignatures[0];
11862                final PublicKey publicKey = verifierSig.getPublicKey();
11863                expectedPublicKey = publicKey.getEncoded();
11864            } catch (CertificateException e) {
11865                return -1;
11866            }
11867
11868            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11869
11870            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11871                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11872                        + " does not have the expected public key; ignoring");
11873                return -1;
11874            }
11875
11876            return pkg.applicationInfo.uid;
11877        }
11878    }
11879
11880    @Override
11881    public void finishPackageInstall(int token, boolean didLaunch) {
11882        enforceSystemOrRoot("Only the system is allowed to finish installs");
11883
11884        if (DEBUG_INSTALL) {
11885            Slog.v(TAG, "BM finishing package install for " + token);
11886        }
11887        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11888
11889        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11890        mHandler.sendMessage(msg);
11891    }
11892
11893    /**
11894     * Get the verification agent timeout.
11895     *
11896     * @return verification timeout in milliseconds
11897     */
11898    private long getVerificationTimeout() {
11899        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11900                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11901                DEFAULT_VERIFICATION_TIMEOUT);
11902    }
11903
11904    /**
11905     * Get the default verification agent response code.
11906     *
11907     * @return default verification response code
11908     */
11909    private int getDefaultVerificationResponse() {
11910        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11911                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11912                DEFAULT_VERIFICATION_RESPONSE);
11913    }
11914
11915    /**
11916     * Check whether or not package verification has been enabled.
11917     *
11918     * @return true if verification should be performed
11919     */
11920    private boolean isVerificationEnabled(int userId, int installFlags) {
11921        if (!DEFAULT_VERIFY_ENABLE) {
11922            return false;
11923        }
11924        // Ephemeral apps don't get the full verification treatment
11925        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11926            if (DEBUG_EPHEMERAL) {
11927                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11928            }
11929            return false;
11930        }
11931
11932        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11933
11934        // Check if installing from ADB
11935        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11936            // Do not run verification in a test harness environment
11937            if (ActivityManager.isRunningInTestHarness()) {
11938                return false;
11939            }
11940            if (ensureVerifyAppsEnabled) {
11941                return true;
11942            }
11943            // Check if the developer does not want package verification for ADB installs
11944            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11945                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11946                return false;
11947            }
11948        }
11949
11950        if (ensureVerifyAppsEnabled) {
11951            return true;
11952        }
11953
11954        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11955                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11956    }
11957
11958    @Override
11959    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11960            throws RemoteException {
11961        mContext.enforceCallingOrSelfPermission(
11962                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11963                "Only intentfilter verification agents can verify applications");
11964
11965        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11966        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11967                Binder.getCallingUid(), verificationCode, failedDomains);
11968        msg.arg1 = id;
11969        msg.obj = response;
11970        mHandler.sendMessage(msg);
11971    }
11972
11973    @Override
11974    public int getIntentVerificationStatus(String packageName, int userId) {
11975        synchronized (mPackages) {
11976            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11977        }
11978    }
11979
11980    @Override
11981    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11982        mContext.enforceCallingOrSelfPermission(
11983                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11984
11985        boolean result = false;
11986        synchronized (mPackages) {
11987            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11988        }
11989        if (result) {
11990            scheduleWritePackageRestrictionsLocked(userId);
11991        }
11992        return result;
11993    }
11994
11995    @Override
11996    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11997            String packageName) {
11998        synchronized (mPackages) {
11999            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12000        }
12001    }
12002
12003    @Override
12004    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12005        if (TextUtils.isEmpty(packageName)) {
12006            return ParceledListSlice.emptyList();
12007        }
12008        synchronized (mPackages) {
12009            PackageParser.Package pkg = mPackages.get(packageName);
12010            if (pkg == null || pkg.activities == null) {
12011                return ParceledListSlice.emptyList();
12012            }
12013            final int count = pkg.activities.size();
12014            ArrayList<IntentFilter> result = new ArrayList<>();
12015            for (int n=0; n<count; n++) {
12016                PackageParser.Activity activity = pkg.activities.get(n);
12017                if (activity.intents != null && activity.intents.size() > 0) {
12018                    result.addAll(activity.intents);
12019                }
12020            }
12021            return new ParceledListSlice<>(result);
12022        }
12023    }
12024
12025    @Override
12026    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12027        mContext.enforceCallingOrSelfPermission(
12028                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12029
12030        synchronized (mPackages) {
12031            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12032            if (packageName != null) {
12033                result |= updateIntentVerificationStatus(packageName,
12034                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12035                        userId);
12036                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12037                        packageName, userId);
12038            }
12039            return result;
12040        }
12041    }
12042
12043    @Override
12044    public String getDefaultBrowserPackageName(int userId) {
12045        synchronized (mPackages) {
12046            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12047        }
12048    }
12049
12050    /**
12051     * Get the "allow unknown sources" setting.
12052     *
12053     * @return the current "allow unknown sources" setting
12054     */
12055    private int getUnknownSourcesSettings() {
12056        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12057                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12058                -1);
12059    }
12060
12061    @Override
12062    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12063        final int uid = Binder.getCallingUid();
12064        // writer
12065        synchronized (mPackages) {
12066            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12067            if (targetPackageSetting == null) {
12068                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12069            }
12070
12071            PackageSetting installerPackageSetting;
12072            if (installerPackageName != null) {
12073                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12074                if (installerPackageSetting == null) {
12075                    throw new IllegalArgumentException("Unknown installer package: "
12076                            + installerPackageName);
12077                }
12078            } else {
12079                installerPackageSetting = null;
12080            }
12081
12082            Signature[] callerSignature;
12083            Object obj = mSettings.getUserIdLPr(uid);
12084            if (obj != null) {
12085                if (obj instanceof SharedUserSetting) {
12086                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12087                } else if (obj instanceof PackageSetting) {
12088                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12089                } else {
12090                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12091                }
12092            } else {
12093                throw new SecurityException("Unknown calling UID: " + uid);
12094            }
12095
12096            // Verify: can't set installerPackageName to a package that is
12097            // not signed with the same cert as the caller.
12098            if (installerPackageSetting != null) {
12099                if (compareSignatures(callerSignature,
12100                        installerPackageSetting.signatures.mSignatures)
12101                        != PackageManager.SIGNATURE_MATCH) {
12102                    throw new SecurityException(
12103                            "Caller does not have same cert as new installer package "
12104                            + installerPackageName);
12105                }
12106            }
12107
12108            // Verify: if target already has an installer package, it must
12109            // be signed with the same cert as the caller.
12110            if (targetPackageSetting.installerPackageName != null) {
12111                PackageSetting setting = mSettings.mPackages.get(
12112                        targetPackageSetting.installerPackageName);
12113                // If the currently set package isn't valid, then it's always
12114                // okay to change it.
12115                if (setting != null) {
12116                    if (compareSignatures(callerSignature,
12117                            setting.signatures.mSignatures)
12118                            != PackageManager.SIGNATURE_MATCH) {
12119                        throw new SecurityException(
12120                                "Caller does not have same cert as old installer package "
12121                                + targetPackageSetting.installerPackageName);
12122                    }
12123                }
12124            }
12125
12126            // Okay!
12127            targetPackageSetting.installerPackageName = installerPackageName;
12128            if (installerPackageName != null) {
12129                mSettings.mInstallerPackages.add(installerPackageName);
12130            }
12131            scheduleWriteSettingsLocked();
12132        }
12133    }
12134
12135    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12136        // Queue up an async operation since the package installation may take a little while.
12137        mHandler.post(new Runnable() {
12138            public void run() {
12139                mHandler.removeCallbacks(this);
12140                 // Result object to be returned
12141                PackageInstalledInfo res = new PackageInstalledInfo();
12142                res.setReturnCode(currentStatus);
12143                res.uid = -1;
12144                res.pkg = null;
12145                res.removedInfo = null;
12146                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12147                    args.doPreInstall(res.returnCode);
12148                    synchronized (mInstallLock) {
12149                        installPackageTracedLI(args, res);
12150                    }
12151                    args.doPostInstall(res.returnCode, res.uid);
12152                }
12153
12154                // A restore should be performed at this point if (a) the install
12155                // succeeded, (b) the operation is not an update, and (c) the new
12156                // package has not opted out of backup participation.
12157                final boolean update = res.removedInfo != null
12158                        && res.removedInfo.removedPackage != null;
12159                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12160                boolean doRestore = !update
12161                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12162
12163                // Set up the post-install work request bookkeeping.  This will be used
12164                // and cleaned up by the post-install event handling regardless of whether
12165                // there's a restore pass performed.  Token values are >= 1.
12166                int token;
12167                if (mNextInstallToken < 0) mNextInstallToken = 1;
12168                token = mNextInstallToken++;
12169
12170                PostInstallData data = new PostInstallData(args, res);
12171                mRunningInstalls.put(token, data);
12172                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12173
12174                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12175                    // Pass responsibility to the Backup Manager.  It will perform a
12176                    // restore if appropriate, then pass responsibility back to the
12177                    // Package Manager to run the post-install observer callbacks
12178                    // and broadcasts.
12179                    IBackupManager bm = IBackupManager.Stub.asInterface(
12180                            ServiceManager.getService(Context.BACKUP_SERVICE));
12181                    if (bm != null) {
12182                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12183                                + " to BM for possible restore");
12184                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12185                        try {
12186                            // TODO: http://b/22388012
12187                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12188                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12189                            } else {
12190                                doRestore = false;
12191                            }
12192                        } catch (RemoteException e) {
12193                            // can't happen; the backup manager is local
12194                        } catch (Exception e) {
12195                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12196                            doRestore = false;
12197                        }
12198                    } else {
12199                        Slog.e(TAG, "Backup Manager not found!");
12200                        doRestore = false;
12201                    }
12202                }
12203
12204                if (!doRestore) {
12205                    // No restore possible, or the Backup Manager was mysteriously not
12206                    // available -- just fire the post-install work request directly.
12207                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12208
12209                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12210
12211                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12212                    mHandler.sendMessage(msg);
12213                }
12214            }
12215        });
12216    }
12217
12218    /**
12219     * Callback from PackageSettings whenever an app is first transitioned out of the
12220     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12221     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12222     * here whether the app is the target of an ongoing install, and only send the
12223     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12224     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12225     * handling.
12226     */
12227    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12228        // Serialize this with the rest of the install-process message chain.  In the
12229        // restore-at-install case, this Runnable will necessarily run before the
12230        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12231        // are coherent.  In the non-restore case, the app has already completed install
12232        // and been launched through some other means, so it is not in a problematic
12233        // state for observers to see the FIRST_LAUNCH signal.
12234        mHandler.post(new Runnable() {
12235            @Override
12236            public void run() {
12237                for (int i = 0; i < mRunningInstalls.size(); i++) {
12238                    final PostInstallData data = mRunningInstalls.valueAt(i);
12239                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12240                        // right package; but is it for the right user?
12241                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12242                            if (userId == data.res.newUsers[uIndex]) {
12243                                if (DEBUG_BACKUP) {
12244                                    Slog.i(TAG, "Package " + pkgName
12245                                            + " being restored so deferring FIRST_LAUNCH");
12246                                }
12247                                return;
12248                            }
12249                        }
12250                    }
12251                }
12252                // didn't find it, so not being restored
12253                if (DEBUG_BACKUP) {
12254                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12255                }
12256                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12257            }
12258        });
12259    }
12260
12261    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12262        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12263                installerPkg, null, userIds);
12264    }
12265
12266    private abstract class HandlerParams {
12267        private static final int MAX_RETRIES = 4;
12268
12269        /**
12270         * Number of times startCopy() has been attempted and had a non-fatal
12271         * error.
12272         */
12273        private int mRetries = 0;
12274
12275        /** User handle for the user requesting the information or installation. */
12276        private final UserHandle mUser;
12277        String traceMethod;
12278        int traceCookie;
12279
12280        HandlerParams(UserHandle user) {
12281            mUser = user;
12282        }
12283
12284        UserHandle getUser() {
12285            return mUser;
12286        }
12287
12288        HandlerParams setTraceMethod(String traceMethod) {
12289            this.traceMethod = traceMethod;
12290            return this;
12291        }
12292
12293        HandlerParams setTraceCookie(int traceCookie) {
12294            this.traceCookie = traceCookie;
12295            return this;
12296        }
12297
12298        final boolean startCopy() {
12299            boolean res;
12300            try {
12301                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12302
12303                if (++mRetries > MAX_RETRIES) {
12304                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12305                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12306                    handleServiceError();
12307                    return false;
12308                } else {
12309                    handleStartCopy();
12310                    res = true;
12311                }
12312            } catch (RemoteException e) {
12313                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12314                mHandler.sendEmptyMessage(MCS_RECONNECT);
12315                res = false;
12316            }
12317            handleReturnCode();
12318            return res;
12319        }
12320
12321        final void serviceError() {
12322            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12323            handleServiceError();
12324            handleReturnCode();
12325        }
12326
12327        abstract void handleStartCopy() throws RemoteException;
12328        abstract void handleServiceError();
12329        abstract void handleReturnCode();
12330    }
12331
12332    class MeasureParams extends HandlerParams {
12333        private final PackageStats mStats;
12334        private boolean mSuccess;
12335
12336        private final IPackageStatsObserver mObserver;
12337
12338        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12339            super(new UserHandle(stats.userHandle));
12340            mObserver = observer;
12341            mStats = stats;
12342        }
12343
12344        @Override
12345        public String toString() {
12346            return "MeasureParams{"
12347                + Integer.toHexString(System.identityHashCode(this))
12348                + " " + mStats.packageName + "}";
12349        }
12350
12351        @Override
12352        void handleStartCopy() throws RemoteException {
12353            synchronized (mInstallLock) {
12354                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12355            }
12356
12357            if (mSuccess) {
12358                final boolean mounted;
12359                if (Environment.isExternalStorageEmulated()) {
12360                    mounted = true;
12361                } else {
12362                    final String status = Environment.getExternalStorageState();
12363                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12364                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12365                }
12366
12367                if (mounted) {
12368                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12369
12370                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12371                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12372
12373                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12374                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12375
12376                    // Always subtract cache size, since it's a subdirectory
12377                    mStats.externalDataSize -= mStats.externalCacheSize;
12378
12379                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12380                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12381
12382                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12383                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12384                }
12385            }
12386        }
12387
12388        @Override
12389        void handleReturnCode() {
12390            if (mObserver != null) {
12391                try {
12392                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12393                } catch (RemoteException e) {
12394                    Slog.i(TAG, "Observer no longer exists.");
12395                }
12396            }
12397        }
12398
12399        @Override
12400        void handleServiceError() {
12401            Slog.e(TAG, "Could not measure application " + mStats.packageName
12402                            + " external storage");
12403        }
12404    }
12405
12406    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12407            throws RemoteException {
12408        long result = 0;
12409        for (File path : paths) {
12410            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12411        }
12412        return result;
12413    }
12414
12415    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12416        for (File path : paths) {
12417            try {
12418                mcs.clearDirectory(path.getAbsolutePath());
12419            } catch (RemoteException e) {
12420            }
12421        }
12422    }
12423
12424    static class OriginInfo {
12425        /**
12426         * Location where install is coming from, before it has been
12427         * copied/renamed into place. This could be a single monolithic APK
12428         * file, or a cluster directory. This location may be untrusted.
12429         */
12430        final File file;
12431        final String cid;
12432
12433        /**
12434         * Flag indicating that {@link #file} or {@link #cid} has already been
12435         * staged, meaning downstream users don't need to defensively copy the
12436         * contents.
12437         */
12438        final boolean staged;
12439
12440        /**
12441         * Flag indicating that {@link #file} or {@link #cid} is an already
12442         * installed app that is being moved.
12443         */
12444        final boolean existing;
12445
12446        final String resolvedPath;
12447        final File resolvedFile;
12448
12449        static OriginInfo fromNothing() {
12450            return new OriginInfo(null, null, false, false);
12451        }
12452
12453        static OriginInfo fromUntrustedFile(File file) {
12454            return new OriginInfo(file, null, false, false);
12455        }
12456
12457        static OriginInfo fromExistingFile(File file) {
12458            return new OriginInfo(file, null, false, true);
12459        }
12460
12461        static OriginInfo fromStagedFile(File file) {
12462            return new OriginInfo(file, null, true, false);
12463        }
12464
12465        static OriginInfo fromStagedContainer(String cid) {
12466            return new OriginInfo(null, cid, true, false);
12467        }
12468
12469        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12470            this.file = file;
12471            this.cid = cid;
12472            this.staged = staged;
12473            this.existing = existing;
12474
12475            if (cid != null) {
12476                resolvedPath = PackageHelper.getSdDir(cid);
12477                resolvedFile = new File(resolvedPath);
12478            } else if (file != null) {
12479                resolvedPath = file.getAbsolutePath();
12480                resolvedFile = file;
12481            } else {
12482                resolvedPath = null;
12483                resolvedFile = null;
12484            }
12485        }
12486    }
12487
12488    static class MoveInfo {
12489        final int moveId;
12490        final String fromUuid;
12491        final String toUuid;
12492        final String packageName;
12493        final String dataAppName;
12494        final int appId;
12495        final String seinfo;
12496        final int targetSdkVersion;
12497
12498        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12499                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12500            this.moveId = moveId;
12501            this.fromUuid = fromUuid;
12502            this.toUuid = toUuid;
12503            this.packageName = packageName;
12504            this.dataAppName = dataAppName;
12505            this.appId = appId;
12506            this.seinfo = seinfo;
12507            this.targetSdkVersion = targetSdkVersion;
12508        }
12509    }
12510
12511    static class VerificationInfo {
12512        /** A constant used to indicate that a uid value is not present. */
12513        public static final int NO_UID = -1;
12514
12515        /** URI referencing where the package was downloaded from. */
12516        final Uri originatingUri;
12517
12518        /** HTTP referrer URI associated with the originatingURI. */
12519        final Uri referrer;
12520
12521        /** UID of the application that the install request originated from. */
12522        final int originatingUid;
12523
12524        /** UID of application requesting the install */
12525        final int installerUid;
12526
12527        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12528            this.originatingUri = originatingUri;
12529            this.referrer = referrer;
12530            this.originatingUid = originatingUid;
12531            this.installerUid = installerUid;
12532        }
12533    }
12534
12535    class InstallParams extends HandlerParams {
12536        final OriginInfo origin;
12537        final MoveInfo move;
12538        final IPackageInstallObserver2 observer;
12539        int installFlags;
12540        final String installerPackageName;
12541        final String volumeUuid;
12542        private InstallArgs mArgs;
12543        private int mRet;
12544        final String packageAbiOverride;
12545        final String[] grantedRuntimePermissions;
12546        final VerificationInfo verificationInfo;
12547        final Certificate[][] certificates;
12548
12549        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12550                int installFlags, String installerPackageName, String volumeUuid,
12551                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12552                String[] grantedPermissions, Certificate[][] certificates) {
12553            super(user);
12554            this.origin = origin;
12555            this.move = move;
12556            this.observer = observer;
12557            this.installFlags = installFlags;
12558            this.installerPackageName = installerPackageName;
12559            this.volumeUuid = volumeUuid;
12560            this.verificationInfo = verificationInfo;
12561            this.packageAbiOverride = packageAbiOverride;
12562            this.grantedRuntimePermissions = grantedPermissions;
12563            this.certificates = certificates;
12564        }
12565
12566        @Override
12567        public String toString() {
12568            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12569                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12570        }
12571
12572        private int installLocationPolicy(PackageInfoLite pkgLite) {
12573            String packageName = pkgLite.packageName;
12574            int installLocation = pkgLite.installLocation;
12575            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12576            // reader
12577            synchronized (mPackages) {
12578                // Currently installed package which the new package is attempting to replace or
12579                // null if no such package is installed.
12580                PackageParser.Package installedPkg = mPackages.get(packageName);
12581                // Package which currently owns the data which the new package will own if installed.
12582                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12583                // will be null whereas dataOwnerPkg will contain information about the package
12584                // which was uninstalled while keeping its data.
12585                PackageParser.Package dataOwnerPkg = installedPkg;
12586                if (dataOwnerPkg  == null) {
12587                    PackageSetting ps = mSettings.mPackages.get(packageName);
12588                    if (ps != null) {
12589                        dataOwnerPkg = ps.pkg;
12590                    }
12591                }
12592
12593                if (dataOwnerPkg != null) {
12594                    // If installed, the package will get access to data left on the device by its
12595                    // predecessor. As a security measure, this is permited only if this is not a
12596                    // version downgrade or if the predecessor package is marked as debuggable and
12597                    // a downgrade is explicitly requested.
12598                    //
12599                    // On debuggable platform builds, downgrades are permitted even for
12600                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12601                    // not offer security guarantees and thus it's OK to disable some security
12602                    // mechanisms to make debugging/testing easier on those builds. However, even on
12603                    // debuggable builds downgrades of packages are permitted only if requested via
12604                    // installFlags. This is because we aim to keep the behavior of debuggable
12605                    // platform builds as close as possible to the behavior of non-debuggable
12606                    // platform builds.
12607                    final boolean downgradeRequested =
12608                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12609                    final boolean packageDebuggable =
12610                                (dataOwnerPkg.applicationInfo.flags
12611                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12612                    final boolean downgradePermitted =
12613                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12614                    if (!downgradePermitted) {
12615                        try {
12616                            checkDowngrade(dataOwnerPkg, pkgLite);
12617                        } catch (PackageManagerException e) {
12618                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12619                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12620                        }
12621                    }
12622                }
12623
12624                if (installedPkg != null) {
12625                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12626                        // Check for updated system application.
12627                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12628                            if (onSd) {
12629                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12630                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12631                            }
12632                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12633                        } else {
12634                            if (onSd) {
12635                                // Install flag overrides everything.
12636                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12637                            }
12638                            // If current upgrade specifies particular preference
12639                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12640                                // Application explicitly specified internal.
12641                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12642                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12643                                // App explictly prefers external. Let policy decide
12644                            } else {
12645                                // Prefer previous location
12646                                if (isExternal(installedPkg)) {
12647                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12648                                }
12649                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12650                            }
12651                        }
12652                    } else {
12653                        // Invalid install. Return error code
12654                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12655                    }
12656                }
12657            }
12658            // All the special cases have been taken care of.
12659            // Return result based on recommended install location.
12660            if (onSd) {
12661                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12662            }
12663            return pkgLite.recommendedInstallLocation;
12664        }
12665
12666        /*
12667         * Invoke remote method to get package information and install
12668         * location values. Override install location based on default
12669         * policy if needed and then create install arguments based
12670         * on the install location.
12671         */
12672        public void handleStartCopy() throws RemoteException {
12673            int ret = PackageManager.INSTALL_SUCCEEDED;
12674
12675            // If we're already staged, we've firmly committed to an install location
12676            if (origin.staged) {
12677                if (origin.file != null) {
12678                    installFlags |= PackageManager.INSTALL_INTERNAL;
12679                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12680                } else if (origin.cid != null) {
12681                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12682                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12683                } else {
12684                    throw new IllegalStateException("Invalid stage location");
12685                }
12686            }
12687
12688            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12689            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12690            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12691            PackageInfoLite pkgLite = null;
12692
12693            if (onInt && onSd) {
12694                // Check if both bits are set.
12695                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12696                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12697            } else if (onSd && ephemeral) {
12698                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12699                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12700            } else {
12701                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12702                        packageAbiOverride);
12703
12704                if (DEBUG_EPHEMERAL && ephemeral) {
12705                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12706                }
12707
12708                /*
12709                 * If we have too little free space, try to free cache
12710                 * before giving up.
12711                 */
12712                if (!origin.staged && pkgLite.recommendedInstallLocation
12713                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12714                    // TODO: focus freeing disk space on the target device
12715                    final StorageManager storage = StorageManager.from(mContext);
12716                    final long lowThreshold = storage.getStorageLowBytes(
12717                            Environment.getDataDirectory());
12718
12719                    final long sizeBytes = mContainerService.calculateInstalledSize(
12720                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12721
12722                    try {
12723                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12724                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12725                                installFlags, packageAbiOverride);
12726                    } catch (InstallerException e) {
12727                        Slog.w(TAG, "Failed to free cache", e);
12728                    }
12729
12730                    /*
12731                     * The cache free must have deleted the file we
12732                     * downloaded to install.
12733                     *
12734                     * TODO: fix the "freeCache" call to not delete
12735                     *       the file we care about.
12736                     */
12737                    if (pkgLite.recommendedInstallLocation
12738                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12739                        pkgLite.recommendedInstallLocation
12740                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12741                    }
12742                }
12743            }
12744
12745            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12746                int loc = pkgLite.recommendedInstallLocation;
12747                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12748                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12749                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12750                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12751                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12752                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12753                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12754                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12755                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12756                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12757                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12758                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12759                } else {
12760                    // Override with defaults if needed.
12761                    loc = installLocationPolicy(pkgLite);
12762                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12763                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12764                    } else if (!onSd && !onInt) {
12765                        // Override install location with flags
12766                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12767                            // Set the flag to install on external media.
12768                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12769                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12770                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12771                            if (DEBUG_EPHEMERAL) {
12772                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12773                            }
12774                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12775                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12776                                    |PackageManager.INSTALL_INTERNAL);
12777                        } else {
12778                            // Make sure the flag for installing on external
12779                            // media is unset
12780                            installFlags |= PackageManager.INSTALL_INTERNAL;
12781                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12782                        }
12783                    }
12784                }
12785            }
12786
12787            final InstallArgs args = createInstallArgs(this);
12788            mArgs = args;
12789
12790            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12791                // TODO: http://b/22976637
12792                // Apps installed for "all" users use the device owner to verify the app
12793                UserHandle verifierUser = getUser();
12794                if (verifierUser == UserHandle.ALL) {
12795                    verifierUser = UserHandle.SYSTEM;
12796                }
12797
12798                /*
12799                 * Determine if we have any installed package verifiers. If we
12800                 * do, then we'll defer to them to verify the packages.
12801                 */
12802                final int requiredUid = mRequiredVerifierPackage == null ? -1
12803                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12804                                verifierUser.getIdentifier());
12805                if (!origin.existing && requiredUid != -1
12806                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12807                    final Intent verification = new Intent(
12808                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12809                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12810                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12811                            PACKAGE_MIME_TYPE);
12812                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12813
12814                    // Query all live verifiers based on current user state
12815                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12816                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12817
12818                    if (DEBUG_VERIFY) {
12819                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12820                                + verification.toString() + " with " + pkgLite.verifiers.length
12821                                + " optional verifiers");
12822                    }
12823
12824                    final int verificationId = mPendingVerificationToken++;
12825
12826                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12827
12828                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12829                            installerPackageName);
12830
12831                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12832                            installFlags);
12833
12834                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12835                            pkgLite.packageName);
12836
12837                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12838                            pkgLite.versionCode);
12839
12840                    if (verificationInfo != null) {
12841                        if (verificationInfo.originatingUri != null) {
12842                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12843                                    verificationInfo.originatingUri);
12844                        }
12845                        if (verificationInfo.referrer != null) {
12846                            verification.putExtra(Intent.EXTRA_REFERRER,
12847                                    verificationInfo.referrer);
12848                        }
12849                        if (verificationInfo.originatingUid >= 0) {
12850                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12851                                    verificationInfo.originatingUid);
12852                        }
12853                        if (verificationInfo.installerUid >= 0) {
12854                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12855                                    verificationInfo.installerUid);
12856                        }
12857                    }
12858
12859                    final PackageVerificationState verificationState = new PackageVerificationState(
12860                            requiredUid, args);
12861
12862                    mPendingVerification.append(verificationId, verificationState);
12863
12864                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12865                            receivers, verificationState);
12866
12867                    /*
12868                     * If any sufficient verifiers were listed in the package
12869                     * manifest, attempt to ask them.
12870                     */
12871                    if (sufficientVerifiers != null) {
12872                        final int N = sufficientVerifiers.size();
12873                        if (N == 0) {
12874                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12875                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12876                        } else {
12877                            for (int i = 0; i < N; i++) {
12878                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12879
12880                                final Intent sufficientIntent = new Intent(verification);
12881                                sufficientIntent.setComponent(verifierComponent);
12882                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12883                            }
12884                        }
12885                    }
12886
12887                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12888                            mRequiredVerifierPackage, receivers);
12889                    if (ret == PackageManager.INSTALL_SUCCEEDED
12890                            && mRequiredVerifierPackage != null) {
12891                        Trace.asyncTraceBegin(
12892                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12893                        /*
12894                         * Send the intent to the required verification agent,
12895                         * but only start the verification timeout after the
12896                         * target BroadcastReceivers have run.
12897                         */
12898                        verification.setComponent(requiredVerifierComponent);
12899                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12900                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12901                                new BroadcastReceiver() {
12902                                    @Override
12903                                    public void onReceive(Context context, Intent intent) {
12904                                        final Message msg = mHandler
12905                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12906                                        msg.arg1 = verificationId;
12907                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12908                                    }
12909                                }, null, 0, null, null);
12910
12911                        /*
12912                         * We don't want the copy to proceed until verification
12913                         * succeeds, so null out this field.
12914                         */
12915                        mArgs = null;
12916                    }
12917                } else {
12918                    /*
12919                     * No package verification is enabled, so immediately start
12920                     * the remote call to initiate copy using temporary file.
12921                     */
12922                    ret = args.copyApk(mContainerService, true);
12923                }
12924            }
12925
12926            mRet = ret;
12927        }
12928
12929        @Override
12930        void handleReturnCode() {
12931            // If mArgs is null, then MCS couldn't be reached. When it
12932            // reconnects, it will try again to install. At that point, this
12933            // will succeed.
12934            if (mArgs != null) {
12935                processPendingInstall(mArgs, mRet);
12936            }
12937        }
12938
12939        @Override
12940        void handleServiceError() {
12941            mArgs = createInstallArgs(this);
12942            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12943        }
12944
12945        public boolean isForwardLocked() {
12946            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12947        }
12948    }
12949
12950    /**
12951     * Used during creation of InstallArgs
12952     *
12953     * @param installFlags package installation flags
12954     * @return true if should be installed on external storage
12955     */
12956    private static boolean installOnExternalAsec(int installFlags) {
12957        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12958            return false;
12959        }
12960        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12961            return true;
12962        }
12963        return false;
12964    }
12965
12966    /**
12967     * Used during creation of InstallArgs
12968     *
12969     * @param installFlags package installation flags
12970     * @return true if should be installed as forward locked
12971     */
12972    private static boolean installForwardLocked(int installFlags) {
12973        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12974    }
12975
12976    private InstallArgs createInstallArgs(InstallParams params) {
12977        if (params.move != null) {
12978            return new MoveInstallArgs(params);
12979        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12980            return new AsecInstallArgs(params);
12981        } else {
12982            return new FileInstallArgs(params);
12983        }
12984    }
12985
12986    /**
12987     * Create args that describe an existing installed package. Typically used
12988     * when cleaning up old installs, or used as a move source.
12989     */
12990    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12991            String resourcePath, String[] instructionSets) {
12992        final boolean isInAsec;
12993        if (installOnExternalAsec(installFlags)) {
12994            /* Apps on SD card are always in ASEC containers. */
12995            isInAsec = true;
12996        } else if (installForwardLocked(installFlags)
12997                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12998            /*
12999             * Forward-locked apps are only in ASEC containers if they're the
13000             * new style
13001             */
13002            isInAsec = true;
13003        } else {
13004            isInAsec = false;
13005        }
13006
13007        if (isInAsec) {
13008            return new AsecInstallArgs(codePath, instructionSets,
13009                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13010        } else {
13011            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13012        }
13013    }
13014
13015    static abstract class InstallArgs {
13016        /** @see InstallParams#origin */
13017        final OriginInfo origin;
13018        /** @see InstallParams#move */
13019        final MoveInfo move;
13020
13021        final IPackageInstallObserver2 observer;
13022        // Always refers to PackageManager flags only
13023        final int installFlags;
13024        final String installerPackageName;
13025        final String volumeUuid;
13026        final UserHandle user;
13027        final String abiOverride;
13028        final String[] installGrantPermissions;
13029        /** If non-null, drop an async trace when the install completes */
13030        final String traceMethod;
13031        final int traceCookie;
13032        final Certificate[][] certificates;
13033
13034        // The list of instruction sets supported by this app. This is currently
13035        // only used during the rmdex() phase to clean up resources. We can get rid of this
13036        // if we move dex files under the common app path.
13037        /* nullable */ String[] instructionSets;
13038
13039        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13040                int installFlags, String installerPackageName, String volumeUuid,
13041                UserHandle user, String[] instructionSets,
13042                String abiOverride, String[] installGrantPermissions,
13043                String traceMethod, int traceCookie, Certificate[][] certificates) {
13044            this.origin = origin;
13045            this.move = move;
13046            this.installFlags = installFlags;
13047            this.observer = observer;
13048            this.installerPackageName = installerPackageName;
13049            this.volumeUuid = volumeUuid;
13050            this.user = user;
13051            this.instructionSets = instructionSets;
13052            this.abiOverride = abiOverride;
13053            this.installGrantPermissions = installGrantPermissions;
13054            this.traceMethod = traceMethod;
13055            this.traceCookie = traceCookie;
13056            this.certificates = certificates;
13057        }
13058
13059        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13060        abstract int doPreInstall(int status);
13061
13062        /**
13063         * Rename package into final resting place. All paths on the given
13064         * scanned package should be updated to reflect the rename.
13065         */
13066        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13067        abstract int doPostInstall(int status, int uid);
13068
13069        /** @see PackageSettingBase#codePathString */
13070        abstract String getCodePath();
13071        /** @see PackageSettingBase#resourcePathString */
13072        abstract String getResourcePath();
13073
13074        // Need installer lock especially for dex file removal.
13075        abstract void cleanUpResourcesLI();
13076        abstract boolean doPostDeleteLI(boolean delete);
13077
13078        /**
13079         * Called before the source arguments are copied. This is used mostly
13080         * for MoveParams when it needs to read the source file to put it in the
13081         * destination.
13082         */
13083        int doPreCopy() {
13084            return PackageManager.INSTALL_SUCCEEDED;
13085        }
13086
13087        /**
13088         * Called after the source arguments are copied. This is used mostly for
13089         * MoveParams when it needs to read the source file to put it in the
13090         * destination.
13091         */
13092        int doPostCopy(int uid) {
13093            return PackageManager.INSTALL_SUCCEEDED;
13094        }
13095
13096        protected boolean isFwdLocked() {
13097            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13098        }
13099
13100        protected boolean isExternalAsec() {
13101            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13102        }
13103
13104        protected boolean isEphemeral() {
13105            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13106        }
13107
13108        UserHandle getUser() {
13109            return user;
13110        }
13111    }
13112
13113    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13114        if (!allCodePaths.isEmpty()) {
13115            if (instructionSets == null) {
13116                throw new IllegalStateException("instructionSet == null");
13117            }
13118            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13119            for (String codePath : allCodePaths) {
13120                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13121                    try {
13122                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13123                    } catch (InstallerException ignored) {
13124                    }
13125                }
13126            }
13127        }
13128    }
13129
13130    /**
13131     * Logic to handle installation of non-ASEC applications, including copying
13132     * and renaming logic.
13133     */
13134    class FileInstallArgs extends InstallArgs {
13135        private File codeFile;
13136        private File resourceFile;
13137
13138        // Example topology:
13139        // /data/app/com.example/base.apk
13140        // /data/app/com.example/split_foo.apk
13141        // /data/app/com.example/lib/arm/libfoo.so
13142        // /data/app/com.example/lib/arm64/libfoo.so
13143        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13144
13145        /** New install */
13146        FileInstallArgs(InstallParams params) {
13147            super(params.origin, params.move, params.observer, params.installFlags,
13148                    params.installerPackageName, params.volumeUuid,
13149                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13150                    params.grantedRuntimePermissions,
13151                    params.traceMethod, params.traceCookie, params.certificates);
13152            if (isFwdLocked()) {
13153                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13154            }
13155        }
13156
13157        /** Existing install */
13158        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13159            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13160                    null, null, null, 0, null /*certificates*/);
13161            this.codeFile = (codePath != null) ? new File(codePath) : null;
13162            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13163        }
13164
13165        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13166            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13167            try {
13168                return doCopyApk(imcs, temp);
13169            } finally {
13170                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13171            }
13172        }
13173
13174        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13175            if (origin.staged) {
13176                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13177                codeFile = origin.file;
13178                resourceFile = origin.file;
13179                return PackageManager.INSTALL_SUCCEEDED;
13180            }
13181
13182            try {
13183                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13184                final File tempDir =
13185                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13186                codeFile = tempDir;
13187                resourceFile = tempDir;
13188            } catch (IOException e) {
13189                Slog.w(TAG, "Failed to create copy file: " + e);
13190                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13191            }
13192
13193            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13194                @Override
13195                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13196                    if (!FileUtils.isValidExtFilename(name)) {
13197                        throw new IllegalArgumentException("Invalid filename: " + name);
13198                    }
13199                    try {
13200                        final File file = new File(codeFile, name);
13201                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13202                                O_RDWR | O_CREAT, 0644);
13203                        Os.chmod(file.getAbsolutePath(), 0644);
13204                        return new ParcelFileDescriptor(fd);
13205                    } catch (ErrnoException e) {
13206                        throw new RemoteException("Failed to open: " + e.getMessage());
13207                    }
13208                }
13209            };
13210
13211            int ret = PackageManager.INSTALL_SUCCEEDED;
13212            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13213            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13214                Slog.e(TAG, "Failed to copy package");
13215                return ret;
13216            }
13217
13218            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13219            NativeLibraryHelper.Handle handle = null;
13220            try {
13221                handle = NativeLibraryHelper.Handle.create(codeFile);
13222                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13223                        abiOverride);
13224            } catch (IOException e) {
13225                Slog.e(TAG, "Copying native libraries failed", e);
13226                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13227            } finally {
13228                IoUtils.closeQuietly(handle);
13229            }
13230
13231            return ret;
13232        }
13233
13234        int doPreInstall(int status) {
13235            if (status != PackageManager.INSTALL_SUCCEEDED) {
13236                cleanUp();
13237            }
13238            return status;
13239        }
13240
13241        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13242            if (status != PackageManager.INSTALL_SUCCEEDED) {
13243                cleanUp();
13244                return false;
13245            }
13246
13247            final File targetDir = codeFile.getParentFile();
13248            final File beforeCodeFile = codeFile;
13249            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13250
13251            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13252            try {
13253                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13254            } catch (ErrnoException e) {
13255                Slog.w(TAG, "Failed to rename", e);
13256                return false;
13257            }
13258
13259            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13260                Slog.w(TAG, "Failed to restorecon");
13261                return false;
13262            }
13263
13264            // Reflect the rename internally
13265            codeFile = afterCodeFile;
13266            resourceFile = afterCodeFile;
13267
13268            // Reflect the rename in scanned details
13269            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13270            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13271                    afterCodeFile, pkg.baseCodePath));
13272            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13273                    afterCodeFile, pkg.splitCodePaths));
13274
13275            // Reflect the rename in app info
13276            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13277            pkg.setApplicationInfoCodePath(pkg.codePath);
13278            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13279            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13280            pkg.setApplicationInfoResourcePath(pkg.codePath);
13281            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13282            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13283
13284            return true;
13285        }
13286
13287        int doPostInstall(int status, int uid) {
13288            if (status != PackageManager.INSTALL_SUCCEEDED) {
13289                cleanUp();
13290            }
13291            return status;
13292        }
13293
13294        @Override
13295        String getCodePath() {
13296            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13297        }
13298
13299        @Override
13300        String getResourcePath() {
13301            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13302        }
13303
13304        private boolean cleanUp() {
13305            if (codeFile == null || !codeFile.exists()) {
13306                return false;
13307            }
13308
13309            removeCodePathLI(codeFile);
13310
13311            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13312                resourceFile.delete();
13313            }
13314
13315            return true;
13316        }
13317
13318        void cleanUpResourcesLI() {
13319            // Try enumerating all code paths before deleting
13320            List<String> allCodePaths = Collections.EMPTY_LIST;
13321            if (codeFile != null && codeFile.exists()) {
13322                try {
13323                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13324                    allCodePaths = pkg.getAllCodePaths();
13325                } catch (PackageParserException e) {
13326                    // Ignored; we tried our best
13327                }
13328            }
13329
13330            cleanUp();
13331            removeDexFiles(allCodePaths, instructionSets);
13332        }
13333
13334        boolean doPostDeleteLI(boolean delete) {
13335            // XXX err, shouldn't we respect the delete flag?
13336            cleanUpResourcesLI();
13337            return true;
13338        }
13339    }
13340
13341    private boolean isAsecExternal(String cid) {
13342        final String asecPath = PackageHelper.getSdFilesystem(cid);
13343        return !asecPath.startsWith(mAsecInternalPath);
13344    }
13345
13346    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13347            PackageManagerException {
13348        if (copyRet < 0) {
13349            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13350                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13351                throw new PackageManagerException(copyRet, message);
13352            }
13353        }
13354    }
13355
13356    /**
13357     * Extract the MountService "container ID" from the full code path of an
13358     * .apk.
13359     */
13360    static String cidFromCodePath(String fullCodePath) {
13361        int eidx = fullCodePath.lastIndexOf("/");
13362        String subStr1 = fullCodePath.substring(0, eidx);
13363        int sidx = subStr1.lastIndexOf("/");
13364        return subStr1.substring(sidx+1, eidx);
13365    }
13366
13367    /**
13368     * Logic to handle installation of ASEC applications, including copying and
13369     * renaming logic.
13370     */
13371    class AsecInstallArgs extends InstallArgs {
13372        static final String RES_FILE_NAME = "pkg.apk";
13373        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13374
13375        String cid;
13376        String packagePath;
13377        String resourcePath;
13378
13379        /** New install */
13380        AsecInstallArgs(InstallParams params) {
13381            super(params.origin, params.move, params.observer, params.installFlags,
13382                    params.installerPackageName, params.volumeUuid,
13383                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13384                    params.grantedRuntimePermissions,
13385                    params.traceMethod, params.traceCookie, params.certificates);
13386        }
13387
13388        /** Existing install */
13389        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13390                        boolean isExternal, boolean isForwardLocked) {
13391            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13392              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13393                    instructionSets, null, null, null, 0, null /*certificates*/);
13394            // Hackily pretend we're still looking at a full code path
13395            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13396                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13397            }
13398
13399            // Extract cid from fullCodePath
13400            int eidx = fullCodePath.lastIndexOf("/");
13401            String subStr1 = fullCodePath.substring(0, eidx);
13402            int sidx = subStr1.lastIndexOf("/");
13403            cid = subStr1.substring(sidx+1, eidx);
13404            setMountPath(subStr1);
13405        }
13406
13407        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13408            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13409              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13410                    instructionSets, null, null, null, 0, null /*certificates*/);
13411            this.cid = cid;
13412            setMountPath(PackageHelper.getSdDir(cid));
13413        }
13414
13415        void createCopyFile() {
13416            cid = mInstallerService.allocateExternalStageCidLegacy();
13417        }
13418
13419        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13420            if (origin.staged && origin.cid != null) {
13421                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13422                cid = origin.cid;
13423                setMountPath(PackageHelper.getSdDir(cid));
13424                return PackageManager.INSTALL_SUCCEEDED;
13425            }
13426
13427            if (temp) {
13428                createCopyFile();
13429            } else {
13430                /*
13431                 * Pre-emptively destroy the container since it's destroyed if
13432                 * copying fails due to it existing anyway.
13433                 */
13434                PackageHelper.destroySdDir(cid);
13435            }
13436
13437            final String newMountPath = imcs.copyPackageToContainer(
13438                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13439                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13440
13441            if (newMountPath != null) {
13442                setMountPath(newMountPath);
13443                return PackageManager.INSTALL_SUCCEEDED;
13444            } else {
13445                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13446            }
13447        }
13448
13449        @Override
13450        String getCodePath() {
13451            return packagePath;
13452        }
13453
13454        @Override
13455        String getResourcePath() {
13456            return resourcePath;
13457        }
13458
13459        int doPreInstall(int status) {
13460            if (status != PackageManager.INSTALL_SUCCEEDED) {
13461                // Destroy container
13462                PackageHelper.destroySdDir(cid);
13463            } else {
13464                boolean mounted = PackageHelper.isContainerMounted(cid);
13465                if (!mounted) {
13466                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13467                            Process.SYSTEM_UID);
13468                    if (newMountPath != null) {
13469                        setMountPath(newMountPath);
13470                    } else {
13471                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13472                    }
13473                }
13474            }
13475            return status;
13476        }
13477
13478        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13479            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13480            String newMountPath = null;
13481            if (PackageHelper.isContainerMounted(cid)) {
13482                // Unmount the container
13483                if (!PackageHelper.unMountSdDir(cid)) {
13484                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13485                    return false;
13486                }
13487            }
13488            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13489                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13490                        " which might be stale. Will try to clean up.");
13491                // Clean up the stale container and proceed to recreate.
13492                if (!PackageHelper.destroySdDir(newCacheId)) {
13493                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13494                    return false;
13495                }
13496                // Successfully cleaned up stale container. Try to rename again.
13497                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13498                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13499                            + " inspite of cleaning it up.");
13500                    return false;
13501                }
13502            }
13503            if (!PackageHelper.isContainerMounted(newCacheId)) {
13504                Slog.w(TAG, "Mounting container " + newCacheId);
13505                newMountPath = PackageHelper.mountSdDir(newCacheId,
13506                        getEncryptKey(), Process.SYSTEM_UID);
13507            } else {
13508                newMountPath = PackageHelper.getSdDir(newCacheId);
13509            }
13510            if (newMountPath == null) {
13511                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13512                return false;
13513            }
13514            Log.i(TAG, "Succesfully renamed " + cid +
13515                    " to " + newCacheId +
13516                    " at new path: " + newMountPath);
13517            cid = newCacheId;
13518
13519            final File beforeCodeFile = new File(packagePath);
13520            setMountPath(newMountPath);
13521            final File afterCodeFile = new File(packagePath);
13522
13523            // Reflect the rename in scanned details
13524            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13525            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13526                    afterCodeFile, pkg.baseCodePath));
13527            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13528                    afterCodeFile, pkg.splitCodePaths));
13529
13530            // Reflect the rename in app info
13531            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13532            pkg.setApplicationInfoCodePath(pkg.codePath);
13533            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13534            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13535            pkg.setApplicationInfoResourcePath(pkg.codePath);
13536            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13537            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13538
13539            return true;
13540        }
13541
13542        private void setMountPath(String mountPath) {
13543            final File mountFile = new File(mountPath);
13544
13545            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13546            if (monolithicFile.exists()) {
13547                packagePath = monolithicFile.getAbsolutePath();
13548                if (isFwdLocked()) {
13549                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13550                } else {
13551                    resourcePath = packagePath;
13552                }
13553            } else {
13554                packagePath = mountFile.getAbsolutePath();
13555                resourcePath = packagePath;
13556            }
13557        }
13558
13559        int doPostInstall(int status, int uid) {
13560            if (status != PackageManager.INSTALL_SUCCEEDED) {
13561                cleanUp();
13562            } else {
13563                final int groupOwner;
13564                final String protectedFile;
13565                if (isFwdLocked()) {
13566                    groupOwner = UserHandle.getSharedAppGid(uid);
13567                    protectedFile = RES_FILE_NAME;
13568                } else {
13569                    groupOwner = -1;
13570                    protectedFile = null;
13571                }
13572
13573                if (uid < Process.FIRST_APPLICATION_UID
13574                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13575                    Slog.e(TAG, "Failed to finalize " + cid);
13576                    PackageHelper.destroySdDir(cid);
13577                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13578                }
13579
13580                boolean mounted = PackageHelper.isContainerMounted(cid);
13581                if (!mounted) {
13582                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13583                }
13584            }
13585            return status;
13586        }
13587
13588        private void cleanUp() {
13589            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13590
13591            // Destroy secure container
13592            PackageHelper.destroySdDir(cid);
13593        }
13594
13595        private List<String> getAllCodePaths() {
13596            final File codeFile = new File(getCodePath());
13597            if (codeFile != null && codeFile.exists()) {
13598                try {
13599                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13600                    return pkg.getAllCodePaths();
13601                } catch (PackageParserException e) {
13602                    // Ignored; we tried our best
13603                }
13604            }
13605            return Collections.EMPTY_LIST;
13606        }
13607
13608        void cleanUpResourcesLI() {
13609            // Enumerate all code paths before deleting
13610            cleanUpResourcesLI(getAllCodePaths());
13611        }
13612
13613        private void cleanUpResourcesLI(List<String> allCodePaths) {
13614            cleanUp();
13615            removeDexFiles(allCodePaths, instructionSets);
13616        }
13617
13618        String getPackageName() {
13619            return getAsecPackageName(cid);
13620        }
13621
13622        boolean doPostDeleteLI(boolean delete) {
13623            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13624            final List<String> allCodePaths = getAllCodePaths();
13625            boolean mounted = PackageHelper.isContainerMounted(cid);
13626            if (mounted) {
13627                // Unmount first
13628                if (PackageHelper.unMountSdDir(cid)) {
13629                    mounted = false;
13630                }
13631            }
13632            if (!mounted && delete) {
13633                cleanUpResourcesLI(allCodePaths);
13634            }
13635            return !mounted;
13636        }
13637
13638        @Override
13639        int doPreCopy() {
13640            if (isFwdLocked()) {
13641                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13642                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13643                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13644                }
13645            }
13646
13647            return PackageManager.INSTALL_SUCCEEDED;
13648        }
13649
13650        @Override
13651        int doPostCopy(int uid) {
13652            if (isFwdLocked()) {
13653                if (uid < Process.FIRST_APPLICATION_UID
13654                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13655                                RES_FILE_NAME)) {
13656                    Slog.e(TAG, "Failed to finalize " + cid);
13657                    PackageHelper.destroySdDir(cid);
13658                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13659                }
13660            }
13661
13662            return PackageManager.INSTALL_SUCCEEDED;
13663        }
13664    }
13665
13666    /**
13667     * Logic to handle movement of existing installed applications.
13668     */
13669    class MoveInstallArgs extends InstallArgs {
13670        private File codeFile;
13671        private File resourceFile;
13672
13673        /** New install */
13674        MoveInstallArgs(InstallParams params) {
13675            super(params.origin, params.move, params.observer, params.installFlags,
13676                    params.installerPackageName, params.volumeUuid,
13677                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13678                    params.grantedRuntimePermissions,
13679                    params.traceMethod, params.traceCookie, params.certificates);
13680        }
13681
13682        int copyApk(IMediaContainerService imcs, boolean temp) {
13683            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13684                    + move.fromUuid + " to " + move.toUuid);
13685            synchronized (mInstaller) {
13686                try {
13687                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13688                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13689                } catch (InstallerException e) {
13690                    Slog.w(TAG, "Failed to move app", e);
13691                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13692                }
13693            }
13694
13695            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13696            resourceFile = codeFile;
13697            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13698
13699            return PackageManager.INSTALL_SUCCEEDED;
13700        }
13701
13702        int doPreInstall(int status) {
13703            if (status != PackageManager.INSTALL_SUCCEEDED) {
13704                cleanUp(move.toUuid);
13705            }
13706            return status;
13707        }
13708
13709        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13710            if (status != PackageManager.INSTALL_SUCCEEDED) {
13711                cleanUp(move.toUuid);
13712                return false;
13713            }
13714
13715            // Reflect the move in app info
13716            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13717            pkg.setApplicationInfoCodePath(pkg.codePath);
13718            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13719            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13720            pkg.setApplicationInfoResourcePath(pkg.codePath);
13721            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13722            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13723
13724            return true;
13725        }
13726
13727        int doPostInstall(int status, int uid) {
13728            if (status == PackageManager.INSTALL_SUCCEEDED) {
13729                cleanUp(move.fromUuid);
13730            } else {
13731                cleanUp(move.toUuid);
13732            }
13733            return status;
13734        }
13735
13736        @Override
13737        String getCodePath() {
13738            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13739        }
13740
13741        @Override
13742        String getResourcePath() {
13743            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13744        }
13745
13746        private boolean cleanUp(String volumeUuid) {
13747            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13748                    move.dataAppName);
13749            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13750            final int[] userIds = sUserManager.getUserIds();
13751            synchronized (mInstallLock) {
13752                // Clean up both app data and code
13753                // All package moves are frozen until finished
13754                for (int userId : userIds) {
13755                    try {
13756                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13757                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13758                    } catch (InstallerException e) {
13759                        Slog.w(TAG, String.valueOf(e));
13760                    }
13761                }
13762                removeCodePathLI(codeFile);
13763            }
13764            return true;
13765        }
13766
13767        void cleanUpResourcesLI() {
13768            throw new UnsupportedOperationException();
13769        }
13770
13771        boolean doPostDeleteLI(boolean delete) {
13772            throw new UnsupportedOperationException();
13773        }
13774    }
13775
13776    static String getAsecPackageName(String packageCid) {
13777        int idx = packageCid.lastIndexOf("-");
13778        if (idx == -1) {
13779            return packageCid;
13780        }
13781        return packageCid.substring(0, idx);
13782    }
13783
13784    // Utility method used to create code paths based on package name and available index.
13785    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13786        String idxStr = "";
13787        int idx = 1;
13788        // Fall back to default value of idx=1 if prefix is not
13789        // part of oldCodePath
13790        if (oldCodePath != null) {
13791            String subStr = oldCodePath;
13792            // Drop the suffix right away
13793            if (suffix != null && subStr.endsWith(suffix)) {
13794                subStr = subStr.substring(0, subStr.length() - suffix.length());
13795            }
13796            // If oldCodePath already contains prefix find out the
13797            // ending index to either increment or decrement.
13798            int sidx = subStr.lastIndexOf(prefix);
13799            if (sidx != -1) {
13800                subStr = subStr.substring(sidx + prefix.length());
13801                if (subStr != null) {
13802                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13803                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13804                    }
13805                    try {
13806                        idx = Integer.parseInt(subStr);
13807                        if (idx <= 1) {
13808                            idx++;
13809                        } else {
13810                            idx--;
13811                        }
13812                    } catch(NumberFormatException e) {
13813                    }
13814                }
13815            }
13816        }
13817        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13818        return prefix + idxStr;
13819    }
13820
13821    private File getNextCodePath(File targetDir, String packageName) {
13822        int suffix = 1;
13823        File result;
13824        do {
13825            result = new File(targetDir, packageName + "-" + suffix);
13826            suffix++;
13827        } while (result.exists());
13828        return result;
13829    }
13830
13831    // Utility method that returns the relative package path with respect
13832    // to the installation directory. Like say for /data/data/com.test-1.apk
13833    // string com.test-1 is returned.
13834    static String deriveCodePathName(String codePath) {
13835        if (codePath == null) {
13836            return null;
13837        }
13838        final File codeFile = new File(codePath);
13839        final String name = codeFile.getName();
13840        if (codeFile.isDirectory()) {
13841            return name;
13842        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13843            final int lastDot = name.lastIndexOf('.');
13844            return name.substring(0, lastDot);
13845        } else {
13846            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13847            return null;
13848        }
13849    }
13850
13851    static class PackageInstalledInfo {
13852        String name;
13853        int uid;
13854        // The set of users that originally had this package installed.
13855        int[] origUsers;
13856        // The set of users that now have this package installed.
13857        int[] newUsers;
13858        PackageParser.Package pkg;
13859        int returnCode;
13860        String returnMsg;
13861        PackageRemovedInfo removedInfo;
13862        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13863
13864        public void setError(int code, String msg) {
13865            setReturnCode(code);
13866            setReturnMessage(msg);
13867            Slog.w(TAG, msg);
13868        }
13869
13870        public void setError(String msg, PackageParserException e) {
13871            setReturnCode(e.error);
13872            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13873            Slog.w(TAG, msg, e);
13874        }
13875
13876        public void setError(String msg, PackageManagerException e) {
13877            returnCode = e.error;
13878            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13879            Slog.w(TAG, msg, e);
13880        }
13881
13882        public void setReturnCode(int returnCode) {
13883            this.returnCode = returnCode;
13884            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13885            for (int i = 0; i < childCount; i++) {
13886                addedChildPackages.valueAt(i).returnCode = returnCode;
13887            }
13888        }
13889
13890        private void setReturnMessage(String returnMsg) {
13891            this.returnMsg = returnMsg;
13892            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13893            for (int i = 0; i < childCount; i++) {
13894                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13895            }
13896        }
13897
13898        // In some error cases we want to convey more info back to the observer
13899        String origPackage;
13900        String origPermission;
13901    }
13902
13903    /*
13904     * Install a non-existing package.
13905     */
13906    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13907            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13908            PackageInstalledInfo res) {
13909        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13910
13911        // Remember this for later, in case we need to rollback this install
13912        String pkgName = pkg.packageName;
13913
13914        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13915
13916        synchronized(mPackages) {
13917            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13918                // A package with the same name is already installed, though
13919                // it has been renamed to an older name.  The package we
13920                // are trying to install should be installed as an update to
13921                // the existing one, but that has not been requested, so bail.
13922                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13923                        + " without first uninstalling package running as "
13924                        + mSettings.mRenamedPackages.get(pkgName));
13925                return;
13926            }
13927            if (mPackages.containsKey(pkgName)) {
13928                // Don't allow installation over an existing package with the same name.
13929                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13930                        + " without first uninstalling.");
13931                return;
13932            }
13933        }
13934
13935        try {
13936            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13937                    System.currentTimeMillis(), user);
13938
13939            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13940
13941            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13942                prepareAppDataAfterInstallLIF(newPackage);
13943
13944            } else {
13945                // Remove package from internal structures, but keep around any
13946                // data that might have already existed
13947                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13948                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13949            }
13950        } catch (PackageManagerException e) {
13951            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13952        }
13953
13954        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13955    }
13956
13957    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13958        // Can't rotate keys during boot or if sharedUser.
13959        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13960                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13961            return false;
13962        }
13963        // app is using upgradeKeySets; make sure all are valid
13964        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13965        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13966        for (int i = 0; i < upgradeKeySets.length; i++) {
13967            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13968                Slog.wtf(TAG, "Package "
13969                         + (oldPs.name != null ? oldPs.name : "<null>")
13970                         + " contains upgrade-key-set reference to unknown key-set: "
13971                         + upgradeKeySets[i]
13972                         + " reverting to signatures check.");
13973                return false;
13974            }
13975        }
13976        return true;
13977    }
13978
13979    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13980        // Upgrade keysets are being used.  Determine if new package has a superset of the
13981        // required keys.
13982        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13983        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13984        for (int i = 0; i < upgradeKeySets.length; i++) {
13985            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13986            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13987                return true;
13988            }
13989        }
13990        return false;
13991    }
13992
13993    private static void updateDigest(MessageDigest digest, File file) throws IOException {
13994        try (DigestInputStream digestStream =
13995                new DigestInputStream(new FileInputStream(file), digest)) {
13996            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
13997        }
13998    }
13999
14000    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14001            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14002        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14003
14004        final PackageParser.Package oldPackage;
14005        final String pkgName = pkg.packageName;
14006        final int[] allUsers;
14007        final int[] installedUsers;
14008
14009        synchronized(mPackages) {
14010            oldPackage = mPackages.get(pkgName);
14011            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14012
14013            // don't allow upgrade to target a release SDK from a pre-release SDK
14014            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14015                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14016            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14017                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14018            if (oldTargetsPreRelease
14019                    && !newTargetsPreRelease
14020                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14021                Slog.w(TAG, "Can't install package targeting released sdk");
14022                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14023                return;
14024            }
14025
14026            // don't allow an upgrade from full to ephemeral
14027            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14028            if (isEphemeral && !oldIsEphemeral) {
14029                // can't downgrade from full to ephemeral
14030                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14031                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14032                return;
14033            }
14034
14035            // verify signatures are valid
14036            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14037            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14038                if (!checkUpgradeKeySetLP(ps, pkg)) {
14039                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14040                            "New package not signed by keys specified by upgrade-keysets: "
14041                                    + pkgName);
14042                    return;
14043                }
14044            } else {
14045                // default to original signature matching
14046                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14047                        != PackageManager.SIGNATURE_MATCH) {
14048                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14049                            "New package has a different signature: " + pkgName);
14050                    return;
14051                }
14052            }
14053
14054            // don't allow a system upgrade unless the upgrade hash matches
14055            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14056                byte[] digestBytes = null;
14057                try {
14058                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14059                    updateDigest(digest, new File(pkg.baseCodePath));
14060                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14061                        for (String path : pkg.splitCodePaths) {
14062                            updateDigest(digest, new File(path));
14063                        }
14064                    }
14065                    digestBytes = digest.digest();
14066                } catch (NoSuchAlgorithmException | IOException e) {
14067                    res.setError(INSTALL_FAILED_INVALID_APK,
14068                            "Could not compute hash: " + pkgName);
14069                    return;
14070                }
14071                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14072                    res.setError(INSTALL_FAILED_INVALID_APK,
14073                            "New package fails restrict-update check: " + pkgName);
14074                    return;
14075                }
14076                // retain upgrade restriction
14077                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14078            }
14079
14080            // Check for shared user id changes
14081            String invalidPackageName =
14082                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14083            if (invalidPackageName != null) {
14084                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14085                        "Package " + invalidPackageName + " tried to change user "
14086                                + oldPackage.mSharedUserId);
14087                return;
14088            }
14089
14090            // In case of rollback, remember per-user/profile install state
14091            allUsers = sUserManager.getUserIds();
14092            installedUsers = ps.queryInstalledUsers(allUsers, true);
14093        }
14094
14095        // Update what is removed
14096        res.removedInfo = new PackageRemovedInfo();
14097        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14098        res.removedInfo.removedPackage = oldPackage.packageName;
14099        res.removedInfo.isUpdate = true;
14100        res.removedInfo.origUsers = installedUsers;
14101        final int childCount = (oldPackage.childPackages != null)
14102                ? oldPackage.childPackages.size() : 0;
14103        for (int i = 0; i < childCount; i++) {
14104            boolean childPackageUpdated = false;
14105            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14106            if (res.addedChildPackages != null) {
14107                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14108                if (childRes != null) {
14109                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14110                    childRes.removedInfo.removedPackage = childPkg.packageName;
14111                    childRes.removedInfo.isUpdate = true;
14112                    childPackageUpdated = true;
14113                }
14114            }
14115            if (!childPackageUpdated) {
14116                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14117                childRemovedRes.removedPackage = childPkg.packageName;
14118                childRemovedRes.isUpdate = false;
14119                childRemovedRes.dataRemoved = true;
14120                synchronized (mPackages) {
14121                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14122                    if (childPs != null) {
14123                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14124                    }
14125                }
14126                if (res.removedInfo.removedChildPackages == null) {
14127                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14128                }
14129                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14130            }
14131        }
14132
14133        boolean sysPkg = (isSystemApp(oldPackage));
14134        if (sysPkg) {
14135            // Set the system/privileged flags as needed
14136            final boolean privileged =
14137                    (oldPackage.applicationInfo.privateFlags
14138                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14139            final int systemPolicyFlags = policyFlags
14140                    | PackageParser.PARSE_IS_SYSTEM
14141                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14142
14143            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14144                    user, allUsers, installerPackageName, res);
14145        } else {
14146            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14147                    user, allUsers, installerPackageName, res);
14148        }
14149    }
14150
14151    public List<String> getPreviousCodePaths(String packageName) {
14152        final PackageSetting ps = mSettings.mPackages.get(packageName);
14153        final List<String> result = new ArrayList<String>();
14154        if (ps != null && ps.oldCodePaths != null) {
14155            result.addAll(ps.oldCodePaths);
14156        }
14157        return result;
14158    }
14159
14160    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14161            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14162            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14163        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14164                + deletedPackage);
14165
14166        String pkgName = deletedPackage.packageName;
14167        boolean deletedPkg = true;
14168        boolean addedPkg = false;
14169        boolean updatedSettings = false;
14170        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14171        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14172                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14173
14174        final long origUpdateTime = (pkg.mExtras != null)
14175                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14176
14177        // First delete the existing package while retaining the data directory
14178        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14179                res.removedInfo, true, pkg)) {
14180            // If the existing package wasn't successfully deleted
14181            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14182            deletedPkg = false;
14183        } else {
14184            // Successfully deleted the old package; proceed with replace.
14185
14186            // If deleted package lived in a container, give users a chance to
14187            // relinquish resources before killing.
14188            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14189                if (DEBUG_INSTALL) {
14190                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14191                }
14192                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14193                final ArrayList<String> pkgList = new ArrayList<String>(1);
14194                pkgList.add(deletedPackage.applicationInfo.packageName);
14195                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14196            }
14197
14198            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14199                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14200            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14201
14202            try {
14203                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14204                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14205                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14206
14207                // Update the in-memory copy of the previous code paths.
14208                PackageSetting ps = mSettings.mPackages.get(pkgName);
14209                if (!killApp) {
14210                    if (ps.oldCodePaths == null) {
14211                        ps.oldCodePaths = new ArraySet<>();
14212                    }
14213                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14214                    if (deletedPackage.splitCodePaths != null) {
14215                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14216                    }
14217                } else {
14218                    ps.oldCodePaths = null;
14219                }
14220                if (ps.childPackageNames != null) {
14221                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14222                        final String childPkgName = ps.childPackageNames.get(i);
14223                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14224                        childPs.oldCodePaths = ps.oldCodePaths;
14225                    }
14226                }
14227                prepareAppDataAfterInstallLIF(newPackage);
14228                addedPkg = true;
14229            } catch (PackageManagerException e) {
14230                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14231            }
14232        }
14233
14234        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14235            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14236
14237            // Revert all internal state mutations and added folders for the failed install
14238            if (addedPkg) {
14239                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14240                        res.removedInfo, true, null);
14241            }
14242
14243            // Restore the old package
14244            if (deletedPkg) {
14245                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14246                File restoreFile = new File(deletedPackage.codePath);
14247                // Parse old package
14248                boolean oldExternal = isExternal(deletedPackage);
14249                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14250                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14251                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14252                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14253                try {
14254                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14255                            null);
14256                } catch (PackageManagerException e) {
14257                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14258                            + e.getMessage());
14259                    return;
14260                }
14261
14262                synchronized (mPackages) {
14263                    // Ensure the installer package name up to date
14264                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14265
14266                    // Update permissions for restored package
14267                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14268
14269                    mSettings.writeLPr();
14270                }
14271
14272                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14273            }
14274        } else {
14275            synchronized (mPackages) {
14276                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14277                if (ps != null) {
14278                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14279                    if (res.removedInfo.removedChildPackages != null) {
14280                        final int childCount = res.removedInfo.removedChildPackages.size();
14281                        // Iterate in reverse as we may modify the collection
14282                        for (int i = childCount - 1; i >= 0; i--) {
14283                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14284                            if (res.addedChildPackages.containsKey(childPackageName)) {
14285                                res.removedInfo.removedChildPackages.removeAt(i);
14286                            } else {
14287                                PackageRemovedInfo childInfo = res.removedInfo
14288                                        .removedChildPackages.valueAt(i);
14289                                childInfo.removedForAllUsers = mPackages.get(
14290                                        childInfo.removedPackage) == null;
14291                            }
14292                        }
14293                    }
14294                }
14295            }
14296        }
14297    }
14298
14299    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14300            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14301            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14302        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14303                + ", old=" + deletedPackage);
14304
14305        final boolean disabledSystem;
14306
14307        // Remove existing system package
14308        removePackageLI(deletedPackage, true);
14309
14310        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14311        if (!disabledSystem) {
14312            // We didn't need to disable the .apk as a current system package,
14313            // which means we are replacing another update that is already
14314            // installed.  We need to make sure to delete the older one's .apk.
14315            res.removedInfo.args = createInstallArgsForExisting(0,
14316                    deletedPackage.applicationInfo.getCodePath(),
14317                    deletedPackage.applicationInfo.getResourcePath(),
14318                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14319        } else {
14320            res.removedInfo.args = null;
14321        }
14322
14323        // Successfully disabled the old package. Now proceed with re-installation
14324        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14325                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14326        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14327
14328        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14329        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14330                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14331
14332        PackageParser.Package newPackage = null;
14333        try {
14334            // Add the package to the internal data structures
14335            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14336
14337            // Set the update and install times
14338            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14339            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14340                    System.currentTimeMillis());
14341
14342            // Update the package dynamic state if succeeded
14343            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14344                // Now that the install succeeded make sure we remove data
14345                // directories for any child package the update removed.
14346                final int deletedChildCount = (deletedPackage.childPackages != null)
14347                        ? deletedPackage.childPackages.size() : 0;
14348                final int newChildCount = (newPackage.childPackages != null)
14349                        ? newPackage.childPackages.size() : 0;
14350                for (int i = 0; i < deletedChildCount; i++) {
14351                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14352                    boolean childPackageDeleted = true;
14353                    for (int j = 0; j < newChildCount; j++) {
14354                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14355                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14356                            childPackageDeleted = false;
14357                            break;
14358                        }
14359                    }
14360                    if (childPackageDeleted) {
14361                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14362                                deletedChildPkg.packageName);
14363                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14364                            PackageRemovedInfo removedChildRes = res.removedInfo
14365                                    .removedChildPackages.get(deletedChildPkg.packageName);
14366                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14367                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14368                        }
14369                    }
14370                }
14371
14372                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14373                prepareAppDataAfterInstallLIF(newPackage);
14374            }
14375        } catch (PackageManagerException e) {
14376            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14377            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14378        }
14379
14380        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14381            // Re installation failed. Restore old information
14382            // Remove new pkg information
14383            if (newPackage != null) {
14384                removeInstalledPackageLI(newPackage, true);
14385            }
14386            // Add back the old system package
14387            try {
14388                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14389            } catch (PackageManagerException e) {
14390                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14391            }
14392
14393            synchronized (mPackages) {
14394                if (disabledSystem) {
14395                    enableSystemPackageLPw(deletedPackage);
14396                }
14397
14398                // Ensure the installer package name up to date
14399                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14400
14401                // Update permissions for restored package
14402                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14403
14404                mSettings.writeLPr();
14405            }
14406
14407            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14408                    + " after failed upgrade");
14409        }
14410    }
14411
14412    /**
14413     * Checks whether the parent or any of the child packages have a change shared
14414     * user. For a package to be a valid update the shred users of the parent and
14415     * the children should match. We may later support changing child shared users.
14416     * @param oldPkg The updated package.
14417     * @param newPkg The update package.
14418     * @return The shared user that change between the versions.
14419     */
14420    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14421            PackageParser.Package newPkg) {
14422        // Check parent shared user
14423        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14424            return newPkg.packageName;
14425        }
14426        // Check child shared users
14427        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14428        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14429        for (int i = 0; i < newChildCount; i++) {
14430            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14431            // If this child was present, did it have the same shared user?
14432            for (int j = 0; j < oldChildCount; j++) {
14433                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14434                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14435                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14436                    return newChildPkg.packageName;
14437                }
14438            }
14439        }
14440        return null;
14441    }
14442
14443    private void removeNativeBinariesLI(PackageSetting ps) {
14444        // Remove the lib path for the parent package
14445        if (ps != null) {
14446            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14447            // Remove the lib path for the child packages
14448            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14449            for (int i = 0; i < childCount; i++) {
14450                PackageSetting childPs = null;
14451                synchronized (mPackages) {
14452                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14453                }
14454                if (childPs != null) {
14455                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14456                            .legacyNativeLibraryPathString);
14457                }
14458            }
14459        }
14460    }
14461
14462    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14463        // Enable the parent package
14464        mSettings.enableSystemPackageLPw(pkg.packageName);
14465        // Enable the child packages
14466        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14467        for (int i = 0; i < childCount; i++) {
14468            PackageParser.Package childPkg = pkg.childPackages.get(i);
14469            mSettings.enableSystemPackageLPw(childPkg.packageName);
14470        }
14471    }
14472
14473    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14474            PackageParser.Package newPkg) {
14475        // Disable the parent package (parent always replaced)
14476        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14477        // Disable the child packages
14478        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14479        for (int i = 0; i < childCount; i++) {
14480            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14481            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14482            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14483        }
14484        return disabled;
14485    }
14486
14487    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14488            String installerPackageName) {
14489        // Enable the parent package
14490        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14491        // Enable the child packages
14492        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14493        for (int i = 0; i < childCount; i++) {
14494            PackageParser.Package childPkg = pkg.childPackages.get(i);
14495            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14496        }
14497    }
14498
14499    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14500        // Collect all used permissions in the UID
14501        ArraySet<String> usedPermissions = new ArraySet<>();
14502        final int packageCount = su.packages.size();
14503        for (int i = 0; i < packageCount; i++) {
14504            PackageSetting ps = su.packages.valueAt(i);
14505            if (ps.pkg == null) {
14506                continue;
14507            }
14508            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14509            for (int j = 0; j < requestedPermCount; j++) {
14510                String permission = ps.pkg.requestedPermissions.get(j);
14511                BasePermission bp = mSettings.mPermissions.get(permission);
14512                if (bp != null) {
14513                    usedPermissions.add(permission);
14514                }
14515            }
14516        }
14517
14518        PermissionsState permissionsState = su.getPermissionsState();
14519        // Prune install permissions
14520        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14521        final int installPermCount = installPermStates.size();
14522        for (int i = installPermCount - 1; i >= 0;  i--) {
14523            PermissionState permissionState = installPermStates.get(i);
14524            if (!usedPermissions.contains(permissionState.getName())) {
14525                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14526                if (bp != null) {
14527                    permissionsState.revokeInstallPermission(bp);
14528                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14529                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14530                }
14531            }
14532        }
14533
14534        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14535
14536        // Prune runtime permissions
14537        for (int userId : allUserIds) {
14538            List<PermissionState> runtimePermStates = permissionsState
14539                    .getRuntimePermissionStates(userId);
14540            final int runtimePermCount = runtimePermStates.size();
14541            for (int i = runtimePermCount - 1; i >= 0; i--) {
14542                PermissionState permissionState = runtimePermStates.get(i);
14543                if (!usedPermissions.contains(permissionState.getName())) {
14544                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14545                    if (bp != null) {
14546                        permissionsState.revokeRuntimePermission(bp, userId);
14547                        permissionsState.updatePermissionFlags(bp, userId,
14548                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14549                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14550                                runtimePermissionChangedUserIds, userId);
14551                    }
14552                }
14553            }
14554        }
14555
14556        return runtimePermissionChangedUserIds;
14557    }
14558
14559    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14560            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14561        // Update the parent package setting
14562        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14563                res, user);
14564        // Update the child packages setting
14565        final int childCount = (newPackage.childPackages != null)
14566                ? newPackage.childPackages.size() : 0;
14567        for (int i = 0; i < childCount; i++) {
14568            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14569            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14570            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14571                    childRes.origUsers, childRes, user);
14572        }
14573    }
14574
14575    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14576            String installerPackageName, int[] allUsers, int[] installedForUsers,
14577            PackageInstalledInfo res, UserHandle user) {
14578        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14579
14580        String pkgName = newPackage.packageName;
14581        synchronized (mPackages) {
14582            //write settings. the installStatus will be incomplete at this stage.
14583            //note that the new package setting would have already been
14584            //added to mPackages. It hasn't been persisted yet.
14585            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14586            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14587            mSettings.writeLPr();
14588            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14589        }
14590
14591        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14592        synchronized (mPackages) {
14593            updatePermissionsLPw(newPackage.packageName, newPackage,
14594                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14595                            ? UPDATE_PERMISSIONS_ALL : 0));
14596            // For system-bundled packages, we assume that installing an upgraded version
14597            // of the package implies that the user actually wants to run that new code,
14598            // so we enable the package.
14599            PackageSetting ps = mSettings.mPackages.get(pkgName);
14600            final int userId = user.getIdentifier();
14601            if (ps != null) {
14602                if (isSystemApp(newPackage)) {
14603                    if (DEBUG_INSTALL) {
14604                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14605                    }
14606                    // Enable system package for requested users
14607                    if (res.origUsers != null) {
14608                        for (int origUserId : res.origUsers) {
14609                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14610                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14611                                        origUserId, installerPackageName);
14612                            }
14613                        }
14614                    }
14615                    // Also convey the prior install/uninstall state
14616                    if (allUsers != null && installedForUsers != null) {
14617                        for (int currentUserId : allUsers) {
14618                            final boolean installed = ArrayUtils.contains(
14619                                    installedForUsers, currentUserId);
14620                            if (DEBUG_INSTALL) {
14621                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14622                            }
14623                            ps.setInstalled(installed, currentUserId);
14624                        }
14625                        // these install state changes will be persisted in the
14626                        // upcoming call to mSettings.writeLPr().
14627                    }
14628                }
14629                // It's implied that when a user requests installation, they want the app to be
14630                // installed and enabled.
14631                if (userId != UserHandle.USER_ALL) {
14632                    ps.setInstalled(true, userId);
14633                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14634                }
14635            }
14636            res.name = pkgName;
14637            res.uid = newPackage.applicationInfo.uid;
14638            res.pkg = newPackage;
14639            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14640            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14641            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14642            //to update install status
14643            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14644            mSettings.writeLPr();
14645            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14646        }
14647
14648        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14649    }
14650
14651    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14652        try {
14653            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14654            installPackageLI(args, res);
14655        } finally {
14656            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14657        }
14658    }
14659
14660    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14661        final int installFlags = args.installFlags;
14662        final String installerPackageName = args.installerPackageName;
14663        final String volumeUuid = args.volumeUuid;
14664        final File tmpPackageFile = new File(args.getCodePath());
14665        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14666        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14667                || (args.volumeUuid != null));
14668        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14669        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14670        boolean replace = false;
14671        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14672        if (args.move != null) {
14673            // moving a complete application; perform an initial scan on the new install location
14674            scanFlags |= SCAN_INITIAL;
14675        }
14676        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14677            scanFlags |= SCAN_DONT_KILL_APP;
14678        }
14679
14680        // Result object to be returned
14681        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14682
14683        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14684
14685        // Sanity check
14686        if (ephemeral && (forwardLocked || onExternal)) {
14687            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14688                    + " external=" + onExternal);
14689            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14690            return;
14691        }
14692
14693        // Retrieve PackageSettings and parse package
14694        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14695                | PackageParser.PARSE_ENFORCE_CODE
14696                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14697                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14698                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14699                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14700        PackageParser pp = new PackageParser();
14701        pp.setSeparateProcesses(mSeparateProcesses);
14702        pp.setDisplayMetrics(mMetrics);
14703
14704        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14705        final PackageParser.Package pkg;
14706        try {
14707            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14708        } catch (PackageParserException e) {
14709            res.setError("Failed parse during installPackageLI", e);
14710            return;
14711        } finally {
14712            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14713        }
14714
14715        // If we are installing a clustered package add results for the children
14716        if (pkg.childPackages != null) {
14717            synchronized (mPackages) {
14718                final int childCount = pkg.childPackages.size();
14719                for (int i = 0; i < childCount; i++) {
14720                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14721                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14722                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14723                    childRes.pkg = childPkg;
14724                    childRes.name = childPkg.packageName;
14725                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14726                    if (childPs != null) {
14727                        childRes.origUsers = childPs.queryInstalledUsers(
14728                                sUserManager.getUserIds(), true);
14729                    }
14730                    if ((mPackages.containsKey(childPkg.packageName))) {
14731                        childRes.removedInfo = new PackageRemovedInfo();
14732                        childRes.removedInfo.removedPackage = childPkg.packageName;
14733                    }
14734                    if (res.addedChildPackages == null) {
14735                        res.addedChildPackages = new ArrayMap<>();
14736                    }
14737                    res.addedChildPackages.put(childPkg.packageName, childRes);
14738                }
14739            }
14740        }
14741
14742        // If package doesn't declare API override, mark that we have an install
14743        // time CPU ABI override.
14744        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14745            pkg.cpuAbiOverride = args.abiOverride;
14746        }
14747
14748        String pkgName = res.name = pkg.packageName;
14749        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14750            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14751                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14752                return;
14753            }
14754        }
14755
14756        try {
14757            // either use what we've been given or parse directly from the APK
14758            if (args.certificates != null) {
14759                try {
14760                    PackageParser.populateCertificates(pkg, args.certificates);
14761                } catch (PackageParserException e) {
14762                    // there was something wrong with the certificates we were given;
14763                    // try to pull them from the APK
14764                    PackageParser.collectCertificates(pkg, parseFlags);
14765                }
14766            } else {
14767                PackageParser.collectCertificates(pkg, parseFlags);
14768            }
14769        } catch (PackageParserException e) {
14770            res.setError("Failed collect during installPackageLI", e);
14771            return;
14772        }
14773
14774        // Get rid of all references to package scan path via parser.
14775        pp = null;
14776        String oldCodePath = null;
14777        boolean systemApp = false;
14778        synchronized (mPackages) {
14779            // Check if installing already existing package
14780            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14781                String oldName = mSettings.mRenamedPackages.get(pkgName);
14782                if (pkg.mOriginalPackages != null
14783                        && pkg.mOriginalPackages.contains(oldName)
14784                        && mPackages.containsKey(oldName)) {
14785                    // This package is derived from an original package,
14786                    // and this device has been updating from that original
14787                    // name.  We must continue using the original name, so
14788                    // rename the new package here.
14789                    pkg.setPackageName(oldName);
14790                    pkgName = pkg.packageName;
14791                    replace = true;
14792                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14793                            + oldName + " pkgName=" + pkgName);
14794                } else if (mPackages.containsKey(pkgName)) {
14795                    // This package, under its official name, already exists
14796                    // on the device; we should replace it.
14797                    replace = true;
14798                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14799                }
14800
14801                // Child packages are installed through the parent package
14802                if (pkg.parentPackage != null) {
14803                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14804                            "Package " + pkg.packageName + " is child of package "
14805                                    + pkg.parentPackage.parentPackage + ". Child packages "
14806                                    + "can be updated only through the parent package.");
14807                    return;
14808                }
14809
14810                if (replace) {
14811                    // Prevent apps opting out from runtime permissions
14812                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14813                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14814                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14815                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14816                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14817                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14818                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14819                                        + " doesn't support runtime permissions but the old"
14820                                        + " target SDK " + oldTargetSdk + " does.");
14821                        return;
14822                    }
14823
14824                    // Prevent installing of child packages
14825                    if (oldPackage.parentPackage != null) {
14826                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14827                                "Package " + pkg.packageName + " is child of package "
14828                                        + oldPackage.parentPackage + ". Child packages "
14829                                        + "can be updated only through the parent package.");
14830                        return;
14831                    }
14832                }
14833            }
14834
14835            PackageSetting ps = mSettings.mPackages.get(pkgName);
14836            if (ps != null) {
14837                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14838
14839                // Quick sanity check that we're signed correctly if updating;
14840                // we'll check this again later when scanning, but we want to
14841                // bail early here before tripping over redefined permissions.
14842                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14843                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14844                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14845                                + pkg.packageName + " upgrade keys do not match the "
14846                                + "previously installed version");
14847                        return;
14848                    }
14849                } else {
14850                    try {
14851                        verifySignaturesLP(ps, pkg);
14852                    } catch (PackageManagerException e) {
14853                        res.setError(e.error, e.getMessage());
14854                        return;
14855                    }
14856                }
14857
14858                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14859                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14860                    systemApp = (ps.pkg.applicationInfo.flags &
14861                            ApplicationInfo.FLAG_SYSTEM) != 0;
14862                }
14863                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14864            }
14865
14866            // Check whether the newly-scanned package wants to define an already-defined perm
14867            int N = pkg.permissions.size();
14868            for (int i = N-1; i >= 0; i--) {
14869                PackageParser.Permission perm = pkg.permissions.get(i);
14870                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14871                if (bp != null) {
14872                    // If the defining package is signed with our cert, it's okay.  This
14873                    // also includes the "updating the same package" case, of course.
14874                    // "updating same package" could also involve key-rotation.
14875                    final boolean sigsOk;
14876                    if (bp.sourcePackage.equals(pkg.packageName)
14877                            && (bp.packageSetting instanceof PackageSetting)
14878                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14879                                    scanFlags))) {
14880                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14881                    } else {
14882                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14883                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14884                    }
14885                    if (!sigsOk) {
14886                        // If the owning package is the system itself, we log but allow
14887                        // install to proceed; we fail the install on all other permission
14888                        // redefinitions.
14889                        if (!bp.sourcePackage.equals("android")) {
14890                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14891                                    + pkg.packageName + " attempting to redeclare permission "
14892                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14893                            res.origPermission = perm.info.name;
14894                            res.origPackage = bp.sourcePackage;
14895                            return;
14896                        } else {
14897                            Slog.w(TAG, "Package " + pkg.packageName
14898                                    + " attempting to redeclare system permission "
14899                                    + perm.info.name + "; ignoring new declaration");
14900                            pkg.permissions.remove(i);
14901                        }
14902                    }
14903                }
14904            }
14905        }
14906
14907        if (systemApp) {
14908            if (onExternal) {
14909                // Abort update; system app can't be replaced with app on sdcard
14910                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14911                        "Cannot install updates to system apps on sdcard");
14912                return;
14913            } else if (ephemeral) {
14914                // Abort update; system app can't be replaced with an ephemeral app
14915                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14916                        "Cannot update a system app with an ephemeral app");
14917                return;
14918            }
14919        }
14920
14921        if (args.move != null) {
14922            // We did an in-place move, so dex is ready to roll
14923            scanFlags |= SCAN_NO_DEX;
14924            scanFlags |= SCAN_MOVE;
14925
14926            synchronized (mPackages) {
14927                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14928                if (ps == null) {
14929                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14930                            "Missing settings for moved package " + pkgName);
14931                }
14932
14933                // We moved the entire application as-is, so bring over the
14934                // previously derived ABI information.
14935                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14936                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14937            }
14938
14939        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14940            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14941            scanFlags |= SCAN_NO_DEX;
14942
14943            try {
14944                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14945                    args.abiOverride : pkg.cpuAbiOverride);
14946                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14947                        true /* extract libs */);
14948            } catch (PackageManagerException pme) {
14949                Slog.e(TAG, "Error deriving application ABI", pme);
14950                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14951                return;
14952            }
14953
14954            // Shared libraries for the package need to be updated.
14955            synchronized (mPackages) {
14956                try {
14957                    updateSharedLibrariesLPw(pkg, null);
14958                } catch (PackageManagerException e) {
14959                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14960                }
14961            }
14962            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14963            // Do not run PackageDexOptimizer through the local performDexOpt
14964            // method because `pkg` is not in `mPackages` yet.
14965            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14966                    null /* instructionSets */, false /* checkProfiles */,
14967                    getCompilerFilterForReason(REASON_INSTALL));
14968            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14969            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14970                String msg = "Extracting package failed for " + pkgName;
14971                res.setError(INSTALL_FAILED_DEXOPT, msg);
14972                return;
14973            }
14974
14975            // Notify BackgroundDexOptService that the package has been changed.
14976            // If this is an update of a package which used to fail to compile,
14977            // BDOS will remove it from its blacklist.
14978            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14979        }
14980
14981        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14982            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14983            return;
14984        }
14985
14986        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14987
14988        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14989                "installPackageLI")) {
14990            if (replace) {
14991                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14992                        installerPackageName, res);
14993            } else {
14994                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14995                        args.user, installerPackageName, volumeUuid, res);
14996            }
14997        }
14998        synchronized (mPackages) {
14999            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15000            if (ps != null) {
15001                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15002            }
15003
15004            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15005            for (int i = 0; i < childCount; i++) {
15006                PackageParser.Package childPkg = pkg.childPackages.get(i);
15007                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15008                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15009                if (childPs != null) {
15010                    childRes.newUsers = childPs.queryInstalledUsers(
15011                            sUserManager.getUserIds(), true);
15012                }
15013            }
15014        }
15015    }
15016
15017    private void startIntentFilterVerifications(int userId, boolean replacing,
15018            PackageParser.Package pkg) {
15019        if (mIntentFilterVerifierComponent == null) {
15020            Slog.w(TAG, "No IntentFilter verification will not be done as "
15021                    + "there is no IntentFilterVerifier available!");
15022            return;
15023        }
15024
15025        final int verifierUid = getPackageUid(
15026                mIntentFilterVerifierComponent.getPackageName(),
15027                MATCH_DEBUG_TRIAGED_MISSING,
15028                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15029
15030        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15031        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15032        mHandler.sendMessage(msg);
15033
15034        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15035        for (int i = 0; i < childCount; i++) {
15036            PackageParser.Package childPkg = pkg.childPackages.get(i);
15037            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15038            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15039            mHandler.sendMessage(msg);
15040        }
15041    }
15042
15043    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15044            PackageParser.Package pkg) {
15045        int size = pkg.activities.size();
15046        if (size == 0) {
15047            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15048                    "No activity, so no need to verify any IntentFilter!");
15049            return;
15050        }
15051
15052        final boolean hasDomainURLs = hasDomainURLs(pkg);
15053        if (!hasDomainURLs) {
15054            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15055                    "No domain URLs, so no need to verify any IntentFilter!");
15056            return;
15057        }
15058
15059        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15060                + " if any IntentFilter from the " + size
15061                + " Activities needs verification ...");
15062
15063        int count = 0;
15064        final String packageName = pkg.packageName;
15065
15066        synchronized (mPackages) {
15067            // If this is a new install and we see that we've already run verification for this
15068            // package, we have nothing to do: it means the state was restored from backup.
15069            if (!replacing) {
15070                IntentFilterVerificationInfo ivi =
15071                        mSettings.getIntentFilterVerificationLPr(packageName);
15072                if (ivi != null) {
15073                    if (DEBUG_DOMAIN_VERIFICATION) {
15074                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15075                                + ivi.getStatusString());
15076                    }
15077                    return;
15078                }
15079            }
15080
15081            // If any filters need to be verified, then all need to be.
15082            boolean needToVerify = false;
15083            for (PackageParser.Activity a : pkg.activities) {
15084                for (ActivityIntentInfo filter : a.intents) {
15085                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15086                        if (DEBUG_DOMAIN_VERIFICATION) {
15087                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15088                        }
15089                        needToVerify = true;
15090                        break;
15091                    }
15092                }
15093            }
15094
15095            if (needToVerify) {
15096                final int verificationId = mIntentFilterVerificationToken++;
15097                for (PackageParser.Activity a : pkg.activities) {
15098                    for (ActivityIntentInfo filter : a.intents) {
15099                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15100                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15101                                    "Verification needed for IntentFilter:" + filter.toString());
15102                            mIntentFilterVerifier.addOneIntentFilterVerification(
15103                                    verifierUid, userId, verificationId, filter, packageName);
15104                            count++;
15105                        }
15106                    }
15107                }
15108            }
15109        }
15110
15111        if (count > 0) {
15112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15113                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15114                    +  " for userId:" + userId);
15115            mIntentFilterVerifier.startVerifications(userId);
15116        } else {
15117            if (DEBUG_DOMAIN_VERIFICATION) {
15118                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15119            }
15120        }
15121    }
15122
15123    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15124        final ComponentName cn  = filter.activity.getComponentName();
15125        final String packageName = cn.getPackageName();
15126
15127        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15128                packageName);
15129        if (ivi == null) {
15130            return true;
15131        }
15132        int status = ivi.getStatus();
15133        switch (status) {
15134            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15135            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15136                return true;
15137
15138            default:
15139                // Nothing to do
15140                return false;
15141        }
15142    }
15143
15144    private static boolean isMultiArch(ApplicationInfo info) {
15145        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15146    }
15147
15148    private static boolean isExternal(PackageParser.Package pkg) {
15149        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15150    }
15151
15152    private static boolean isExternal(PackageSetting ps) {
15153        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15154    }
15155
15156    private static boolean isEphemeral(PackageParser.Package pkg) {
15157        return pkg.applicationInfo.isEphemeralApp();
15158    }
15159
15160    private static boolean isEphemeral(PackageSetting ps) {
15161        return ps.pkg != null && isEphemeral(ps.pkg);
15162    }
15163
15164    private static boolean isSystemApp(PackageParser.Package pkg) {
15165        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15166    }
15167
15168    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15169        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15170    }
15171
15172    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15173        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15174    }
15175
15176    private static boolean isSystemApp(PackageSetting ps) {
15177        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15178    }
15179
15180    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15181        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15182    }
15183
15184    private int packageFlagsToInstallFlags(PackageSetting ps) {
15185        int installFlags = 0;
15186        if (isEphemeral(ps)) {
15187            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15188        }
15189        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15190            // This existing package was an external ASEC install when we have
15191            // the external flag without a UUID
15192            installFlags |= PackageManager.INSTALL_EXTERNAL;
15193        }
15194        if (ps.isForwardLocked()) {
15195            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15196        }
15197        return installFlags;
15198    }
15199
15200    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15201        if (isExternal(pkg)) {
15202            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15203                return StorageManager.UUID_PRIMARY_PHYSICAL;
15204            } else {
15205                return pkg.volumeUuid;
15206            }
15207        } else {
15208            return StorageManager.UUID_PRIVATE_INTERNAL;
15209        }
15210    }
15211
15212    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15213        if (isExternal(pkg)) {
15214            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15215                return mSettings.getExternalVersion();
15216            } else {
15217                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15218            }
15219        } else {
15220            return mSettings.getInternalVersion();
15221        }
15222    }
15223
15224    private void deleteTempPackageFiles() {
15225        final FilenameFilter filter = new FilenameFilter() {
15226            public boolean accept(File dir, String name) {
15227                return name.startsWith("vmdl") && name.endsWith(".tmp");
15228            }
15229        };
15230        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15231            file.delete();
15232        }
15233    }
15234
15235    @Override
15236    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15237            int flags) {
15238        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15239                flags);
15240    }
15241
15242    @Override
15243    public void deletePackage(final String packageName,
15244            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15245        mContext.enforceCallingOrSelfPermission(
15246                android.Manifest.permission.DELETE_PACKAGES, null);
15247        Preconditions.checkNotNull(packageName);
15248        Preconditions.checkNotNull(observer);
15249        final int uid = Binder.getCallingUid();
15250        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15251        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15252        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15253            mContext.enforceCallingOrSelfPermission(
15254                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15255                    "deletePackage for user " + userId);
15256        }
15257
15258        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15259            try {
15260                observer.onPackageDeleted(packageName,
15261                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15262            } catch (RemoteException re) {
15263            }
15264            return;
15265        }
15266
15267        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15268            try {
15269                observer.onPackageDeleted(packageName,
15270                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15271            } catch (RemoteException re) {
15272            }
15273            return;
15274        }
15275
15276        if (DEBUG_REMOVE) {
15277            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15278                    + " deleteAllUsers: " + deleteAllUsers );
15279        }
15280        // Queue up an async operation since the package deletion may take a little while.
15281        mHandler.post(new Runnable() {
15282            public void run() {
15283                mHandler.removeCallbacks(this);
15284                int returnCode;
15285                if (!deleteAllUsers) {
15286                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15287                } else {
15288                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15289                    // If nobody is blocking uninstall, proceed with delete for all users
15290                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15291                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15292                    } else {
15293                        // Otherwise uninstall individually for users with blockUninstalls=false
15294                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15295                        for (int userId : users) {
15296                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15297                                returnCode = deletePackageX(packageName, userId, userFlags);
15298                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15299                                    Slog.w(TAG, "Package delete failed for user " + userId
15300                                            + ", returnCode " + returnCode);
15301                                }
15302                            }
15303                        }
15304                        // The app has only been marked uninstalled for certain users.
15305                        // We still need to report that delete was blocked
15306                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15307                    }
15308                }
15309                try {
15310                    observer.onPackageDeleted(packageName, returnCode, null);
15311                } catch (RemoteException e) {
15312                    Log.i(TAG, "Observer no longer exists.");
15313                } //end catch
15314            } //end run
15315        });
15316    }
15317
15318    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15319        int[] result = EMPTY_INT_ARRAY;
15320        for (int userId : userIds) {
15321            if (getBlockUninstallForUser(packageName, userId)) {
15322                result = ArrayUtils.appendInt(result, userId);
15323            }
15324        }
15325        return result;
15326    }
15327
15328    @Override
15329    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15330        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15331    }
15332
15333    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15334        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15335                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15336        try {
15337            if (dpm != null) {
15338                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15339                        /* callingUserOnly =*/ false);
15340                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15341                        : deviceOwnerComponentName.getPackageName();
15342                // Does the package contains the device owner?
15343                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15344                // this check is probably not needed, since DO should be registered as a device
15345                // admin on some user too. (Original bug for this: b/17657954)
15346                if (packageName.equals(deviceOwnerPackageName)) {
15347                    return true;
15348                }
15349                // Does it contain a device admin for any user?
15350                int[] users;
15351                if (userId == UserHandle.USER_ALL) {
15352                    users = sUserManager.getUserIds();
15353                } else {
15354                    users = new int[]{userId};
15355                }
15356                for (int i = 0; i < users.length; ++i) {
15357                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15358                        return true;
15359                    }
15360                }
15361            }
15362        } catch (RemoteException e) {
15363        }
15364        return false;
15365    }
15366
15367    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15368        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15369    }
15370
15371    /**
15372     *  This method is an internal method that could be get invoked either
15373     *  to delete an installed package or to clean up a failed installation.
15374     *  After deleting an installed package, a broadcast is sent to notify any
15375     *  listeners that the package has been removed. For cleaning up a failed
15376     *  installation, the broadcast is not necessary since the package's
15377     *  installation wouldn't have sent the initial broadcast either
15378     *  The key steps in deleting a package are
15379     *  deleting the package information in internal structures like mPackages,
15380     *  deleting the packages base directories through installd
15381     *  updating mSettings to reflect current status
15382     *  persisting settings for later use
15383     *  sending a broadcast if necessary
15384     */
15385    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15386        final PackageRemovedInfo info = new PackageRemovedInfo();
15387        final boolean res;
15388
15389        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15390                ? UserHandle.ALL : new UserHandle(userId);
15391
15392        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15393            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15394            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15395        }
15396
15397        PackageSetting uninstalledPs = null;
15398
15399        // for the uninstall-updates case and restricted profiles, remember the per-
15400        // user handle installed state
15401        int[] allUsers;
15402        synchronized (mPackages) {
15403            uninstalledPs = mSettings.mPackages.get(packageName);
15404            if (uninstalledPs == null) {
15405                Slog.w(TAG, "Not removing non-existent package " + packageName);
15406                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15407            }
15408            allUsers = sUserManager.getUserIds();
15409            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15410        }
15411
15412        synchronized (mInstallLock) {
15413            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15414            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15415                    "deletePackageX")) {
15416                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15417                        deleteFlags | REMOVE_CHATTY, info, true, null);
15418            }
15419            synchronized (mPackages) {
15420                if (res) {
15421                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15422                }
15423            }
15424        }
15425
15426        if (res) {
15427            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15428            info.sendPackageRemovedBroadcasts(killApp);
15429            info.sendSystemPackageUpdatedBroadcasts();
15430            info.sendSystemPackageAppearedBroadcasts();
15431        }
15432        // Force a gc here.
15433        Runtime.getRuntime().gc();
15434        // Delete the resources here after sending the broadcast to let
15435        // other processes clean up before deleting resources.
15436        if (info.args != null) {
15437            synchronized (mInstallLock) {
15438                info.args.doPostDeleteLI(true);
15439            }
15440        }
15441
15442        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15443    }
15444
15445    class PackageRemovedInfo {
15446        String removedPackage;
15447        int uid = -1;
15448        int removedAppId = -1;
15449        int[] origUsers;
15450        int[] removedUsers = null;
15451        boolean isRemovedPackageSystemUpdate = false;
15452        boolean isUpdate;
15453        boolean dataRemoved;
15454        boolean removedForAllUsers;
15455        // Clean up resources deleted packages.
15456        InstallArgs args = null;
15457        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15458        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15459
15460        void sendPackageRemovedBroadcasts(boolean killApp) {
15461            sendPackageRemovedBroadcastInternal(killApp);
15462            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15463            for (int i = 0; i < childCount; i++) {
15464                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15465                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15466            }
15467        }
15468
15469        void sendSystemPackageUpdatedBroadcasts() {
15470            if (isRemovedPackageSystemUpdate) {
15471                sendSystemPackageUpdatedBroadcastsInternal();
15472                final int childCount = (removedChildPackages != null)
15473                        ? removedChildPackages.size() : 0;
15474                for (int i = 0; i < childCount; i++) {
15475                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15476                    if (childInfo.isRemovedPackageSystemUpdate) {
15477                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15478                    }
15479                }
15480            }
15481        }
15482
15483        void sendSystemPackageAppearedBroadcasts() {
15484            final int packageCount = (appearedChildPackages != null)
15485                    ? appearedChildPackages.size() : 0;
15486            for (int i = 0; i < packageCount; i++) {
15487                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15488                for (int userId : installedInfo.newUsers) {
15489                    sendPackageAddedForUser(installedInfo.name, true,
15490                            UserHandle.getAppId(installedInfo.uid), userId);
15491                }
15492            }
15493        }
15494
15495        private void sendSystemPackageUpdatedBroadcastsInternal() {
15496            Bundle extras = new Bundle(2);
15497            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15498            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15499            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15500                    extras, 0, null, null, null);
15501            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15502                    extras, 0, null, null, null);
15503            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15504                    null, 0, removedPackage, null, null);
15505        }
15506
15507        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15508            Bundle extras = new Bundle(2);
15509            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15510            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15511            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15512            if (isUpdate || isRemovedPackageSystemUpdate) {
15513                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15514            }
15515            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15516            if (removedPackage != null) {
15517                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15518                        extras, 0, null, null, removedUsers);
15519                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15520                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15521                            removedPackage, extras, 0, null, null, removedUsers);
15522                }
15523            }
15524            if (removedAppId >= 0) {
15525                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15526                        removedUsers);
15527            }
15528        }
15529    }
15530
15531    /*
15532     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15533     * flag is not set, the data directory is removed as well.
15534     * make sure this flag is set for partially installed apps. If not its meaningless to
15535     * delete a partially installed application.
15536     */
15537    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15538            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15539        String packageName = ps.name;
15540        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15541        // Retrieve object to delete permissions for shared user later on
15542        final PackageParser.Package deletedPkg;
15543        final PackageSetting deletedPs;
15544        // reader
15545        synchronized (mPackages) {
15546            deletedPkg = mPackages.get(packageName);
15547            deletedPs = mSettings.mPackages.get(packageName);
15548            if (outInfo != null) {
15549                outInfo.removedPackage = packageName;
15550                outInfo.removedUsers = deletedPs != null
15551                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15552                        : null;
15553            }
15554        }
15555
15556        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15557
15558        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15559            final PackageParser.Package resolvedPkg;
15560            if (deletedPkg != null) {
15561                resolvedPkg = deletedPkg;
15562            } else {
15563                // We don't have a parsed package when it lives on an ejected
15564                // adopted storage device, so fake something together
15565                resolvedPkg = new PackageParser.Package(ps.name);
15566                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15567            }
15568            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15569                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15570            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15571            if (outInfo != null) {
15572                outInfo.dataRemoved = true;
15573            }
15574            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15575        }
15576
15577        // writer
15578        synchronized (mPackages) {
15579            if (deletedPs != null) {
15580                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15581                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15582                    clearDefaultBrowserIfNeeded(packageName);
15583                    if (outInfo != null) {
15584                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15585                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15586                    }
15587                    updatePermissionsLPw(deletedPs.name, null, 0);
15588                    if (deletedPs.sharedUser != null) {
15589                        // Remove permissions associated with package. Since runtime
15590                        // permissions are per user we have to kill the removed package
15591                        // or packages running under the shared user of the removed
15592                        // package if revoking the permissions requested only by the removed
15593                        // package is successful and this causes a change in gids.
15594                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15595                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15596                                    userId);
15597                            if (userIdToKill == UserHandle.USER_ALL
15598                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15599                                // If gids changed for this user, kill all affected packages.
15600                                mHandler.post(new Runnable() {
15601                                    @Override
15602                                    public void run() {
15603                                        // This has to happen with no lock held.
15604                                        killApplication(deletedPs.name, deletedPs.appId,
15605                                                KILL_APP_REASON_GIDS_CHANGED);
15606                                    }
15607                                });
15608                                break;
15609                            }
15610                        }
15611                    }
15612                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15613                }
15614                // make sure to preserve per-user disabled state if this removal was just
15615                // a downgrade of a system app to the factory package
15616                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15617                    if (DEBUG_REMOVE) {
15618                        Slog.d(TAG, "Propagating install state across downgrade");
15619                    }
15620                    for (int userId : allUserHandles) {
15621                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15622                        if (DEBUG_REMOVE) {
15623                            Slog.d(TAG, "    user " + userId + " => " + installed);
15624                        }
15625                        ps.setInstalled(installed, userId);
15626                    }
15627                }
15628            }
15629            // can downgrade to reader
15630            if (writeSettings) {
15631                // Save settings now
15632                mSettings.writeLPr();
15633            }
15634        }
15635        if (outInfo != null) {
15636            // A user ID was deleted here. Go through all users and remove it
15637            // from KeyStore.
15638            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15639        }
15640    }
15641
15642    static boolean locationIsPrivileged(File path) {
15643        try {
15644            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15645                    .getCanonicalPath();
15646            return path.getCanonicalPath().startsWith(privilegedAppDir);
15647        } catch (IOException e) {
15648            Slog.e(TAG, "Unable to access code path " + path);
15649        }
15650        return false;
15651    }
15652
15653    /*
15654     * Tries to delete system package.
15655     */
15656    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15657            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15658            boolean writeSettings) {
15659        if (deletedPs.parentPackageName != null) {
15660            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15661            return false;
15662        }
15663
15664        final boolean applyUserRestrictions
15665                = (allUserHandles != null) && (outInfo.origUsers != null);
15666        final PackageSetting disabledPs;
15667        // Confirm if the system package has been updated
15668        // An updated system app can be deleted. This will also have to restore
15669        // the system pkg from system partition
15670        // reader
15671        synchronized (mPackages) {
15672            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15673        }
15674
15675        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15676                + " disabledPs=" + disabledPs);
15677
15678        if (disabledPs == null) {
15679            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15680            return false;
15681        } else if (DEBUG_REMOVE) {
15682            Slog.d(TAG, "Deleting system pkg from data partition");
15683        }
15684
15685        if (DEBUG_REMOVE) {
15686            if (applyUserRestrictions) {
15687                Slog.d(TAG, "Remembering install states:");
15688                for (int userId : allUserHandles) {
15689                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15690                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15691                }
15692            }
15693        }
15694
15695        // Delete the updated package
15696        outInfo.isRemovedPackageSystemUpdate = true;
15697        if (outInfo.removedChildPackages != null) {
15698            final int childCount = (deletedPs.childPackageNames != null)
15699                    ? deletedPs.childPackageNames.size() : 0;
15700            for (int i = 0; i < childCount; i++) {
15701                String childPackageName = deletedPs.childPackageNames.get(i);
15702                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15703                        .contains(childPackageName)) {
15704                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15705                            childPackageName);
15706                    if (childInfo != null) {
15707                        childInfo.isRemovedPackageSystemUpdate = true;
15708                    }
15709                }
15710            }
15711        }
15712
15713        if (disabledPs.versionCode < deletedPs.versionCode) {
15714            // Delete data for downgrades
15715            flags &= ~PackageManager.DELETE_KEEP_DATA;
15716        } else {
15717            // Preserve data by setting flag
15718            flags |= PackageManager.DELETE_KEEP_DATA;
15719        }
15720
15721        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15722                outInfo, writeSettings, disabledPs.pkg);
15723        if (!ret) {
15724            return false;
15725        }
15726
15727        // writer
15728        synchronized (mPackages) {
15729            // Reinstate the old system package
15730            enableSystemPackageLPw(disabledPs.pkg);
15731            // Remove any native libraries from the upgraded package.
15732            removeNativeBinariesLI(deletedPs);
15733        }
15734
15735        // Install the system package
15736        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15737        int parseFlags = mDefParseFlags
15738                | PackageParser.PARSE_MUST_BE_APK
15739                | PackageParser.PARSE_IS_SYSTEM
15740                | PackageParser.PARSE_IS_SYSTEM_DIR;
15741        if (locationIsPrivileged(disabledPs.codePath)) {
15742            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15743        }
15744
15745        final PackageParser.Package newPkg;
15746        try {
15747            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15748        } catch (PackageManagerException e) {
15749            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15750                    + e.getMessage());
15751            return false;
15752        }
15753
15754        prepareAppDataAfterInstallLIF(newPkg);
15755
15756        // writer
15757        synchronized (mPackages) {
15758            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15759
15760            // Propagate the permissions state as we do not want to drop on the floor
15761            // runtime permissions. The update permissions method below will take
15762            // care of removing obsolete permissions and grant install permissions.
15763            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15764            updatePermissionsLPw(newPkg.packageName, newPkg,
15765                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15766
15767            if (applyUserRestrictions) {
15768                if (DEBUG_REMOVE) {
15769                    Slog.d(TAG, "Propagating install state across reinstall");
15770                }
15771                for (int userId : allUserHandles) {
15772                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15773                    if (DEBUG_REMOVE) {
15774                        Slog.d(TAG, "    user " + userId + " => " + installed);
15775                    }
15776                    ps.setInstalled(installed, userId);
15777
15778                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15779                }
15780                // Regardless of writeSettings we need to ensure that this restriction
15781                // state propagation is persisted
15782                mSettings.writeAllUsersPackageRestrictionsLPr();
15783            }
15784            // can downgrade to reader here
15785            if (writeSettings) {
15786                mSettings.writeLPr();
15787            }
15788        }
15789        return true;
15790    }
15791
15792    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15793            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15794            PackageRemovedInfo outInfo, boolean writeSettings,
15795            PackageParser.Package replacingPackage) {
15796        synchronized (mPackages) {
15797            if (outInfo != null) {
15798                outInfo.uid = ps.appId;
15799            }
15800
15801            if (outInfo != null && outInfo.removedChildPackages != null) {
15802                final int childCount = (ps.childPackageNames != null)
15803                        ? ps.childPackageNames.size() : 0;
15804                for (int i = 0; i < childCount; i++) {
15805                    String childPackageName = ps.childPackageNames.get(i);
15806                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15807                    if (childPs == null) {
15808                        return false;
15809                    }
15810                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15811                            childPackageName);
15812                    if (childInfo != null) {
15813                        childInfo.uid = childPs.appId;
15814                    }
15815                }
15816            }
15817        }
15818
15819        // Delete package data from internal structures and also remove data if flag is set
15820        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15821
15822        // Delete the child packages data
15823        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15824        for (int i = 0; i < childCount; i++) {
15825            PackageSetting childPs;
15826            synchronized (mPackages) {
15827                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15828            }
15829            if (childPs != null) {
15830                PackageRemovedInfo childOutInfo = (outInfo != null
15831                        && outInfo.removedChildPackages != null)
15832                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15833                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15834                        && (replacingPackage != null
15835                        && !replacingPackage.hasChildPackage(childPs.name))
15836                        ? flags & ~DELETE_KEEP_DATA : flags;
15837                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15838                        deleteFlags, writeSettings);
15839            }
15840        }
15841
15842        // Delete application code and resources only for parent packages
15843        if (ps.parentPackageName == null) {
15844            if (deleteCodeAndResources && (outInfo != null)) {
15845                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15846                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15847                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15848            }
15849        }
15850
15851        return true;
15852    }
15853
15854    @Override
15855    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15856            int userId) {
15857        mContext.enforceCallingOrSelfPermission(
15858                android.Manifest.permission.DELETE_PACKAGES, null);
15859        synchronized (mPackages) {
15860            PackageSetting ps = mSettings.mPackages.get(packageName);
15861            if (ps == null) {
15862                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15863                return false;
15864            }
15865            if (!ps.getInstalled(userId)) {
15866                // Can't block uninstall for an app that is not installed or enabled.
15867                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15868                return false;
15869            }
15870            ps.setBlockUninstall(blockUninstall, userId);
15871            mSettings.writePackageRestrictionsLPr(userId);
15872        }
15873        return true;
15874    }
15875
15876    @Override
15877    public boolean getBlockUninstallForUser(String packageName, int userId) {
15878        synchronized (mPackages) {
15879            PackageSetting ps = mSettings.mPackages.get(packageName);
15880            if (ps == null) {
15881                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15882                return false;
15883            }
15884            return ps.getBlockUninstall(userId);
15885        }
15886    }
15887
15888    @Override
15889    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15890        int callingUid = Binder.getCallingUid();
15891        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15892            throw new SecurityException(
15893                    "setRequiredForSystemUser can only be run by the system or root");
15894        }
15895        synchronized (mPackages) {
15896            PackageSetting ps = mSettings.mPackages.get(packageName);
15897            if (ps == null) {
15898                Log.w(TAG, "Package doesn't exist: " + packageName);
15899                return false;
15900            }
15901            if (systemUserApp) {
15902                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15903            } else {
15904                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15905            }
15906            mSettings.writeLPr();
15907        }
15908        return true;
15909    }
15910
15911    /*
15912     * This method handles package deletion in general
15913     */
15914    private boolean deletePackageLIF(String packageName, UserHandle user,
15915            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15916            PackageRemovedInfo outInfo, boolean writeSettings,
15917            PackageParser.Package replacingPackage) {
15918        if (packageName == null) {
15919            Slog.w(TAG, "Attempt to delete null packageName.");
15920            return false;
15921        }
15922
15923        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15924
15925        PackageSetting ps;
15926
15927        synchronized (mPackages) {
15928            ps = mSettings.mPackages.get(packageName);
15929            if (ps == null) {
15930                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15931                return false;
15932            }
15933
15934            if (ps.parentPackageName != null && (!isSystemApp(ps)
15935                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15936                if (DEBUG_REMOVE) {
15937                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15938                            + ((user == null) ? UserHandle.USER_ALL : user));
15939                }
15940                final int removedUserId = (user != null) ? user.getIdentifier()
15941                        : UserHandle.USER_ALL;
15942                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15943                    return false;
15944                }
15945                markPackageUninstalledForUserLPw(ps, user);
15946                scheduleWritePackageRestrictionsLocked(user);
15947                return true;
15948            }
15949        }
15950
15951        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15952                && user.getIdentifier() != UserHandle.USER_ALL)) {
15953            // The caller is asking that the package only be deleted for a single
15954            // user.  To do this, we just mark its uninstalled state and delete
15955            // its data. If this is a system app, we only allow this to happen if
15956            // they have set the special DELETE_SYSTEM_APP which requests different
15957            // semantics than normal for uninstalling system apps.
15958            markPackageUninstalledForUserLPw(ps, user);
15959
15960            if (!isSystemApp(ps)) {
15961                // Do not uninstall the APK if an app should be cached
15962                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15963                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15964                    // Other user still have this package installed, so all
15965                    // we need to do is clear this user's data and save that
15966                    // it is uninstalled.
15967                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15968                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15969                        return false;
15970                    }
15971                    scheduleWritePackageRestrictionsLocked(user);
15972                    return true;
15973                } else {
15974                    // We need to set it back to 'installed' so the uninstall
15975                    // broadcasts will be sent correctly.
15976                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15977                    ps.setInstalled(true, user.getIdentifier());
15978                }
15979            } else {
15980                // This is a system app, so we assume that the
15981                // other users still have this package installed, so all
15982                // we need to do is clear this user's data and save that
15983                // it is uninstalled.
15984                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15985                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15986                    return false;
15987                }
15988                scheduleWritePackageRestrictionsLocked(user);
15989                return true;
15990            }
15991        }
15992
15993        // If we are deleting a composite package for all users, keep track
15994        // of result for each child.
15995        if (ps.childPackageNames != null && outInfo != null) {
15996            synchronized (mPackages) {
15997                final int childCount = ps.childPackageNames.size();
15998                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15999                for (int i = 0; i < childCount; i++) {
16000                    String childPackageName = ps.childPackageNames.get(i);
16001                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16002                    childInfo.removedPackage = childPackageName;
16003                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16004                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16005                    if (childPs != null) {
16006                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16007                    }
16008                }
16009            }
16010        }
16011
16012        boolean ret = false;
16013        if (isSystemApp(ps)) {
16014            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16015            // When an updated system application is deleted we delete the existing resources
16016            // as well and fall back to existing code in system partition
16017            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16018        } else {
16019            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16020            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16021                    outInfo, writeSettings, replacingPackage);
16022        }
16023
16024        // Take a note whether we deleted the package for all users
16025        if (outInfo != null) {
16026            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16027            if (outInfo.removedChildPackages != null) {
16028                synchronized (mPackages) {
16029                    final int childCount = outInfo.removedChildPackages.size();
16030                    for (int i = 0; i < childCount; i++) {
16031                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16032                        if (childInfo != null) {
16033                            childInfo.removedForAllUsers = mPackages.get(
16034                                    childInfo.removedPackage) == null;
16035                        }
16036                    }
16037                }
16038            }
16039            // If we uninstalled an update to a system app there may be some
16040            // child packages that appeared as they are declared in the system
16041            // app but were not declared in the update.
16042            if (isSystemApp(ps)) {
16043                synchronized (mPackages) {
16044                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16045                    final int childCount = (updatedPs.childPackageNames != null)
16046                            ? updatedPs.childPackageNames.size() : 0;
16047                    for (int i = 0; i < childCount; i++) {
16048                        String childPackageName = updatedPs.childPackageNames.get(i);
16049                        if (outInfo.removedChildPackages == null
16050                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16051                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16052                            if (childPs == null) {
16053                                continue;
16054                            }
16055                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16056                            installRes.name = childPackageName;
16057                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16058                            installRes.pkg = mPackages.get(childPackageName);
16059                            installRes.uid = childPs.pkg.applicationInfo.uid;
16060                            if (outInfo.appearedChildPackages == null) {
16061                                outInfo.appearedChildPackages = new ArrayMap<>();
16062                            }
16063                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16064                        }
16065                    }
16066                }
16067            }
16068        }
16069
16070        return ret;
16071    }
16072
16073    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16074        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16075                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16076        for (int nextUserId : userIds) {
16077            if (DEBUG_REMOVE) {
16078                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16079            }
16080            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16081                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16082                    false /*hidden*/, false /*suspended*/, null, null, null,
16083                    false /*blockUninstall*/,
16084                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16085        }
16086    }
16087
16088    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16089            PackageRemovedInfo outInfo) {
16090        final PackageParser.Package pkg;
16091        synchronized (mPackages) {
16092            pkg = mPackages.get(ps.name);
16093        }
16094
16095        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16096                : new int[] {userId};
16097        for (int nextUserId : userIds) {
16098            if (DEBUG_REMOVE) {
16099                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16100                        + nextUserId);
16101            }
16102
16103            destroyAppDataLIF(pkg, userId,
16104                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16105            destroyAppProfilesLIF(pkg, userId);
16106            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16107            schedulePackageCleaning(ps.name, nextUserId, false);
16108            synchronized (mPackages) {
16109                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16110                    scheduleWritePackageRestrictionsLocked(nextUserId);
16111                }
16112                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16113            }
16114        }
16115
16116        if (outInfo != null) {
16117            outInfo.removedPackage = ps.name;
16118            outInfo.removedAppId = ps.appId;
16119            outInfo.removedUsers = userIds;
16120        }
16121
16122        return true;
16123    }
16124
16125    private final class ClearStorageConnection implements ServiceConnection {
16126        IMediaContainerService mContainerService;
16127
16128        @Override
16129        public void onServiceConnected(ComponentName name, IBinder service) {
16130            synchronized (this) {
16131                mContainerService = IMediaContainerService.Stub.asInterface(service);
16132                notifyAll();
16133            }
16134        }
16135
16136        @Override
16137        public void onServiceDisconnected(ComponentName name) {
16138        }
16139    }
16140
16141    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16142        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16143
16144        final boolean mounted;
16145        if (Environment.isExternalStorageEmulated()) {
16146            mounted = true;
16147        } else {
16148            final String status = Environment.getExternalStorageState();
16149
16150            mounted = status.equals(Environment.MEDIA_MOUNTED)
16151                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16152        }
16153
16154        if (!mounted) {
16155            return;
16156        }
16157
16158        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16159        int[] users;
16160        if (userId == UserHandle.USER_ALL) {
16161            users = sUserManager.getUserIds();
16162        } else {
16163            users = new int[] { userId };
16164        }
16165        final ClearStorageConnection conn = new ClearStorageConnection();
16166        if (mContext.bindServiceAsUser(
16167                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16168            try {
16169                for (int curUser : users) {
16170                    long timeout = SystemClock.uptimeMillis() + 5000;
16171                    synchronized (conn) {
16172                        long now = SystemClock.uptimeMillis();
16173                        while (conn.mContainerService == null && now < timeout) {
16174                            try {
16175                                conn.wait(timeout - now);
16176                            } catch (InterruptedException e) {
16177                            }
16178                        }
16179                    }
16180                    if (conn.mContainerService == null) {
16181                        return;
16182                    }
16183
16184                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16185                    clearDirectory(conn.mContainerService,
16186                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16187                    if (allData) {
16188                        clearDirectory(conn.mContainerService,
16189                                userEnv.buildExternalStorageAppDataDirs(packageName));
16190                        clearDirectory(conn.mContainerService,
16191                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16192                    }
16193                }
16194            } finally {
16195                mContext.unbindService(conn);
16196            }
16197        }
16198    }
16199
16200    @Override
16201    public void clearApplicationProfileData(String packageName) {
16202        enforceSystemOrRoot("Only the system can clear all profile data");
16203
16204        final PackageParser.Package pkg;
16205        synchronized (mPackages) {
16206            pkg = mPackages.get(packageName);
16207        }
16208
16209        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16210            synchronized (mInstallLock) {
16211                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16212            }
16213        }
16214    }
16215
16216    @Override
16217    public void clearApplicationUserData(final String packageName,
16218            final IPackageDataObserver observer, final int userId) {
16219        mContext.enforceCallingOrSelfPermission(
16220                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16221
16222        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16223                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16224
16225        final DevicePolicyManagerInternal dpmi = LocalServices
16226                .getService(DevicePolicyManagerInternal.class);
16227        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16228            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16229        }
16230        // Queue up an async operation since the package deletion may take a little while.
16231        mHandler.post(new Runnable() {
16232            public void run() {
16233                mHandler.removeCallbacks(this);
16234                final boolean succeeded;
16235                try (PackageFreezer freezer = freezePackage(packageName,
16236                        "clearApplicationUserData")) {
16237                    synchronized (mInstallLock) {
16238                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16239                    }
16240                    clearExternalStorageDataSync(packageName, userId, true);
16241                }
16242                if (succeeded) {
16243                    // invoke DeviceStorageMonitor's update method to clear any notifications
16244                    DeviceStorageMonitorInternal dsm = LocalServices
16245                            .getService(DeviceStorageMonitorInternal.class);
16246                    if (dsm != null) {
16247                        dsm.checkMemory();
16248                    }
16249                }
16250                if(observer != null) {
16251                    try {
16252                        observer.onRemoveCompleted(packageName, succeeded);
16253                    } catch (RemoteException e) {
16254                        Log.i(TAG, "Observer no longer exists.");
16255                    }
16256                } //end if observer
16257            } //end run
16258        });
16259    }
16260
16261    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16262        if (packageName == null) {
16263            Slog.w(TAG, "Attempt to delete null packageName.");
16264            return false;
16265        }
16266
16267        // Try finding details about the requested package
16268        PackageParser.Package pkg;
16269        synchronized (mPackages) {
16270            pkg = mPackages.get(packageName);
16271            if (pkg == null) {
16272                final PackageSetting ps = mSettings.mPackages.get(packageName);
16273                if (ps != null) {
16274                    pkg = ps.pkg;
16275                }
16276            }
16277
16278            if (pkg == null) {
16279                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16280                return false;
16281            }
16282
16283            PackageSetting ps = (PackageSetting) pkg.mExtras;
16284            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16285        }
16286
16287        clearAppDataLIF(pkg, userId,
16288                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16289
16290        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16291        removeKeystoreDataIfNeeded(userId, appId);
16292
16293        UserManagerInternal umInternal = getUserManagerInternal();
16294        final int flags;
16295        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16296            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16297        } else if (umInternal.isUserRunning(userId)) {
16298            flags = StorageManager.FLAG_STORAGE_DE;
16299        } else {
16300            flags = 0;
16301        }
16302        prepareAppDataContentsLIF(pkg, userId, flags);
16303
16304        return true;
16305    }
16306
16307    /**
16308     * Reverts user permission state changes (permissions and flags) in
16309     * all packages for a given user.
16310     *
16311     * @param userId The device user for which to do a reset.
16312     */
16313    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16314        final int packageCount = mPackages.size();
16315        for (int i = 0; i < packageCount; i++) {
16316            PackageParser.Package pkg = mPackages.valueAt(i);
16317            PackageSetting ps = (PackageSetting) pkg.mExtras;
16318            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16319        }
16320    }
16321
16322    private void resetNetworkPolicies(int userId) {
16323        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16324    }
16325
16326    /**
16327     * Reverts user permission state changes (permissions and flags).
16328     *
16329     * @param ps The package for which to reset.
16330     * @param userId The device user for which to do a reset.
16331     */
16332    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16333            final PackageSetting ps, final int userId) {
16334        if (ps.pkg == null) {
16335            return;
16336        }
16337
16338        // These are flags that can change base on user actions.
16339        final int userSettableMask = FLAG_PERMISSION_USER_SET
16340                | FLAG_PERMISSION_USER_FIXED
16341                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16342                | FLAG_PERMISSION_REVIEW_REQUIRED;
16343
16344        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16345                | FLAG_PERMISSION_POLICY_FIXED;
16346
16347        boolean writeInstallPermissions = false;
16348        boolean writeRuntimePermissions = false;
16349
16350        final int permissionCount = ps.pkg.requestedPermissions.size();
16351        for (int i = 0; i < permissionCount; i++) {
16352            String permission = ps.pkg.requestedPermissions.get(i);
16353
16354            BasePermission bp = mSettings.mPermissions.get(permission);
16355            if (bp == null) {
16356                continue;
16357            }
16358
16359            // If shared user we just reset the state to which only this app contributed.
16360            if (ps.sharedUser != null) {
16361                boolean used = false;
16362                final int packageCount = ps.sharedUser.packages.size();
16363                for (int j = 0; j < packageCount; j++) {
16364                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16365                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16366                            && pkg.pkg.requestedPermissions.contains(permission)) {
16367                        used = true;
16368                        break;
16369                    }
16370                }
16371                if (used) {
16372                    continue;
16373                }
16374            }
16375
16376            PermissionsState permissionsState = ps.getPermissionsState();
16377
16378            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16379
16380            // Always clear the user settable flags.
16381            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16382                    bp.name) != null;
16383            // If permission review is enabled and this is a legacy app, mark the
16384            // permission as requiring a review as this is the initial state.
16385            int flags = 0;
16386            if (Build.PERMISSIONS_REVIEW_REQUIRED
16387                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16388                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16389            }
16390            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16391                if (hasInstallState) {
16392                    writeInstallPermissions = true;
16393                } else {
16394                    writeRuntimePermissions = true;
16395                }
16396            }
16397
16398            // Below is only runtime permission handling.
16399            if (!bp.isRuntime()) {
16400                continue;
16401            }
16402
16403            // Never clobber system or policy.
16404            if ((oldFlags & policyOrSystemFlags) != 0) {
16405                continue;
16406            }
16407
16408            // If this permission was granted by default, make sure it is.
16409            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16410                if (permissionsState.grantRuntimePermission(bp, userId)
16411                        != PERMISSION_OPERATION_FAILURE) {
16412                    writeRuntimePermissions = true;
16413                }
16414            // If permission review is enabled the permissions for a legacy apps
16415            // are represented as constantly granted runtime ones, so don't revoke.
16416            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16417                // Otherwise, reset the permission.
16418                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16419                switch (revokeResult) {
16420                    case PERMISSION_OPERATION_SUCCESS:
16421                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16422                        writeRuntimePermissions = true;
16423                        final int appId = ps.appId;
16424                        mHandler.post(new Runnable() {
16425                            @Override
16426                            public void run() {
16427                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16428                            }
16429                        });
16430                    } break;
16431                }
16432            }
16433        }
16434
16435        // Synchronously write as we are taking permissions away.
16436        if (writeRuntimePermissions) {
16437            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16438        }
16439
16440        // Synchronously write as we are taking permissions away.
16441        if (writeInstallPermissions) {
16442            mSettings.writeLPr();
16443        }
16444    }
16445
16446    /**
16447     * Remove entries from the keystore daemon. Will only remove it if the
16448     * {@code appId} is valid.
16449     */
16450    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16451        if (appId < 0) {
16452            return;
16453        }
16454
16455        final KeyStore keyStore = KeyStore.getInstance();
16456        if (keyStore != null) {
16457            if (userId == UserHandle.USER_ALL) {
16458                for (final int individual : sUserManager.getUserIds()) {
16459                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16460                }
16461            } else {
16462                keyStore.clearUid(UserHandle.getUid(userId, appId));
16463            }
16464        } else {
16465            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16466        }
16467    }
16468
16469    @Override
16470    public void deleteApplicationCacheFiles(final String packageName,
16471            final IPackageDataObserver observer) {
16472        final int userId = UserHandle.getCallingUserId();
16473        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16474    }
16475
16476    @Override
16477    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16478            final IPackageDataObserver observer) {
16479        mContext.enforceCallingOrSelfPermission(
16480                android.Manifest.permission.DELETE_CACHE_FILES, null);
16481        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16482                /* requireFullPermission= */ true, /* checkShell= */ false,
16483                "delete application cache files");
16484
16485        final PackageParser.Package pkg;
16486        synchronized (mPackages) {
16487            pkg = mPackages.get(packageName);
16488        }
16489
16490        // Queue up an async operation since the package deletion may take a little while.
16491        mHandler.post(new Runnable() {
16492            public void run() {
16493                synchronized (mInstallLock) {
16494                    final int flags = StorageManager.FLAG_STORAGE_DE
16495                            | StorageManager.FLAG_STORAGE_CE;
16496                    // We're only clearing cache files, so we don't care if the
16497                    // app is unfrozen and still able to run
16498                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16499                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16500                }
16501                clearExternalStorageDataSync(packageName, userId, false);
16502                if (observer != null) {
16503                    try {
16504                        observer.onRemoveCompleted(packageName, true);
16505                    } catch (RemoteException e) {
16506                        Log.i(TAG, "Observer no longer exists.");
16507                    }
16508                }
16509            }
16510        });
16511    }
16512
16513    @Override
16514    public void getPackageSizeInfo(final String packageName, int userHandle,
16515            final IPackageStatsObserver observer) {
16516        mContext.enforceCallingOrSelfPermission(
16517                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16518        if (packageName == null) {
16519            throw new IllegalArgumentException("Attempt to get size of null packageName");
16520        }
16521
16522        PackageStats stats = new PackageStats(packageName, userHandle);
16523
16524        /*
16525         * Queue up an async operation since the package measurement may take a
16526         * little while.
16527         */
16528        Message msg = mHandler.obtainMessage(INIT_COPY);
16529        msg.obj = new MeasureParams(stats, observer);
16530        mHandler.sendMessage(msg);
16531    }
16532
16533    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16534        final PackageSetting ps;
16535        synchronized (mPackages) {
16536            ps = mSettings.mPackages.get(packageName);
16537            if (ps == null) {
16538                Slog.w(TAG, "Failed to find settings for " + packageName);
16539                return false;
16540            }
16541        }
16542        try {
16543            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16544                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16545                    ps.getCeDataInode(userId), ps.codePathString, stats);
16546        } catch (InstallerException e) {
16547            Slog.w(TAG, String.valueOf(e));
16548            return false;
16549        }
16550
16551        // For now, ignore code size of packages on system partition
16552        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16553            stats.codeSize = 0;
16554        }
16555
16556        return true;
16557    }
16558
16559    private int getUidTargetSdkVersionLockedLPr(int uid) {
16560        Object obj = mSettings.getUserIdLPr(uid);
16561        if (obj instanceof SharedUserSetting) {
16562            final SharedUserSetting sus = (SharedUserSetting) obj;
16563            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16564            final Iterator<PackageSetting> it = sus.packages.iterator();
16565            while (it.hasNext()) {
16566                final PackageSetting ps = it.next();
16567                if (ps.pkg != null) {
16568                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16569                    if (v < vers) vers = v;
16570                }
16571            }
16572            return vers;
16573        } else if (obj instanceof PackageSetting) {
16574            final PackageSetting ps = (PackageSetting) obj;
16575            if (ps.pkg != null) {
16576                return ps.pkg.applicationInfo.targetSdkVersion;
16577            }
16578        }
16579        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16580    }
16581
16582    @Override
16583    public void addPreferredActivity(IntentFilter filter, int match,
16584            ComponentName[] set, ComponentName activity, int userId) {
16585        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16586                "Adding preferred");
16587    }
16588
16589    private void addPreferredActivityInternal(IntentFilter filter, int match,
16590            ComponentName[] set, ComponentName activity, boolean always, int userId,
16591            String opname) {
16592        // writer
16593        int callingUid = Binder.getCallingUid();
16594        enforceCrossUserPermission(callingUid, userId,
16595                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16596        if (filter.countActions() == 0) {
16597            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16598            return;
16599        }
16600        synchronized (mPackages) {
16601            if (mContext.checkCallingOrSelfPermission(
16602                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16603                    != PackageManager.PERMISSION_GRANTED) {
16604                if (getUidTargetSdkVersionLockedLPr(callingUid)
16605                        < Build.VERSION_CODES.FROYO) {
16606                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16607                            + callingUid);
16608                    return;
16609                }
16610                mContext.enforceCallingOrSelfPermission(
16611                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16612            }
16613
16614            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16615            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16616                    + userId + ":");
16617            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16618            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16619            scheduleWritePackageRestrictionsLocked(userId);
16620        }
16621    }
16622
16623    @Override
16624    public void replacePreferredActivity(IntentFilter filter, int match,
16625            ComponentName[] set, ComponentName activity, int userId) {
16626        if (filter.countActions() != 1) {
16627            throw new IllegalArgumentException(
16628                    "replacePreferredActivity expects filter to have only 1 action.");
16629        }
16630        if (filter.countDataAuthorities() != 0
16631                || filter.countDataPaths() != 0
16632                || filter.countDataSchemes() > 1
16633                || filter.countDataTypes() != 0) {
16634            throw new IllegalArgumentException(
16635                    "replacePreferredActivity expects filter to have no data authorities, " +
16636                    "paths, or types; and at most one scheme.");
16637        }
16638
16639        final int callingUid = Binder.getCallingUid();
16640        enforceCrossUserPermission(callingUid, userId,
16641                true /* requireFullPermission */, false /* checkShell */,
16642                "replace preferred activity");
16643        synchronized (mPackages) {
16644            if (mContext.checkCallingOrSelfPermission(
16645                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16646                    != PackageManager.PERMISSION_GRANTED) {
16647                if (getUidTargetSdkVersionLockedLPr(callingUid)
16648                        < Build.VERSION_CODES.FROYO) {
16649                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16650                            + Binder.getCallingUid());
16651                    return;
16652                }
16653                mContext.enforceCallingOrSelfPermission(
16654                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16655            }
16656
16657            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16658            if (pir != null) {
16659                // Get all of the existing entries that exactly match this filter.
16660                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16661                if (existing != null && existing.size() == 1) {
16662                    PreferredActivity cur = existing.get(0);
16663                    if (DEBUG_PREFERRED) {
16664                        Slog.i(TAG, "Checking replace of preferred:");
16665                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16666                        if (!cur.mPref.mAlways) {
16667                            Slog.i(TAG, "  -- CUR; not mAlways!");
16668                        } else {
16669                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16670                            Slog.i(TAG, "  -- CUR: mSet="
16671                                    + Arrays.toString(cur.mPref.mSetComponents));
16672                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16673                            Slog.i(TAG, "  -- NEW: mMatch="
16674                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16675                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16676                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16677                        }
16678                    }
16679                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16680                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16681                            && cur.mPref.sameSet(set)) {
16682                        // Setting the preferred activity to what it happens to be already
16683                        if (DEBUG_PREFERRED) {
16684                            Slog.i(TAG, "Replacing with same preferred activity "
16685                                    + cur.mPref.mShortComponent + " for user "
16686                                    + userId + ":");
16687                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16688                        }
16689                        return;
16690                    }
16691                }
16692
16693                if (existing != null) {
16694                    if (DEBUG_PREFERRED) {
16695                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16696                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16697                    }
16698                    for (int i = 0; i < existing.size(); i++) {
16699                        PreferredActivity pa = existing.get(i);
16700                        if (DEBUG_PREFERRED) {
16701                            Slog.i(TAG, "Removing existing preferred activity "
16702                                    + pa.mPref.mComponent + ":");
16703                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16704                        }
16705                        pir.removeFilter(pa);
16706                    }
16707                }
16708            }
16709            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16710                    "Replacing preferred");
16711        }
16712    }
16713
16714    @Override
16715    public void clearPackagePreferredActivities(String packageName) {
16716        final int uid = Binder.getCallingUid();
16717        // writer
16718        synchronized (mPackages) {
16719            PackageParser.Package pkg = mPackages.get(packageName);
16720            if (pkg == null || pkg.applicationInfo.uid != uid) {
16721                if (mContext.checkCallingOrSelfPermission(
16722                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16723                        != PackageManager.PERMISSION_GRANTED) {
16724                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16725                            < Build.VERSION_CODES.FROYO) {
16726                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16727                                + Binder.getCallingUid());
16728                        return;
16729                    }
16730                    mContext.enforceCallingOrSelfPermission(
16731                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16732                }
16733            }
16734
16735            int user = UserHandle.getCallingUserId();
16736            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16737                scheduleWritePackageRestrictionsLocked(user);
16738            }
16739        }
16740    }
16741
16742    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16743    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16744        ArrayList<PreferredActivity> removed = null;
16745        boolean changed = false;
16746        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16747            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16748            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16749            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16750                continue;
16751            }
16752            Iterator<PreferredActivity> it = pir.filterIterator();
16753            while (it.hasNext()) {
16754                PreferredActivity pa = it.next();
16755                // Mark entry for removal only if it matches the package name
16756                // and the entry is of type "always".
16757                if (packageName == null ||
16758                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16759                                && pa.mPref.mAlways)) {
16760                    if (removed == null) {
16761                        removed = new ArrayList<PreferredActivity>();
16762                    }
16763                    removed.add(pa);
16764                }
16765            }
16766            if (removed != null) {
16767                for (int j=0; j<removed.size(); j++) {
16768                    PreferredActivity pa = removed.get(j);
16769                    pir.removeFilter(pa);
16770                }
16771                changed = true;
16772            }
16773        }
16774        return changed;
16775    }
16776
16777    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16778    private void clearIntentFilterVerificationsLPw(int userId) {
16779        final int packageCount = mPackages.size();
16780        for (int i = 0; i < packageCount; i++) {
16781            PackageParser.Package pkg = mPackages.valueAt(i);
16782            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16783        }
16784    }
16785
16786    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16787    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16788        if (userId == UserHandle.USER_ALL) {
16789            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16790                    sUserManager.getUserIds())) {
16791                for (int oneUserId : sUserManager.getUserIds()) {
16792                    scheduleWritePackageRestrictionsLocked(oneUserId);
16793                }
16794            }
16795        } else {
16796            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16797                scheduleWritePackageRestrictionsLocked(userId);
16798            }
16799        }
16800    }
16801
16802    void clearDefaultBrowserIfNeeded(String packageName) {
16803        for (int oneUserId : sUserManager.getUserIds()) {
16804            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16805            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16806            if (packageName.equals(defaultBrowserPackageName)) {
16807                setDefaultBrowserPackageName(null, oneUserId);
16808            }
16809        }
16810    }
16811
16812    @Override
16813    public void resetApplicationPreferences(int userId) {
16814        mContext.enforceCallingOrSelfPermission(
16815                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16816        final long identity = Binder.clearCallingIdentity();
16817        // writer
16818        try {
16819            synchronized (mPackages) {
16820                clearPackagePreferredActivitiesLPw(null, userId);
16821                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16822                // TODO: We have to reset the default SMS and Phone. This requires
16823                // significant refactoring to keep all default apps in the package
16824                // manager (cleaner but more work) or have the services provide
16825                // callbacks to the package manager to request a default app reset.
16826                applyFactoryDefaultBrowserLPw(userId);
16827                clearIntentFilterVerificationsLPw(userId);
16828                primeDomainVerificationsLPw(userId);
16829                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16830                scheduleWritePackageRestrictionsLocked(userId);
16831            }
16832            resetNetworkPolicies(userId);
16833        } finally {
16834            Binder.restoreCallingIdentity(identity);
16835        }
16836    }
16837
16838    @Override
16839    public int getPreferredActivities(List<IntentFilter> outFilters,
16840            List<ComponentName> outActivities, String packageName) {
16841
16842        int num = 0;
16843        final int userId = UserHandle.getCallingUserId();
16844        // reader
16845        synchronized (mPackages) {
16846            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16847            if (pir != null) {
16848                final Iterator<PreferredActivity> it = pir.filterIterator();
16849                while (it.hasNext()) {
16850                    final PreferredActivity pa = it.next();
16851                    if (packageName == null
16852                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16853                                    && pa.mPref.mAlways)) {
16854                        if (outFilters != null) {
16855                            outFilters.add(new IntentFilter(pa));
16856                        }
16857                        if (outActivities != null) {
16858                            outActivities.add(pa.mPref.mComponent);
16859                        }
16860                    }
16861                }
16862            }
16863        }
16864
16865        return num;
16866    }
16867
16868    @Override
16869    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16870            int userId) {
16871        int callingUid = Binder.getCallingUid();
16872        if (callingUid != Process.SYSTEM_UID) {
16873            throw new SecurityException(
16874                    "addPersistentPreferredActivity can only be run by the system");
16875        }
16876        if (filter.countActions() == 0) {
16877            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16878            return;
16879        }
16880        synchronized (mPackages) {
16881            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16882                    ":");
16883            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16884            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16885                    new PersistentPreferredActivity(filter, activity));
16886            scheduleWritePackageRestrictionsLocked(userId);
16887        }
16888    }
16889
16890    @Override
16891    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16892        int callingUid = Binder.getCallingUid();
16893        if (callingUid != Process.SYSTEM_UID) {
16894            throw new SecurityException(
16895                    "clearPackagePersistentPreferredActivities can only be run by the system");
16896        }
16897        ArrayList<PersistentPreferredActivity> removed = null;
16898        boolean changed = false;
16899        synchronized (mPackages) {
16900            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16901                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16902                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16903                        .valueAt(i);
16904                if (userId != thisUserId) {
16905                    continue;
16906                }
16907                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16908                while (it.hasNext()) {
16909                    PersistentPreferredActivity ppa = it.next();
16910                    // Mark entry for removal only if it matches the package name.
16911                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16912                        if (removed == null) {
16913                            removed = new ArrayList<PersistentPreferredActivity>();
16914                        }
16915                        removed.add(ppa);
16916                    }
16917                }
16918                if (removed != null) {
16919                    for (int j=0; j<removed.size(); j++) {
16920                        PersistentPreferredActivity ppa = removed.get(j);
16921                        ppir.removeFilter(ppa);
16922                    }
16923                    changed = true;
16924                }
16925            }
16926
16927            if (changed) {
16928                scheduleWritePackageRestrictionsLocked(userId);
16929            }
16930        }
16931    }
16932
16933    /**
16934     * Common machinery for picking apart a restored XML blob and passing
16935     * it to a caller-supplied functor to be applied to the running system.
16936     */
16937    private void restoreFromXml(XmlPullParser parser, int userId,
16938            String expectedStartTag, BlobXmlRestorer functor)
16939            throws IOException, XmlPullParserException {
16940        int type;
16941        while ((type = parser.next()) != XmlPullParser.START_TAG
16942                && type != XmlPullParser.END_DOCUMENT) {
16943        }
16944        if (type != XmlPullParser.START_TAG) {
16945            // oops didn't find a start tag?!
16946            if (DEBUG_BACKUP) {
16947                Slog.e(TAG, "Didn't find start tag during restore");
16948            }
16949            return;
16950        }
16951Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16952        // this is supposed to be TAG_PREFERRED_BACKUP
16953        if (!expectedStartTag.equals(parser.getName())) {
16954            if (DEBUG_BACKUP) {
16955                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16956            }
16957            return;
16958        }
16959
16960        // skip interfering stuff, then we're aligned with the backing implementation
16961        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16962Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16963        functor.apply(parser, userId);
16964    }
16965
16966    private interface BlobXmlRestorer {
16967        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16968    }
16969
16970    /**
16971     * Non-Binder method, support for the backup/restore mechanism: write the
16972     * full set of preferred activities in its canonical XML format.  Returns the
16973     * XML output as a byte array, or null if there is none.
16974     */
16975    @Override
16976    public byte[] getPreferredActivityBackup(int userId) {
16977        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16978            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16979        }
16980
16981        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16982        try {
16983            final XmlSerializer serializer = new FastXmlSerializer();
16984            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16985            serializer.startDocument(null, true);
16986            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16987
16988            synchronized (mPackages) {
16989                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16990            }
16991
16992            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16993            serializer.endDocument();
16994            serializer.flush();
16995        } catch (Exception e) {
16996            if (DEBUG_BACKUP) {
16997                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16998            }
16999            return null;
17000        }
17001
17002        return dataStream.toByteArray();
17003    }
17004
17005    @Override
17006    public void restorePreferredActivities(byte[] backup, int userId) {
17007        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17008            throw new SecurityException("Only the system may call restorePreferredActivities()");
17009        }
17010
17011        try {
17012            final XmlPullParser parser = Xml.newPullParser();
17013            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17014            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17015                    new BlobXmlRestorer() {
17016                        @Override
17017                        public void apply(XmlPullParser parser, int userId)
17018                                throws XmlPullParserException, IOException {
17019                            synchronized (mPackages) {
17020                                mSettings.readPreferredActivitiesLPw(parser, userId);
17021                            }
17022                        }
17023                    } );
17024        } catch (Exception e) {
17025            if (DEBUG_BACKUP) {
17026                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17027            }
17028        }
17029    }
17030
17031    /**
17032     * Non-Binder method, support for the backup/restore mechanism: write the
17033     * default browser (etc) settings in its canonical XML format.  Returns the default
17034     * browser XML representation as a byte array, or null if there is none.
17035     */
17036    @Override
17037    public byte[] getDefaultAppsBackup(int userId) {
17038        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17039            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17040        }
17041
17042        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17043        try {
17044            final XmlSerializer serializer = new FastXmlSerializer();
17045            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17046            serializer.startDocument(null, true);
17047            serializer.startTag(null, TAG_DEFAULT_APPS);
17048
17049            synchronized (mPackages) {
17050                mSettings.writeDefaultAppsLPr(serializer, userId);
17051            }
17052
17053            serializer.endTag(null, TAG_DEFAULT_APPS);
17054            serializer.endDocument();
17055            serializer.flush();
17056        } catch (Exception e) {
17057            if (DEBUG_BACKUP) {
17058                Slog.e(TAG, "Unable to write default apps for backup", e);
17059            }
17060            return null;
17061        }
17062
17063        return dataStream.toByteArray();
17064    }
17065
17066    @Override
17067    public void restoreDefaultApps(byte[] backup, int userId) {
17068        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17069            throw new SecurityException("Only the system may call restoreDefaultApps()");
17070        }
17071
17072        try {
17073            final XmlPullParser parser = Xml.newPullParser();
17074            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17075            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17076                    new BlobXmlRestorer() {
17077                        @Override
17078                        public void apply(XmlPullParser parser, int userId)
17079                                throws XmlPullParserException, IOException {
17080                            synchronized (mPackages) {
17081                                mSettings.readDefaultAppsLPw(parser, userId);
17082                            }
17083                        }
17084                    } );
17085        } catch (Exception e) {
17086            if (DEBUG_BACKUP) {
17087                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17088            }
17089        }
17090    }
17091
17092    @Override
17093    public byte[] getIntentFilterVerificationBackup(int userId) {
17094        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17095            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17096        }
17097
17098        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17099        try {
17100            final XmlSerializer serializer = new FastXmlSerializer();
17101            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17102            serializer.startDocument(null, true);
17103            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17104
17105            synchronized (mPackages) {
17106                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17107            }
17108
17109            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17110            serializer.endDocument();
17111            serializer.flush();
17112        } catch (Exception e) {
17113            if (DEBUG_BACKUP) {
17114                Slog.e(TAG, "Unable to write default apps for backup", e);
17115            }
17116            return null;
17117        }
17118
17119        return dataStream.toByteArray();
17120    }
17121
17122    @Override
17123    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17124        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17125            throw new SecurityException("Only the system may call restorePreferredActivities()");
17126        }
17127
17128        try {
17129            final XmlPullParser parser = Xml.newPullParser();
17130            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17131            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17132                    new BlobXmlRestorer() {
17133                        @Override
17134                        public void apply(XmlPullParser parser, int userId)
17135                                throws XmlPullParserException, IOException {
17136                            synchronized (mPackages) {
17137                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17138                                mSettings.writeLPr();
17139                            }
17140                        }
17141                    } );
17142        } catch (Exception e) {
17143            if (DEBUG_BACKUP) {
17144                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17145            }
17146        }
17147    }
17148
17149    @Override
17150    public byte[] getPermissionGrantBackup(int userId) {
17151        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17152            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17153        }
17154
17155        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17156        try {
17157            final XmlSerializer serializer = new FastXmlSerializer();
17158            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17159            serializer.startDocument(null, true);
17160            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17161
17162            synchronized (mPackages) {
17163                serializeRuntimePermissionGrantsLPr(serializer, userId);
17164            }
17165
17166            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17167            serializer.endDocument();
17168            serializer.flush();
17169        } catch (Exception e) {
17170            if (DEBUG_BACKUP) {
17171                Slog.e(TAG, "Unable to write default apps for backup", e);
17172            }
17173            return null;
17174        }
17175
17176        return dataStream.toByteArray();
17177    }
17178
17179    @Override
17180    public void restorePermissionGrants(byte[] backup, int userId) {
17181        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17182            throw new SecurityException("Only the system may call restorePermissionGrants()");
17183        }
17184
17185        try {
17186            final XmlPullParser parser = Xml.newPullParser();
17187            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17188            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17189                    new BlobXmlRestorer() {
17190                        @Override
17191                        public void apply(XmlPullParser parser, int userId)
17192                                throws XmlPullParserException, IOException {
17193                            synchronized (mPackages) {
17194                                processRestoredPermissionGrantsLPr(parser, userId);
17195                            }
17196                        }
17197                    } );
17198        } catch (Exception e) {
17199            if (DEBUG_BACKUP) {
17200                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17201            }
17202        }
17203    }
17204
17205    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17206            throws IOException {
17207        serializer.startTag(null, TAG_ALL_GRANTS);
17208
17209        final int N = mSettings.mPackages.size();
17210        for (int i = 0; i < N; i++) {
17211            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17212            boolean pkgGrantsKnown = false;
17213
17214            PermissionsState packagePerms = ps.getPermissionsState();
17215
17216            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17217                final int grantFlags = state.getFlags();
17218                // only look at grants that are not system/policy fixed
17219                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17220                    final boolean isGranted = state.isGranted();
17221                    // And only back up the user-twiddled state bits
17222                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17223                        final String packageName = mSettings.mPackages.keyAt(i);
17224                        if (!pkgGrantsKnown) {
17225                            serializer.startTag(null, TAG_GRANT);
17226                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17227                            pkgGrantsKnown = true;
17228                        }
17229
17230                        final boolean userSet =
17231                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17232                        final boolean userFixed =
17233                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17234                        final boolean revoke =
17235                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17236
17237                        serializer.startTag(null, TAG_PERMISSION);
17238                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17239                        if (isGranted) {
17240                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17241                        }
17242                        if (userSet) {
17243                            serializer.attribute(null, ATTR_USER_SET, "true");
17244                        }
17245                        if (userFixed) {
17246                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17247                        }
17248                        if (revoke) {
17249                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17250                        }
17251                        serializer.endTag(null, TAG_PERMISSION);
17252                    }
17253                }
17254            }
17255
17256            if (pkgGrantsKnown) {
17257                serializer.endTag(null, TAG_GRANT);
17258            }
17259        }
17260
17261        serializer.endTag(null, TAG_ALL_GRANTS);
17262    }
17263
17264    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17265            throws XmlPullParserException, IOException {
17266        String pkgName = null;
17267        int outerDepth = parser.getDepth();
17268        int type;
17269        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17270                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17271            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17272                continue;
17273            }
17274
17275            final String tagName = parser.getName();
17276            if (tagName.equals(TAG_GRANT)) {
17277                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17278                if (DEBUG_BACKUP) {
17279                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17280                }
17281            } else if (tagName.equals(TAG_PERMISSION)) {
17282
17283                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17284                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17285
17286                int newFlagSet = 0;
17287                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17288                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17289                }
17290                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17291                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17292                }
17293                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17294                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17295                }
17296                if (DEBUG_BACKUP) {
17297                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17298                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17299                }
17300                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17301                if (ps != null) {
17302                    // Already installed so we apply the grant immediately
17303                    if (DEBUG_BACKUP) {
17304                        Slog.v(TAG, "        + already installed; applying");
17305                    }
17306                    PermissionsState perms = ps.getPermissionsState();
17307                    BasePermission bp = mSettings.mPermissions.get(permName);
17308                    if (bp != null) {
17309                        if (isGranted) {
17310                            perms.grantRuntimePermission(bp, userId);
17311                        }
17312                        if (newFlagSet != 0) {
17313                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17314                        }
17315                    }
17316                } else {
17317                    // Need to wait for post-restore install to apply the grant
17318                    if (DEBUG_BACKUP) {
17319                        Slog.v(TAG, "        - not yet installed; saving for later");
17320                    }
17321                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17322                            isGranted, newFlagSet, userId);
17323                }
17324            } else {
17325                PackageManagerService.reportSettingsProblem(Log.WARN,
17326                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17327                XmlUtils.skipCurrentTag(parser);
17328            }
17329        }
17330
17331        scheduleWriteSettingsLocked();
17332        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17333    }
17334
17335    @Override
17336    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17337            int sourceUserId, int targetUserId, int flags) {
17338        mContext.enforceCallingOrSelfPermission(
17339                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17340        int callingUid = Binder.getCallingUid();
17341        enforceOwnerRights(ownerPackage, callingUid);
17342        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17343        if (intentFilter.countActions() == 0) {
17344            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17345            return;
17346        }
17347        synchronized (mPackages) {
17348            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17349                    ownerPackage, targetUserId, flags);
17350            CrossProfileIntentResolver resolver =
17351                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17352            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17353            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17354            if (existing != null) {
17355                int size = existing.size();
17356                for (int i = 0; i < size; i++) {
17357                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17358                        return;
17359                    }
17360                }
17361            }
17362            resolver.addFilter(newFilter);
17363            scheduleWritePackageRestrictionsLocked(sourceUserId);
17364        }
17365    }
17366
17367    @Override
17368    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17369        mContext.enforceCallingOrSelfPermission(
17370                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17371        int callingUid = Binder.getCallingUid();
17372        enforceOwnerRights(ownerPackage, callingUid);
17373        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17374        synchronized (mPackages) {
17375            CrossProfileIntentResolver resolver =
17376                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17377            ArraySet<CrossProfileIntentFilter> set =
17378                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17379            for (CrossProfileIntentFilter filter : set) {
17380                if (filter.getOwnerPackage().equals(ownerPackage)) {
17381                    resolver.removeFilter(filter);
17382                }
17383            }
17384            scheduleWritePackageRestrictionsLocked(sourceUserId);
17385        }
17386    }
17387
17388    // Enforcing that callingUid is owning pkg on userId
17389    private void enforceOwnerRights(String pkg, int callingUid) {
17390        // The system owns everything.
17391        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17392            return;
17393        }
17394        int callingUserId = UserHandle.getUserId(callingUid);
17395        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17396        if (pi == null) {
17397            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17398                    + callingUserId);
17399        }
17400        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17401            throw new SecurityException("Calling uid " + callingUid
17402                    + " does not own package " + pkg);
17403        }
17404    }
17405
17406    @Override
17407    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17408        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17409    }
17410
17411    private Intent getHomeIntent() {
17412        Intent intent = new Intent(Intent.ACTION_MAIN);
17413        intent.addCategory(Intent.CATEGORY_HOME);
17414        return intent;
17415    }
17416
17417    private IntentFilter getHomeFilter() {
17418        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17419        filter.addCategory(Intent.CATEGORY_HOME);
17420        filter.addCategory(Intent.CATEGORY_DEFAULT);
17421        return filter;
17422    }
17423
17424    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17425            int userId) {
17426        Intent intent  = getHomeIntent();
17427        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17428                PackageManager.GET_META_DATA, userId);
17429        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17430                true, false, false, userId);
17431
17432        allHomeCandidates.clear();
17433        if (list != null) {
17434            for (ResolveInfo ri : list) {
17435                allHomeCandidates.add(ri);
17436            }
17437        }
17438        return (preferred == null || preferred.activityInfo == null)
17439                ? null
17440                : new ComponentName(preferred.activityInfo.packageName,
17441                        preferred.activityInfo.name);
17442    }
17443
17444    @Override
17445    public void setHomeActivity(ComponentName comp, int userId) {
17446        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17447        getHomeActivitiesAsUser(homeActivities, userId);
17448
17449        boolean found = false;
17450
17451        final int size = homeActivities.size();
17452        final ComponentName[] set = new ComponentName[size];
17453        for (int i = 0; i < size; i++) {
17454            final ResolveInfo candidate = homeActivities.get(i);
17455            final ActivityInfo info = candidate.activityInfo;
17456            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17457            set[i] = activityName;
17458            if (!found && activityName.equals(comp)) {
17459                found = true;
17460            }
17461        }
17462        if (!found) {
17463            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17464                    + userId);
17465        }
17466        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17467                set, comp, userId);
17468    }
17469
17470    private @Nullable String getSetupWizardPackageName() {
17471        final Intent intent = new Intent(Intent.ACTION_MAIN);
17472        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17473
17474        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17475                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17476                        | MATCH_DISABLED_COMPONENTS,
17477                UserHandle.myUserId());
17478        if (matches.size() == 1) {
17479            return matches.get(0).getComponentInfo().packageName;
17480        } else {
17481            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17482                    + ": matches=" + matches);
17483            return null;
17484        }
17485    }
17486
17487    @Override
17488    public void setApplicationEnabledSetting(String appPackageName,
17489            int newState, int flags, int userId, String callingPackage) {
17490        if (!sUserManager.exists(userId)) return;
17491        if (callingPackage == null) {
17492            callingPackage = Integer.toString(Binder.getCallingUid());
17493        }
17494        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17495    }
17496
17497    @Override
17498    public void setComponentEnabledSetting(ComponentName componentName,
17499            int newState, int flags, int userId) {
17500        if (!sUserManager.exists(userId)) return;
17501        setEnabledSetting(componentName.getPackageName(),
17502                componentName.getClassName(), newState, flags, userId, null);
17503    }
17504
17505    private void setEnabledSetting(final String packageName, String className, int newState,
17506            final int flags, int userId, String callingPackage) {
17507        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17508              || newState == COMPONENT_ENABLED_STATE_ENABLED
17509              || newState == COMPONENT_ENABLED_STATE_DISABLED
17510              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17511              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17512            throw new IllegalArgumentException("Invalid new component state: "
17513                    + newState);
17514        }
17515        PackageSetting pkgSetting;
17516        final int uid = Binder.getCallingUid();
17517        final int permission;
17518        if (uid == Process.SYSTEM_UID) {
17519            permission = PackageManager.PERMISSION_GRANTED;
17520        } else {
17521            permission = mContext.checkCallingOrSelfPermission(
17522                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17523        }
17524        enforceCrossUserPermission(uid, userId,
17525                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17526        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17527        boolean sendNow = false;
17528        boolean isApp = (className == null);
17529        String componentName = isApp ? packageName : className;
17530        int packageUid = -1;
17531        ArrayList<String> components;
17532
17533        // writer
17534        synchronized (mPackages) {
17535            pkgSetting = mSettings.mPackages.get(packageName);
17536            if (pkgSetting == null) {
17537                if (className == null) {
17538                    throw new IllegalArgumentException("Unknown package: " + packageName);
17539                }
17540                throw new IllegalArgumentException(
17541                        "Unknown component: " + packageName + "/" + className);
17542            }
17543        }
17544
17545        // Limit who can change which apps
17546        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17547            // Don't allow apps that don't have permission to modify other apps
17548            if (!allowedByPermission) {
17549                throw new SecurityException(
17550                        "Permission Denial: attempt to change component state from pid="
17551                        + Binder.getCallingPid()
17552                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17553            }
17554            // Don't allow changing profile and device owners. Calling into DPMS, so no locking.
17555            final DevicePolicyManagerInternal dpmi = LocalServices
17556                    .getService(DevicePolicyManagerInternal.class);
17557            if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
17558                throw new SecurityException("Cannot disable a device owner or a profile owner");
17559            }
17560        }
17561
17562        synchronized (mPackages) {
17563            if (uid == Process.SHELL_UID) {
17564                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17565                int oldState = pkgSetting.getEnabled(userId);
17566                if (className == null
17567                    &&
17568                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17569                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17570                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17571                    &&
17572                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17573                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17574                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17575                    // ok
17576                } else {
17577                    throw new SecurityException(
17578                            "Shell cannot change component state for " + packageName + "/"
17579                            + className + " to " + newState);
17580                }
17581            }
17582            if (className == null) {
17583                // We're dealing with an application/package level state change
17584                if (pkgSetting.getEnabled(userId) == newState) {
17585                    // Nothing to do
17586                    return;
17587                }
17588                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17589                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17590                    // Don't care about who enables an app.
17591                    callingPackage = null;
17592                }
17593                pkgSetting.setEnabled(newState, userId, callingPackage);
17594                // pkgSetting.pkg.mSetEnabled = newState;
17595            } else {
17596                // We're dealing with a component level state change
17597                // First, verify that this is a valid class name.
17598                PackageParser.Package pkg = pkgSetting.pkg;
17599                if (pkg == null || !pkg.hasComponentClassName(className)) {
17600                    if (pkg != null &&
17601                            pkg.applicationInfo.targetSdkVersion >=
17602                                    Build.VERSION_CODES.JELLY_BEAN) {
17603                        throw new IllegalArgumentException("Component class " + className
17604                                + " does not exist in " + packageName);
17605                    } else {
17606                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17607                                + className + " does not exist in " + packageName);
17608                    }
17609                }
17610                switch (newState) {
17611                case COMPONENT_ENABLED_STATE_ENABLED:
17612                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17613                        return;
17614                    }
17615                    break;
17616                case COMPONENT_ENABLED_STATE_DISABLED:
17617                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17618                        return;
17619                    }
17620                    break;
17621                case COMPONENT_ENABLED_STATE_DEFAULT:
17622                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17623                        return;
17624                    }
17625                    break;
17626                default:
17627                    Slog.e(TAG, "Invalid new component state: " + newState);
17628                    return;
17629                }
17630            }
17631            scheduleWritePackageRestrictionsLocked(userId);
17632            components = mPendingBroadcasts.get(userId, packageName);
17633            final boolean newPackage = components == null;
17634            if (newPackage) {
17635                components = new ArrayList<String>();
17636            }
17637            if (!components.contains(componentName)) {
17638                components.add(componentName);
17639            }
17640            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17641                sendNow = true;
17642                // Purge entry from pending broadcast list if another one exists already
17643                // since we are sending one right away.
17644                mPendingBroadcasts.remove(userId, packageName);
17645            } else {
17646                if (newPackage) {
17647                    mPendingBroadcasts.put(userId, packageName, components);
17648                }
17649                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17650                    // Schedule a message
17651                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17652                }
17653            }
17654        }
17655
17656        long callingId = Binder.clearCallingIdentity();
17657        try {
17658            if (sendNow) {
17659                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17660                sendPackageChangedBroadcast(packageName,
17661                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17662            }
17663        } finally {
17664            Binder.restoreCallingIdentity(callingId);
17665        }
17666    }
17667
17668    @Override
17669    public void flushPackageRestrictionsAsUser(int userId) {
17670        if (!sUserManager.exists(userId)) {
17671            return;
17672        }
17673        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17674                false /* checkShell */, "flushPackageRestrictions");
17675        synchronized (mPackages) {
17676            mSettings.writePackageRestrictionsLPr(userId);
17677            mDirtyUsers.remove(userId);
17678            if (mDirtyUsers.isEmpty()) {
17679                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17680            }
17681        }
17682    }
17683
17684    private void sendPackageChangedBroadcast(String packageName,
17685            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17686        if (DEBUG_INSTALL)
17687            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17688                    + componentNames);
17689        Bundle extras = new Bundle(4);
17690        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17691        String nameList[] = new String[componentNames.size()];
17692        componentNames.toArray(nameList);
17693        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17694        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17695        extras.putInt(Intent.EXTRA_UID, packageUid);
17696        // If this is not reporting a change of the overall package, then only send it
17697        // to registered receivers.  We don't want to launch a swath of apps for every
17698        // little component state change.
17699        final int flags = !componentNames.contains(packageName)
17700                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17701        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17702                new int[] {UserHandle.getUserId(packageUid)});
17703    }
17704
17705    @Override
17706    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17707        if (!sUserManager.exists(userId)) return;
17708        final int uid = Binder.getCallingUid();
17709        final int permission = mContext.checkCallingOrSelfPermission(
17710                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17711        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17712        enforceCrossUserPermission(uid, userId,
17713                true /* requireFullPermission */, true /* checkShell */, "stop package");
17714        // writer
17715        synchronized (mPackages) {
17716            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17717                    allowedByPermission, uid, userId)) {
17718                scheduleWritePackageRestrictionsLocked(userId);
17719            }
17720        }
17721    }
17722
17723    @Override
17724    public String getInstallerPackageName(String packageName) {
17725        // reader
17726        synchronized (mPackages) {
17727            return mSettings.getInstallerPackageNameLPr(packageName);
17728        }
17729    }
17730
17731    public boolean isOrphaned(String packageName) {
17732        // reader
17733        synchronized (mPackages) {
17734            return mSettings.isOrphaned(packageName);
17735        }
17736    }
17737
17738    @Override
17739    public int getApplicationEnabledSetting(String packageName, int userId) {
17740        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17741        int uid = Binder.getCallingUid();
17742        enforceCrossUserPermission(uid, userId,
17743                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17744        // reader
17745        synchronized (mPackages) {
17746            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17747        }
17748    }
17749
17750    @Override
17751    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17752        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17753        int uid = Binder.getCallingUid();
17754        enforceCrossUserPermission(uid, userId,
17755                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17756        // reader
17757        synchronized (mPackages) {
17758            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17759        }
17760    }
17761
17762    @Override
17763    public void enterSafeMode() {
17764        enforceSystemOrRoot("Only the system can request entering safe mode");
17765
17766        if (!mSystemReady) {
17767            mSafeMode = true;
17768        }
17769    }
17770
17771    @Override
17772    public void systemReady() {
17773        mSystemReady = true;
17774
17775        // Read the compatibilty setting when the system is ready.
17776        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17777                mContext.getContentResolver(),
17778                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17779        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17780        if (DEBUG_SETTINGS) {
17781            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17782        }
17783
17784        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17785
17786        synchronized (mPackages) {
17787            // Verify that all of the preferred activity components actually
17788            // exist.  It is possible for applications to be updated and at
17789            // that point remove a previously declared activity component that
17790            // had been set as a preferred activity.  We try to clean this up
17791            // the next time we encounter that preferred activity, but it is
17792            // possible for the user flow to never be able to return to that
17793            // situation so here we do a sanity check to make sure we haven't
17794            // left any junk around.
17795            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17796            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17797                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17798                removed.clear();
17799                for (PreferredActivity pa : pir.filterSet()) {
17800                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17801                        removed.add(pa);
17802                    }
17803                }
17804                if (removed.size() > 0) {
17805                    for (int r=0; r<removed.size(); r++) {
17806                        PreferredActivity pa = removed.get(r);
17807                        Slog.w(TAG, "Removing dangling preferred activity: "
17808                                + pa.mPref.mComponent);
17809                        pir.removeFilter(pa);
17810                    }
17811                    mSettings.writePackageRestrictionsLPr(
17812                            mSettings.mPreferredActivities.keyAt(i));
17813                }
17814            }
17815
17816            for (int userId : UserManagerService.getInstance().getUserIds()) {
17817                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17818                    grantPermissionsUserIds = ArrayUtils.appendInt(
17819                            grantPermissionsUserIds, userId);
17820                }
17821            }
17822        }
17823        sUserManager.systemReady();
17824
17825        // If we upgraded grant all default permissions before kicking off.
17826        for (int userId : grantPermissionsUserIds) {
17827            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17828        }
17829
17830        // Kick off any messages waiting for system ready
17831        if (mPostSystemReadyMessages != null) {
17832            for (Message msg : mPostSystemReadyMessages) {
17833                msg.sendToTarget();
17834            }
17835            mPostSystemReadyMessages = null;
17836        }
17837
17838        // Watch for external volumes that come and go over time
17839        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17840        storage.registerListener(mStorageListener);
17841
17842        mInstallerService.systemReady();
17843        mPackageDexOptimizer.systemReady();
17844
17845        MountServiceInternal mountServiceInternal = LocalServices.getService(
17846                MountServiceInternal.class);
17847        mountServiceInternal.addExternalStoragePolicy(
17848                new MountServiceInternal.ExternalStorageMountPolicy() {
17849            @Override
17850            public int getMountMode(int uid, String packageName) {
17851                if (Process.isIsolated(uid)) {
17852                    return Zygote.MOUNT_EXTERNAL_NONE;
17853                }
17854                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17855                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17856                }
17857                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17858                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17859                }
17860                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17861                    return Zygote.MOUNT_EXTERNAL_READ;
17862                }
17863                return Zygote.MOUNT_EXTERNAL_WRITE;
17864            }
17865
17866            @Override
17867            public boolean hasExternalStorage(int uid, String packageName) {
17868                return true;
17869            }
17870        });
17871
17872        // Now that we're mostly running, clean up stale users and apps
17873        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17874        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17875    }
17876
17877    @Override
17878    public boolean isSafeMode() {
17879        return mSafeMode;
17880    }
17881
17882    @Override
17883    public boolean hasSystemUidErrors() {
17884        return mHasSystemUidErrors;
17885    }
17886
17887    static String arrayToString(int[] array) {
17888        StringBuffer buf = new StringBuffer(128);
17889        buf.append('[');
17890        if (array != null) {
17891            for (int i=0; i<array.length; i++) {
17892                if (i > 0) buf.append(", ");
17893                buf.append(array[i]);
17894            }
17895        }
17896        buf.append(']');
17897        return buf.toString();
17898    }
17899
17900    static class DumpState {
17901        public static final int DUMP_LIBS = 1 << 0;
17902        public static final int DUMP_FEATURES = 1 << 1;
17903        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17904        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17905        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17906        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17907        public static final int DUMP_PERMISSIONS = 1 << 6;
17908        public static final int DUMP_PACKAGES = 1 << 7;
17909        public static final int DUMP_SHARED_USERS = 1 << 8;
17910        public static final int DUMP_MESSAGES = 1 << 9;
17911        public static final int DUMP_PROVIDERS = 1 << 10;
17912        public static final int DUMP_VERIFIERS = 1 << 11;
17913        public static final int DUMP_PREFERRED = 1 << 12;
17914        public static final int DUMP_PREFERRED_XML = 1 << 13;
17915        public static final int DUMP_KEYSETS = 1 << 14;
17916        public static final int DUMP_VERSION = 1 << 15;
17917        public static final int DUMP_INSTALLS = 1 << 16;
17918        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17919        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17920        public static final int DUMP_FROZEN = 1 << 19;
17921        public static final int DUMP_DEXOPT = 1 << 20;
17922
17923        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17924
17925        private int mTypes;
17926
17927        private int mOptions;
17928
17929        private boolean mTitlePrinted;
17930
17931        private SharedUserSetting mSharedUser;
17932
17933        public boolean isDumping(int type) {
17934            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17935                return true;
17936            }
17937
17938            return (mTypes & type) != 0;
17939        }
17940
17941        public void setDump(int type) {
17942            mTypes |= type;
17943        }
17944
17945        public boolean isOptionEnabled(int option) {
17946            return (mOptions & option) != 0;
17947        }
17948
17949        public void setOptionEnabled(int option) {
17950            mOptions |= option;
17951        }
17952
17953        public boolean onTitlePrinted() {
17954            final boolean printed = mTitlePrinted;
17955            mTitlePrinted = true;
17956            return printed;
17957        }
17958
17959        public boolean getTitlePrinted() {
17960            return mTitlePrinted;
17961        }
17962
17963        public void setTitlePrinted(boolean enabled) {
17964            mTitlePrinted = enabled;
17965        }
17966
17967        public SharedUserSetting getSharedUser() {
17968            return mSharedUser;
17969        }
17970
17971        public void setSharedUser(SharedUserSetting user) {
17972            mSharedUser = user;
17973        }
17974    }
17975
17976    @Override
17977    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17978            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17979        (new PackageManagerShellCommand(this)).exec(
17980                this, in, out, err, args, resultReceiver);
17981    }
17982
17983    @Override
17984    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17985        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17986                != PackageManager.PERMISSION_GRANTED) {
17987            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17988                    + Binder.getCallingPid()
17989                    + ", uid=" + Binder.getCallingUid()
17990                    + " without permission "
17991                    + android.Manifest.permission.DUMP);
17992            return;
17993        }
17994
17995        DumpState dumpState = new DumpState();
17996        boolean fullPreferred = false;
17997        boolean checkin = false;
17998
17999        String packageName = null;
18000        ArraySet<String> permissionNames = null;
18001
18002        int opti = 0;
18003        while (opti < args.length) {
18004            String opt = args[opti];
18005            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18006                break;
18007            }
18008            opti++;
18009
18010            if ("-a".equals(opt)) {
18011                // Right now we only know how to print all.
18012            } else if ("-h".equals(opt)) {
18013                pw.println("Package manager dump options:");
18014                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18015                pw.println("    --checkin: dump for a checkin");
18016                pw.println("    -f: print details of intent filters");
18017                pw.println("    -h: print this help");
18018                pw.println("  cmd may be one of:");
18019                pw.println("    l[ibraries]: list known shared libraries");
18020                pw.println("    f[eatures]: list device features");
18021                pw.println("    k[eysets]: print known keysets");
18022                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18023                pw.println("    perm[issions]: dump permissions");
18024                pw.println("    permission [name ...]: dump declaration and use of given permission");
18025                pw.println("    pref[erred]: print preferred package settings");
18026                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18027                pw.println("    prov[iders]: dump content providers");
18028                pw.println("    p[ackages]: dump installed packages");
18029                pw.println("    s[hared-users]: dump shared user IDs");
18030                pw.println("    m[essages]: print collected runtime messages");
18031                pw.println("    v[erifiers]: print package verifier info");
18032                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18033                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18034                pw.println("    version: print database version info");
18035                pw.println("    write: write current settings now");
18036                pw.println("    installs: details about install sessions");
18037                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18038                pw.println("    dexopt: dump dexopt state");
18039                pw.println("    <package.name>: info about given package");
18040                return;
18041            } else if ("--checkin".equals(opt)) {
18042                checkin = true;
18043            } else if ("-f".equals(opt)) {
18044                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18045            } else {
18046                pw.println("Unknown argument: " + opt + "; use -h for help");
18047            }
18048        }
18049
18050        // Is the caller requesting to dump a particular piece of data?
18051        if (opti < args.length) {
18052            String cmd = args[opti];
18053            opti++;
18054            // Is this a package name?
18055            if ("android".equals(cmd) || cmd.contains(".")) {
18056                packageName = cmd;
18057                // When dumping a single package, we always dump all of its
18058                // filter information since the amount of data will be reasonable.
18059                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18060            } else if ("check-permission".equals(cmd)) {
18061                if (opti >= args.length) {
18062                    pw.println("Error: check-permission missing permission argument");
18063                    return;
18064                }
18065                String perm = args[opti];
18066                opti++;
18067                if (opti >= args.length) {
18068                    pw.println("Error: check-permission missing package argument");
18069                    return;
18070                }
18071                String pkg = args[opti];
18072                opti++;
18073                int user = UserHandle.getUserId(Binder.getCallingUid());
18074                if (opti < args.length) {
18075                    try {
18076                        user = Integer.parseInt(args[opti]);
18077                    } catch (NumberFormatException e) {
18078                        pw.println("Error: check-permission user argument is not a number: "
18079                                + args[opti]);
18080                        return;
18081                    }
18082                }
18083                pw.println(checkPermission(perm, pkg, user));
18084                return;
18085            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18086                dumpState.setDump(DumpState.DUMP_LIBS);
18087            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18088                dumpState.setDump(DumpState.DUMP_FEATURES);
18089            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18090                if (opti >= args.length) {
18091                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18092                            | DumpState.DUMP_SERVICE_RESOLVERS
18093                            | DumpState.DUMP_RECEIVER_RESOLVERS
18094                            | DumpState.DUMP_CONTENT_RESOLVERS);
18095                } else {
18096                    while (opti < args.length) {
18097                        String name = args[opti];
18098                        if ("a".equals(name) || "activity".equals(name)) {
18099                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18100                        } else if ("s".equals(name) || "service".equals(name)) {
18101                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18102                        } else if ("r".equals(name) || "receiver".equals(name)) {
18103                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18104                        } else if ("c".equals(name) || "content".equals(name)) {
18105                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18106                        } else {
18107                            pw.println("Error: unknown resolver table type: " + name);
18108                            return;
18109                        }
18110                        opti++;
18111                    }
18112                }
18113            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18114                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18115            } else if ("permission".equals(cmd)) {
18116                if (opti >= args.length) {
18117                    pw.println("Error: permission requires permission name");
18118                    return;
18119                }
18120                permissionNames = new ArraySet<>();
18121                while (opti < args.length) {
18122                    permissionNames.add(args[opti]);
18123                    opti++;
18124                }
18125                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18126                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18127            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18128                dumpState.setDump(DumpState.DUMP_PREFERRED);
18129            } else if ("preferred-xml".equals(cmd)) {
18130                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18131                if (opti < args.length && "--full".equals(args[opti])) {
18132                    fullPreferred = true;
18133                    opti++;
18134                }
18135            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18136                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18137            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18138                dumpState.setDump(DumpState.DUMP_PACKAGES);
18139            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18140                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18141            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18142                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18143            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18144                dumpState.setDump(DumpState.DUMP_MESSAGES);
18145            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18146                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18147            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18148                    || "intent-filter-verifiers".equals(cmd)) {
18149                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18150            } else if ("version".equals(cmd)) {
18151                dumpState.setDump(DumpState.DUMP_VERSION);
18152            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18153                dumpState.setDump(DumpState.DUMP_KEYSETS);
18154            } else if ("installs".equals(cmd)) {
18155                dumpState.setDump(DumpState.DUMP_INSTALLS);
18156            } else if ("frozen".equals(cmd)) {
18157                dumpState.setDump(DumpState.DUMP_FROZEN);
18158            } else if ("dexopt".equals(cmd)) {
18159                dumpState.setDump(DumpState.DUMP_DEXOPT);
18160            } else if ("write".equals(cmd)) {
18161                synchronized (mPackages) {
18162                    mSettings.writeLPr();
18163                    pw.println("Settings written.");
18164                    return;
18165                }
18166            }
18167        }
18168
18169        if (checkin) {
18170            pw.println("vers,1");
18171        }
18172
18173        // reader
18174        synchronized (mPackages) {
18175            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18176                if (!checkin) {
18177                    if (dumpState.onTitlePrinted())
18178                        pw.println();
18179                    pw.println("Database versions:");
18180                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18181                }
18182            }
18183
18184            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18185                if (!checkin) {
18186                    if (dumpState.onTitlePrinted())
18187                        pw.println();
18188                    pw.println("Verifiers:");
18189                    pw.print("  Required: ");
18190                    pw.print(mRequiredVerifierPackage);
18191                    pw.print(" (uid=");
18192                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18193                            UserHandle.USER_SYSTEM));
18194                    pw.println(")");
18195                } else if (mRequiredVerifierPackage != null) {
18196                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18197                    pw.print(",");
18198                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18199                            UserHandle.USER_SYSTEM));
18200                }
18201            }
18202
18203            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18204                    packageName == null) {
18205                if (mIntentFilterVerifierComponent != null) {
18206                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18207                    if (!checkin) {
18208                        if (dumpState.onTitlePrinted())
18209                            pw.println();
18210                        pw.println("Intent Filter Verifier:");
18211                        pw.print("  Using: ");
18212                        pw.print(verifierPackageName);
18213                        pw.print(" (uid=");
18214                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18215                                UserHandle.USER_SYSTEM));
18216                        pw.println(")");
18217                    } else if (verifierPackageName != null) {
18218                        pw.print("ifv,"); pw.print(verifierPackageName);
18219                        pw.print(",");
18220                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18221                                UserHandle.USER_SYSTEM));
18222                    }
18223                } else {
18224                    pw.println();
18225                    pw.println("No Intent Filter Verifier available!");
18226                }
18227            }
18228
18229            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18230                boolean printedHeader = false;
18231                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18232                while (it.hasNext()) {
18233                    String name = it.next();
18234                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18235                    if (!checkin) {
18236                        if (!printedHeader) {
18237                            if (dumpState.onTitlePrinted())
18238                                pw.println();
18239                            pw.println("Libraries:");
18240                            printedHeader = true;
18241                        }
18242                        pw.print("  ");
18243                    } else {
18244                        pw.print("lib,");
18245                    }
18246                    pw.print(name);
18247                    if (!checkin) {
18248                        pw.print(" -> ");
18249                    }
18250                    if (ent.path != null) {
18251                        if (!checkin) {
18252                            pw.print("(jar) ");
18253                            pw.print(ent.path);
18254                        } else {
18255                            pw.print(",jar,");
18256                            pw.print(ent.path);
18257                        }
18258                    } else {
18259                        if (!checkin) {
18260                            pw.print("(apk) ");
18261                            pw.print(ent.apk);
18262                        } else {
18263                            pw.print(",apk,");
18264                            pw.print(ent.apk);
18265                        }
18266                    }
18267                    pw.println();
18268                }
18269            }
18270
18271            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18272                if (dumpState.onTitlePrinted())
18273                    pw.println();
18274                if (!checkin) {
18275                    pw.println("Features:");
18276                }
18277
18278                for (FeatureInfo feat : mAvailableFeatures.values()) {
18279                    if (checkin) {
18280                        pw.print("feat,");
18281                        pw.print(feat.name);
18282                        pw.print(",");
18283                        pw.println(feat.version);
18284                    } else {
18285                        pw.print("  ");
18286                        pw.print(feat.name);
18287                        if (feat.version > 0) {
18288                            pw.print(" version=");
18289                            pw.print(feat.version);
18290                        }
18291                        pw.println();
18292                    }
18293                }
18294            }
18295
18296            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18297                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18298                        : "Activity Resolver Table:", "  ", packageName,
18299                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18300                    dumpState.setTitlePrinted(true);
18301                }
18302            }
18303            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18304                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18305                        : "Receiver Resolver Table:", "  ", packageName,
18306                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18307                    dumpState.setTitlePrinted(true);
18308                }
18309            }
18310            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18311                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18312                        : "Service Resolver Table:", "  ", packageName,
18313                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18314                    dumpState.setTitlePrinted(true);
18315                }
18316            }
18317            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18318                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18319                        : "Provider Resolver Table:", "  ", packageName,
18320                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18321                    dumpState.setTitlePrinted(true);
18322                }
18323            }
18324
18325            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18326                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18327                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18328                    int user = mSettings.mPreferredActivities.keyAt(i);
18329                    if (pir.dump(pw,
18330                            dumpState.getTitlePrinted()
18331                                ? "\nPreferred Activities User " + user + ":"
18332                                : "Preferred Activities User " + user + ":", "  ",
18333                            packageName, true, false)) {
18334                        dumpState.setTitlePrinted(true);
18335                    }
18336                }
18337            }
18338
18339            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18340                pw.flush();
18341                FileOutputStream fout = new FileOutputStream(fd);
18342                BufferedOutputStream str = new BufferedOutputStream(fout);
18343                XmlSerializer serializer = new FastXmlSerializer();
18344                try {
18345                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18346                    serializer.startDocument(null, true);
18347                    serializer.setFeature(
18348                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18349                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18350                    serializer.endDocument();
18351                    serializer.flush();
18352                } catch (IllegalArgumentException e) {
18353                    pw.println("Failed writing: " + e);
18354                } catch (IllegalStateException e) {
18355                    pw.println("Failed writing: " + e);
18356                } catch (IOException e) {
18357                    pw.println("Failed writing: " + e);
18358                }
18359            }
18360
18361            if (!checkin
18362                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18363                    && packageName == null) {
18364                pw.println();
18365                int count = mSettings.mPackages.size();
18366                if (count == 0) {
18367                    pw.println("No applications!");
18368                    pw.println();
18369                } else {
18370                    final String prefix = "  ";
18371                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18372                    if (allPackageSettings.size() == 0) {
18373                        pw.println("No domain preferred apps!");
18374                        pw.println();
18375                    } else {
18376                        pw.println("App verification status:");
18377                        pw.println();
18378                        count = 0;
18379                        for (PackageSetting ps : allPackageSettings) {
18380                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18381                            if (ivi == null || ivi.getPackageName() == null) continue;
18382                            pw.println(prefix + "Package: " + ivi.getPackageName());
18383                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18384                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18385                            pw.println();
18386                            count++;
18387                        }
18388                        if (count == 0) {
18389                            pw.println(prefix + "No app verification established.");
18390                            pw.println();
18391                        }
18392                        for (int userId : sUserManager.getUserIds()) {
18393                            pw.println("App linkages for user " + userId + ":");
18394                            pw.println();
18395                            count = 0;
18396                            for (PackageSetting ps : allPackageSettings) {
18397                                final long status = ps.getDomainVerificationStatusForUser(userId);
18398                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18399                                    continue;
18400                                }
18401                                pw.println(prefix + "Package: " + ps.name);
18402                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18403                                String statusStr = IntentFilterVerificationInfo.
18404                                        getStatusStringFromValue(status);
18405                                pw.println(prefix + "Status:  " + statusStr);
18406                                pw.println();
18407                                count++;
18408                            }
18409                            if (count == 0) {
18410                                pw.println(prefix + "No configured app linkages.");
18411                                pw.println();
18412                            }
18413                        }
18414                    }
18415                }
18416            }
18417
18418            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18419                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18420                if (packageName == null && permissionNames == null) {
18421                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18422                        if (iperm == 0) {
18423                            if (dumpState.onTitlePrinted())
18424                                pw.println();
18425                            pw.println("AppOp Permissions:");
18426                        }
18427                        pw.print("  AppOp Permission ");
18428                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18429                        pw.println(":");
18430                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18431                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18432                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18433                        }
18434                    }
18435                }
18436            }
18437
18438            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18439                boolean printedSomething = false;
18440                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18441                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18442                        continue;
18443                    }
18444                    if (!printedSomething) {
18445                        if (dumpState.onTitlePrinted())
18446                            pw.println();
18447                        pw.println("Registered ContentProviders:");
18448                        printedSomething = true;
18449                    }
18450                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18451                    pw.print("    "); pw.println(p.toString());
18452                }
18453                printedSomething = false;
18454                for (Map.Entry<String, PackageParser.Provider> entry :
18455                        mProvidersByAuthority.entrySet()) {
18456                    PackageParser.Provider p = entry.getValue();
18457                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18458                        continue;
18459                    }
18460                    if (!printedSomething) {
18461                        if (dumpState.onTitlePrinted())
18462                            pw.println();
18463                        pw.println("ContentProvider Authorities:");
18464                        printedSomething = true;
18465                    }
18466                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18467                    pw.print("    "); pw.println(p.toString());
18468                    if (p.info != null && p.info.applicationInfo != null) {
18469                        final String appInfo = p.info.applicationInfo.toString();
18470                        pw.print("      applicationInfo="); pw.println(appInfo);
18471                    }
18472                }
18473            }
18474
18475            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18476                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18477            }
18478
18479            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18480                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18481            }
18482
18483            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18484                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18485            }
18486
18487            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18488                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18489            }
18490
18491            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18492                // XXX should handle packageName != null by dumping only install data that
18493                // the given package is involved with.
18494                if (dumpState.onTitlePrinted()) pw.println();
18495                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18496            }
18497
18498            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18499                // XXX should handle packageName != null by dumping only install data that
18500                // the given package is involved with.
18501                if (dumpState.onTitlePrinted()) pw.println();
18502
18503                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18504                ipw.println();
18505                ipw.println("Frozen packages:");
18506                ipw.increaseIndent();
18507                if (mFrozenPackages.size() == 0) {
18508                    ipw.println("(none)");
18509                } else {
18510                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18511                        ipw.println(mFrozenPackages.valueAt(i));
18512                    }
18513                }
18514                ipw.decreaseIndent();
18515            }
18516
18517            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18518                if (dumpState.onTitlePrinted()) pw.println();
18519                dumpDexoptStateLPr(pw, packageName);
18520            }
18521
18522            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18523                if (dumpState.onTitlePrinted()) pw.println();
18524                mSettings.dumpReadMessagesLPr(pw, dumpState);
18525
18526                pw.println();
18527                pw.println("Package warning messages:");
18528                BufferedReader in = null;
18529                String line = null;
18530                try {
18531                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18532                    while ((line = in.readLine()) != null) {
18533                        if (line.contains("ignored: updated version")) continue;
18534                        pw.println(line);
18535                    }
18536                } catch (IOException ignored) {
18537                } finally {
18538                    IoUtils.closeQuietly(in);
18539                }
18540            }
18541
18542            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18543                BufferedReader in = null;
18544                String line = null;
18545                try {
18546                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18547                    while ((line = in.readLine()) != null) {
18548                        if (line.contains("ignored: updated version")) continue;
18549                        pw.print("msg,");
18550                        pw.println(line);
18551                    }
18552                } catch (IOException ignored) {
18553                } finally {
18554                    IoUtils.closeQuietly(in);
18555                }
18556            }
18557        }
18558    }
18559
18560    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18561        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18562        ipw.println();
18563        ipw.println("Dexopt state:");
18564        ipw.increaseIndent();
18565        Collection<PackageParser.Package> packages = null;
18566        if (packageName != null) {
18567            PackageParser.Package targetPackage = mPackages.get(packageName);
18568            if (targetPackage != null) {
18569                packages = Collections.singletonList(targetPackage);
18570            } else {
18571                ipw.println("Unable to find package: " + packageName);
18572                return;
18573            }
18574        } else {
18575            packages = mPackages.values();
18576        }
18577
18578        for (PackageParser.Package pkg : packages) {
18579            ipw.println("[" + pkg.packageName + "]");
18580            ipw.increaseIndent();
18581            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18582            ipw.decreaseIndent();
18583        }
18584    }
18585
18586    private String dumpDomainString(String packageName) {
18587        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18588                .getList();
18589        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18590
18591        ArraySet<String> result = new ArraySet<>();
18592        if (iviList.size() > 0) {
18593            for (IntentFilterVerificationInfo ivi : iviList) {
18594                for (String host : ivi.getDomains()) {
18595                    result.add(host);
18596                }
18597            }
18598        }
18599        if (filters != null && filters.size() > 0) {
18600            for (IntentFilter filter : filters) {
18601                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18602                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18603                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18604                    result.addAll(filter.getHostsList());
18605                }
18606            }
18607        }
18608
18609        StringBuilder sb = new StringBuilder(result.size() * 16);
18610        for (String domain : result) {
18611            if (sb.length() > 0) sb.append(" ");
18612            sb.append(domain);
18613        }
18614        return sb.toString();
18615    }
18616
18617    // ------- apps on sdcard specific code -------
18618    static final boolean DEBUG_SD_INSTALL = false;
18619
18620    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18621
18622    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18623
18624    private boolean mMediaMounted = false;
18625
18626    static String getEncryptKey() {
18627        try {
18628            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18629                    SD_ENCRYPTION_KEYSTORE_NAME);
18630            if (sdEncKey == null) {
18631                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18632                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18633                if (sdEncKey == null) {
18634                    Slog.e(TAG, "Failed to create encryption keys");
18635                    return null;
18636                }
18637            }
18638            return sdEncKey;
18639        } catch (NoSuchAlgorithmException nsae) {
18640            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18641            return null;
18642        } catch (IOException ioe) {
18643            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18644            return null;
18645        }
18646    }
18647
18648    /*
18649     * Update media status on PackageManager.
18650     */
18651    @Override
18652    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18653        int callingUid = Binder.getCallingUid();
18654        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18655            throw new SecurityException("Media status can only be updated by the system");
18656        }
18657        // reader; this apparently protects mMediaMounted, but should probably
18658        // be a different lock in that case.
18659        synchronized (mPackages) {
18660            Log.i(TAG, "Updating external media status from "
18661                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18662                    + (mediaStatus ? "mounted" : "unmounted"));
18663            if (DEBUG_SD_INSTALL)
18664                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18665                        + ", mMediaMounted=" + mMediaMounted);
18666            if (mediaStatus == mMediaMounted) {
18667                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18668                        : 0, -1);
18669                mHandler.sendMessage(msg);
18670                return;
18671            }
18672            mMediaMounted = mediaStatus;
18673        }
18674        // Queue up an async operation since the package installation may take a
18675        // little while.
18676        mHandler.post(new Runnable() {
18677            public void run() {
18678                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18679            }
18680        });
18681    }
18682
18683    /**
18684     * Called by MountService when the initial ASECs to scan are available.
18685     * Should block until all the ASEC containers are finished being scanned.
18686     */
18687    public void scanAvailableAsecs() {
18688        updateExternalMediaStatusInner(true, false, false);
18689    }
18690
18691    /*
18692     * Collect information of applications on external media, map them against
18693     * existing containers and update information based on current mount status.
18694     * Please note that we always have to report status if reportStatus has been
18695     * set to true especially when unloading packages.
18696     */
18697    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18698            boolean externalStorage) {
18699        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18700        int[] uidArr = EmptyArray.INT;
18701
18702        final String[] list = PackageHelper.getSecureContainerList();
18703        if (ArrayUtils.isEmpty(list)) {
18704            Log.i(TAG, "No secure containers found");
18705        } else {
18706            // Process list of secure containers and categorize them
18707            // as active or stale based on their package internal state.
18708
18709            // reader
18710            synchronized (mPackages) {
18711                for (String cid : list) {
18712                    // Leave stages untouched for now; installer service owns them
18713                    if (PackageInstallerService.isStageName(cid)) continue;
18714
18715                    if (DEBUG_SD_INSTALL)
18716                        Log.i(TAG, "Processing container " + cid);
18717                    String pkgName = getAsecPackageName(cid);
18718                    if (pkgName == null) {
18719                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18720                        continue;
18721                    }
18722                    if (DEBUG_SD_INSTALL)
18723                        Log.i(TAG, "Looking for pkg : " + pkgName);
18724
18725                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18726                    if (ps == null) {
18727                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18728                        continue;
18729                    }
18730
18731                    /*
18732                     * Skip packages that are not external if we're unmounting
18733                     * external storage.
18734                     */
18735                    if (externalStorage && !isMounted && !isExternal(ps)) {
18736                        continue;
18737                    }
18738
18739                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18740                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18741                    // The package status is changed only if the code path
18742                    // matches between settings and the container id.
18743                    if (ps.codePathString != null
18744                            && ps.codePathString.startsWith(args.getCodePath())) {
18745                        if (DEBUG_SD_INSTALL) {
18746                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18747                                    + " at code path: " + ps.codePathString);
18748                        }
18749
18750                        // We do have a valid package installed on sdcard
18751                        processCids.put(args, ps.codePathString);
18752                        final int uid = ps.appId;
18753                        if (uid != -1) {
18754                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18755                        }
18756                    } else {
18757                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18758                                + ps.codePathString);
18759                    }
18760                }
18761            }
18762
18763            Arrays.sort(uidArr);
18764        }
18765
18766        // Process packages with valid entries.
18767        if (isMounted) {
18768            if (DEBUG_SD_INSTALL)
18769                Log.i(TAG, "Loading packages");
18770            loadMediaPackages(processCids, uidArr, externalStorage);
18771            startCleaningPackages();
18772            mInstallerService.onSecureContainersAvailable();
18773        } else {
18774            if (DEBUG_SD_INSTALL)
18775                Log.i(TAG, "Unloading packages");
18776            unloadMediaPackages(processCids, uidArr, reportStatus);
18777        }
18778    }
18779
18780    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18781            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18782        final int size = infos.size();
18783        final String[] packageNames = new String[size];
18784        final int[] packageUids = new int[size];
18785        for (int i = 0; i < size; i++) {
18786            final ApplicationInfo info = infos.get(i);
18787            packageNames[i] = info.packageName;
18788            packageUids[i] = info.uid;
18789        }
18790        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18791                finishedReceiver);
18792    }
18793
18794    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18795            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18796        sendResourcesChangedBroadcast(mediaStatus, replacing,
18797                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18798    }
18799
18800    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18801            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18802        int size = pkgList.length;
18803        if (size > 0) {
18804            // Send broadcasts here
18805            Bundle extras = new Bundle();
18806            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18807            if (uidArr != null) {
18808                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18809            }
18810            if (replacing) {
18811                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18812            }
18813            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18814                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18815            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18816        }
18817    }
18818
18819   /*
18820     * Look at potentially valid container ids from processCids If package
18821     * information doesn't match the one on record or package scanning fails,
18822     * the cid is added to list of removeCids. We currently don't delete stale
18823     * containers.
18824     */
18825    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18826            boolean externalStorage) {
18827        ArrayList<String> pkgList = new ArrayList<String>();
18828        Set<AsecInstallArgs> keys = processCids.keySet();
18829
18830        for (AsecInstallArgs args : keys) {
18831            String codePath = processCids.get(args);
18832            if (DEBUG_SD_INSTALL)
18833                Log.i(TAG, "Loading container : " + args.cid);
18834            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18835            try {
18836                // Make sure there are no container errors first.
18837                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18838                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18839                            + " when installing from sdcard");
18840                    continue;
18841                }
18842                // Check code path here.
18843                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18844                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18845                            + " does not match one in settings " + codePath);
18846                    continue;
18847                }
18848                // Parse package
18849                int parseFlags = mDefParseFlags;
18850                if (args.isExternalAsec()) {
18851                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18852                }
18853                if (args.isFwdLocked()) {
18854                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18855                }
18856
18857                synchronized (mInstallLock) {
18858                    PackageParser.Package pkg = null;
18859                    try {
18860                        // Sadly we don't know the package name yet to freeze it
18861                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18862                                SCAN_IGNORE_FROZEN, 0, null);
18863                    } catch (PackageManagerException e) {
18864                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18865                    }
18866                    // Scan the package
18867                    if (pkg != null) {
18868                        /*
18869                         * TODO why is the lock being held? doPostInstall is
18870                         * called in other places without the lock. This needs
18871                         * to be straightened out.
18872                         */
18873                        // writer
18874                        synchronized (mPackages) {
18875                            retCode = PackageManager.INSTALL_SUCCEEDED;
18876                            pkgList.add(pkg.packageName);
18877                            // Post process args
18878                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18879                                    pkg.applicationInfo.uid);
18880                        }
18881                    } else {
18882                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18883                    }
18884                }
18885
18886            } finally {
18887                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18888                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18889                }
18890            }
18891        }
18892        // writer
18893        synchronized (mPackages) {
18894            // If the platform SDK has changed since the last time we booted,
18895            // we need to re-grant app permission to catch any new ones that
18896            // appear. This is really a hack, and means that apps can in some
18897            // cases get permissions that the user didn't initially explicitly
18898            // allow... it would be nice to have some better way to handle
18899            // this situation.
18900            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18901                    : mSettings.getInternalVersion();
18902            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18903                    : StorageManager.UUID_PRIVATE_INTERNAL;
18904
18905            int updateFlags = UPDATE_PERMISSIONS_ALL;
18906            if (ver.sdkVersion != mSdkVersion) {
18907                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18908                        + mSdkVersion + "; regranting permissions for external");
18909                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18910            }
18911            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18912
18913            // Yay, everything is now upgraded
18914            ver.forceCurrent();
18915
18916            // can downgrade to reader
18917            // Persist settings
18918            mSettings.writeLPr();
18919        }
18920        // Send a broadcast to let everyone know we are done processing
18921        if (pkgList.size() > 0) {
18922            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18923        }
18924    }
18925
18926   /*
18927     * Utility method to unload a list of specified containers
18928     */
18929    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18930        // Just unmount all valid containers.
18931        for (AsecInstallArgs arg : cidArgs) {
18932            synchronized (mInstallLock) {
18933                arg.doPostDeleteLI(false);
18934           }
18935       }
18936   }
18937
18938    /*
18939     * Unload packages mounted on external media. This involves deleting package
18940     * data from internal structures, sending broadcasts about disabled packages,
18941     * gc'ing to free up references, unmounting all secure containers
18942     * corresponding to packages on external media, and posting a
18943     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18944     * that we always have to post this message if status has been requested no
18945     * matter what.
18946     */
18947    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18948            final boolean reportStatus) {
18949        if (DEBUG_SD_INSTALL)
18950            Log.i(TAG, "unloading media packages");
18951        ArrayList<String> pkgList = new ArrayList<String>();
18952        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18953        final Set<AsecInstallArgs> keys = processCids.keySet();
18954        for (AsecInstallArgs args : keys) {
18955            String pkgName = args.getPackageName();
18956            if (DEBUG_SD_INSTALL)
18957                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18958            // Delete package internally
18959            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18960            synchronized (mInstallLock) {
18961                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18962                final boolean res;
18963                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18964                        "unloadMediaPackages")) {
18965                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18966                            null);
18967                }
18968                if (res) {
18969                    pkgList.add(pkgName);
18970                } else {
18971                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18972                    failedList.add(args);
18973                }
18974            }
18975        }
18976
18977        // reader
18978        synchronized (mPackages) {
18979            // We didn't update the settings after removing each package;
18980            // write them now for all packages.
18981            mSettings.writeLPr();
18982        }
18983
18984        // We have to absolutely send UPDATED_MEDIA_STATUS only
18985        // after confirming that all the receivers processed the ordered
18986        // broadcast when packages get disabled, force a gc to clean things up.
18987        // and unload all the containers.
18988        if (pkgList.size() > 0) {
18989            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18990                    new IIntentReceiver.Stub() {
18991                public void performReceive(Intent intent, int resultCode, String data,
18992                        Bundle extras, boolean ordered, boolean sticky,
18993                        int sendingUser) throws RemoteException {
18994                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18995                            reportStatus ? 1 : 0, 1, keys);
18996                    mHandler.sendMessage(msg);
18997                }
18998            });
18999        } else {
19000            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19001                    keys);
19002            mHandler.sendMessage(msg);
19003        }
19004    }
19005
19006    private void loadPrivatePackages(final VolumeInfo vol) {
19007        mHandler.post(new Runnable() {
19008            @Override
19009            public void run() {
19010                loadPrivatePackagesInner(vol);
19011            }
19012        });
19013    }
19014
19015    private void loadPrivatePackagesInner(VolumeInfo vol) {
19016        final String volumeUuid = vol.fsUuid;
19017        if (TextUtils.isEmpty(volumeUuid)) {
19018            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19019            return;
19020        }
19021
19022        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19023        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19024        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19025
19026        final VersionInfo ver;
19027        final List<PackageSetting> packages;
19028        synchronized (mPackages) {
19029            ver = mSettings.findOrCreateVersion(volumeUuid);
19030            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19031        }
19032
19033        for (PackageSetting ps : packages) {
19034            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19035            synchronized (mInstallLock) {
19036                final PackageParser.Package pkg;
19037                try {
19038                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19039                    loaded.add(pkg.applicationInfo);
19040
19041                } catch (PackageManagerException e) {
19042                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19043                }
19044
19045                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19046                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19047                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19048                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19049                }
19050            }
19051        }
19052
19053        // Reconcile app data for all started/unlocked users
19054        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19055        final UserManager um = mContext.getSystemService(UserManager.class);
19056        UserManagerInternal umInternal = getUserManagerInternal();
19057        for (UserInfo user : um.getUsers()) {
19058            final int flags;
19059            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19060                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19061            } else if (umInternal.isUserRunning(user.id)) {
19062                flags = StorageManager.FLAG_STORAGE_DE;
19063            } else {
19064                continue;
19065            }
19066
19067            try {
19068                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19069                synchronized (mInstallLock) {
19070                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19071                }
19072            } catch (IllegalStateException e) {
19073                // Device was probably ejected, and we'll process that event momentarily
19074                Slog.w(TAG, "Failed to prepare storage: " + e);
19075            }
19076        }
19077
19078        synchronized (mPackages) {
19079            int updateFlags = UPDATE_PERMISSIONS_ALL;
19080            if (ver.sdkVersion != mSdkVersion) {
19081                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19082                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19083                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19084            }
19085            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19086
19087            // Yay, everything is now upgraded
19088            ver.forceCurrent();
19089
19090            mSettings.writeLPr();
19091        }
19092
19093        for (PackageFreezer freezer : freezers) {
19094            freezer.close();
19095        }
19096
19097        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19098        sendResourcesChangedBroadcast(true, false, loaded, null);
19099    }
19100
19101    private void unloadPrivatePackages(final VolumeInfo vol) {
19102        mHandler.post(new Runnable() {
19103            @Override
19104            public void run() {
19105                unloadPrivatePackagesInner(vol);
19106            }
19107        });
19108    }
19109
19110    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19111        final String volumeUuid = vol.fsUuid;
19112        if (TextUtils.isEmpty(volumeUuid)) {
19113            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19114            return;
19115        }
19116
19117        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19118        synchronized (mInstallLock) {
19119        synchronized (mPackages) {
19120            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19121            for (PackageSetting ps : packages) {
19122                if (ps.pkg == null) continue;
19123
19124                final ApplicationInfo info = ps.pkg.applicationInfo;
19125                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19126                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19127
19128                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19129                        "unloadPrivatePackagesInner")) {
19130                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19131                            false, null)) {
19132                        unloaded.add(info);
19133                    } else {
19134                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19135                    }
19136                }
19137            }
19138
19139            mSettings.writeLPr();
19140        }
19141        }
19142
19143        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19144        sendResourcesChangedBroadcast(false, false, unloaded, null);
19145    }
19146
19147    /**
19148     * Prepare storage areas for given user on all mounted devices.
19149     */
19150    void prepareUserData(int userId, int userSerial, int flags) {
19151        synchronized (mInstallLock) {
19152            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19153            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19154                final String volumeUuid = vol.getFsUuid();
19155                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19156            }
19157        }
19158    }
19159
19160    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19161            boolean allowRecover) {
19162        // Prepare storage and verify that serial numbers are consistent; if
19163        // there's a mismatch we need to destroy to avoid leaking data
19164        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19165        try {
19166            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19167
19168            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19169                UserManagerService.enforceSerialNumber(
19170                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19171            }
19172            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19173                UserManagerService.enforceSerialNumber(
19174                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19175            }
19176
19177            synchronized (mInstallLock) {
19178                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19179            }
19180        } catch (Exception e) {
19181            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19182                    + " because we failed to prepare: " + e);
19183            destroyUserDataLI(volumeUuid, userId,
19184                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19185
19186            if (allowRecover) {
19187                // Try one last time; if we fail again we're really in trouble
19188                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19189            }
19190        }
19191    }
19192
19193    /**
19194     * Destroy storage areas for given user on all mounted devices.
19195     */
19196    void destroyUserData(int userId, int flags) {
19197        synchronized (mInstallLock) {
19198            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19199            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19200                final String volumeUuid = vol.getFsUuid();
19201                destroyUserDataLI(volumeUuid, userId, flags);
19202            }
19203        }
19204    }
19205
19206    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19207        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19208        try {
19209            // Clean up app data, profile data, and media data
19210            mInstaller.destroyUserData(volumeUuid, userId, flags);
19211
19212            // Clean up system data
19213            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19214                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19215                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19216                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19217                }
19218                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19219                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19220                }
19221            }
19222
19223            // Data with special labels is now gone, so finish the job
19224            storage.destroyUserStorage(volumeUuid, userId, flags);
19225
19226        } catch (Exception e) {
19227            logCriticalInfo(Log.WARN,
19228                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19229        }
19230    }
19231
19232    /**
19233     * Examine all users present on given mounted volume, and destroy data
19234     * belonging to users that are no longer valid, or whose user ID has been
19235     * recycled.
19236     */
19237    private void reconcileUsers(String volumeUuid) {
19238        final List<File> files = new ArrayList<>();
19239        Collections.addAll(files, FileUtils
19240                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19241        Collections.addAll(files, FileUtils
19242                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19243        for (File file : files) {
19244            if (!file.isDirectory()) continue;
19245
19246            final int userId;
19247            final UserInfo info;
19248            try {
19249                userId = Integer.parseInt(file.getName());
19250                info = sUserManager.getUserInfo(userId);
19251            } catch (NumberFormatException e) {
19252                Slog.w(TAG, "Invalid user directory " + file);
19253                continue;
19254            }
19255
19256            boolean destroyUser = false;
19257            if (info == null) {
19258                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19259                        + " because no matching user was found");
19260                destroyUser = true;
19261            } else if (!mOnlyCore) {
19262                try {
19263                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19264                } catch (IOException e) {
19265                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19266                            + " because we failed to enforce serial number: " + e);
19267                    destroyUser = true;
19268                }
19269            }
19270
19271            if (destroyUser) {
19272                synchronized (mInstallLock) {
19273                    destroyUserDataLI(volumeUuid, userId,
19274                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19275                }
19276            }
19277        }
19278    }
19279
19280    private void assertPackageKnown(String volumeUuid, String packageName)
19281            throws PackageManagerException {
19282        synchronized (mPackages) {
19283            final PackageSetting ps = mSettings.mPackages.get(packageName);
19284            if (ps == null) {
19285                throw new PackageManagerException("Package " + packageName + " is unknown");
19286            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19287                throw new PackageManagerException(
19288                        "Package " + packageName + " found on unknown volume " + volumeUuid
19289                                + "; expected volume " + ps.volumeUuid);
19290            }
19291        }
19292    }
19293
19294    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19295            throws PackageManagerException {
19296        synchronized (mPackages) {
19297            final PackageSetting ps = mSettings.mPackages.get(packageName);
19298            if (ps == null) {
19299                throw new PackageManagerException("Package " + packageName + " is unknown");
19300            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19301                throw new PackageManagerException(
19302                        "Package " + packageName + " found on unknown volume " + volumeUuid
19303                                + "; expected volume " + ps.volumeUuid);
19304            } else if (!ps.getInstalled(userId)) {
19305                throw new PackageManagerException(
19306                        "Package " + packageName + " not installed for user " + userId);
19307            }
19308        }
19309    }
19310
19311    /**
19312     * Examine all apps present on given mounted volume, and destroy apps that
19313     * aren't expected, either due to uninstallation or reinstallation on
19314     * another volume.
19315     */
19316    private void reconcileApps(String volumeUuid) {
19317        final File[] files = FileUtils
19318                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19319        for (File file : files) {
19320            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19321                    && !PackageInstallerService.isStageName(file.getName());
19322            if (!isPackage) {
19323                // Ignore entries which are not packages
19324                continue;
19325            }
19326
19327            try {
19328                final PackageLite pkg = PackageParser.parsePackageLite(file,
19329                        PackageParser.PARSE_MUST_BE_APK);
19330                assertPackageKnown(volumeUuid, pkg.packageName);
19331
19332            } catch (PackageParserException | PackageManagerException e) {
19333                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19334                synchronized (mInstallLock) {
19335                    removeCodePathLI(file);
19336                }
19337            }
19338        }
19339    }
19340
19341    /**
19342     * Reconcile all app data for the given user.
19343     * <p>
19344     * Verifies that directories exist and that ownership and labeling is
19345     * correct for all installed apps on all mounted volumes.
19346     */
19347    void reconcileAppsData(int userId, int flags) {
19348        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19349        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19350            final String volumeUuid = vol.getFsUuid();
19351            synchronized (mInstallLock) {
19352                reconcileAppsDataLI(volumeUuid, userId, flags);
19353            }
19354        }
19355    }
19356
19357    /**
19358     * Reconcile all app data on given mounted volume.
19359     * <p>
19360     * Destroys app data that isn't expected, either due to uninstallation or
19361     * reinstallation on another volume.
19362     * <p>
19363     * Verifies that directories exist and that ownership and labeling is
19364     * correct for all installed apps.
19365     */
19366    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19367        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19368                + Integer.toHexString(flags));
19369
19370        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19371        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19372
19373        boolean restoreconNeeded = false;
19374
19375        // First look for stale data that doesn't belong, and check if things
19376        // have changed since we did our last restorecon
19377        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19378            if (StorageManager.isFileEncryptedNativeOrEmulated()
19379                    && !StorageManager.isUserKeyUnlocked(userId)) {
19380                throw new RuntimeException(
19381                        "Yikes, someone asked us to reconcile CE storage while " + userId
19382                                + " was still locked; this would have caused massive data loss!");
19383            }
19384
19385            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19386
19387            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19388            for (File file : files) {
19389                final String packageName = file.getName();
19390                try {
19391                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19392                } catch (PackageManagerException e) {
19393                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19394                    try {
19395                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19396                                StorageManager.FLAG_STORAGE_CE, 0);
19397                    } catch (InstallerException e2) {
19398                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19399                    }
19400                }
19401            }
19402        }
19403        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19404            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19405
19406            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19407            for (File file : files) {
19408                final String packageName = file.getName();
19409                try {
19410                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19411                } catch (PackageManagerException e) {
19412                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19413                    try {
19414                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19415                                StorageManager.FLAG_STORAGE_DE, 0);
19416                    } catch (InstallerException e2) {
19417                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19418                    }
19419                }
19420            }
19421        }
19422
19423        // Ensure that data directories are ready to roll for all packages
19424        // installed for this volume and user
19425        final List<PackageSetting> packages;
19426        synchronized (mPackages) {
19427            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19428        }
19429        int preparedCount = 0;
19430        for (PackageSetting ps : packages) {
19431            final String packageName = ps.name;
19432            if (ps.pkg == null) {
19433                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19434                // TODO: might be due to legacy ASEC apps; we should circle back
19435                // and reconcile again once they're scanned
19436                continue;
19437            }
19438
19439            if (ps.getInstalled(userId)) {
19440                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19441
19442                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19443                    // We may have just shuffled around app data directories, so
19444                    // prepare them one more time
19445                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19446                }
19447
19448                preparedCount++;
19449            }
19450        }
19451
19452        if (restoreconNeeded) {
19453            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19454                SELinuxMMAC.setRestoreconDone(ceDir);
19455            }
19456            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19457                SELinuxMMAC.setRestoreconDone(deDir);
19458            }
19459        }
19460
19461        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19462                + " packages; restoreconNeeded was " + restoreconNeeded);
19463    }
19464
19465    /**
19466     * Prepare app data for the given app just after it was installed or
19467     * upgraded. This method carefully only touches users that it's installed
19468     * for, and it forces a restorecon to handle any seinfo changes.
19469     * <p>
19470     * Verifies that directories exist and that ownership and labeling is
19471     * correct for all installed apps. If there is an ownership mismatch, it
19472     * will try recovering system apps by wiping data; third-party app data is
19473     * left intact.
19474     * <p>
19475     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19476     */
19477    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19478        final PackageSetting ps;
19479        synchronized (mPackages) {
19480            ps = mSettings.mPackages.get(pkg.packageName);
19481            mSettings.writeKernelMappingLPr(ps);
19482        }
19483
19484        final UserManager um = mContext.getSystemService(UserManager.class);
19485        UserManagerInternal umInternal = getUserManagerInternal();
19486        for (UserInfo user : um.getUsers()) {
19487            final int flags;
19488            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19489                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19490            } else if (umInternal.isUserRunning(user.id)) {
19491                flags = StorageManager.FLAG_STORAGE_DE;
19492            } else {
19493                continue;
19494            }
19495
19496            if (ps.getInstalled(user.id)) {
19497                // Whenever an app changes, force a restorecon of its data
19498                // TODO: when user data is locked, mark that we're still dirty
19499                prepareAppDataLIF(pkg, user.id, flags, true);
19500            }
19501        }
19502    }
19503
19504    /**
19505     * Prepare app data for the given app.
19506     * <p>
19507     * Verifies that directories exist and that ownership and labeling is
19508     * correct for all installed apps. If there is an ownership mismatch, this
19509     * will try recovering system apps by wiping data; third-party app data is
19510     * left intact.
19511     */
19512    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19513            boolean restoreconNeeded) {
19514        if (pkg == null) {
19515            Slog.wtf(TAG, "Package was null!", new Throwable());
19516            return;
19517        }
19518        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19519        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19520        for (int i = 0; i < childCount; i++) {
19521            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19522        }
19523    }
19524
19525    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19526            boolean restoreconNeeded) {
19527        if (DEBUG_APP_DATA) {
19528            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19529                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19530        }
19531
19532        final String volumeUuid = pkg.volumeUuid;
19533        final String packageName = pkg.packageName;
19534        final ApplicationInfo app = pkg.applicationInfo;
19535        final int appId = UserHandle.getAppId(app.uid);
19536
19537        Preconditions.checkNotNull(app.seinfo);
19538
19539        try {
19540            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19541                    appId, app.seinfo, app.targetSdkVersion);
19542        } catch (InstallerException e) {
19543            if (app.isSystemApp()) {
19544                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19545                        + ", but trying to recover: " + e);
19546                destroyAppDataLeafLIF(pkg, userId, flags);
19547                try {
19548                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19549                            appId, app.seinfo, app.targetSdkVersion);
19550                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19551                } catch (InstallerException e2) {
19552                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19553                }
19554            } else {
19555                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19556            }
19557        }
19558
19559        if (restoreconNeeded) {
19560            try {
19561                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19562                        app.seinfo);
19563            } catch (InstallerException e) {
19564                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19565            }
19566        }
19567
19568        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19569            try {
19570                // CE storage is unlocked right now, so read out the inode and
19571                // remember for use later when it's locked
19572                // TODO: mark this structure as dirty so we persist it!
19573                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19574                        StorageManager.FLAG_STORAGE_CE);
19575                synchronized (mPackages) {
19576                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19577                    if (ps != null) {
19578                        ps.setCeDataInode(ceDataInode, userId);
19579                    }
19580                }
19581            } catch (InstallerException e) {
19582                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19583            }
19584        }
19585
19586        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19587    }
19588
19589    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19590        if (pkg == null) {
19591            Slog.wtf(TAG, "Package was null!", new Throwable());
19592            return;
19593        }
19594        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19595        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19596        for (int i = 0; i < childCount; i++) {
19597            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19598        }
19599    }
19600
19601    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19602        final String volumeUuid = pkg.volumeUuid;
19603        final String packageName = pkg.packageName;
19604        final ApplicationInfo app = pkg.applicationInfo;
19605
19606        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19607            // Create a native library symlink only if we have native libraries
19608            // and if the native libraries are 32 bit libraries. We do not provide
19609            // this symlink for 64 bit libraries.
19610            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19611                final String nativeLibPath = app.nativeLibraryDir;
19612                try {
19613                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19614                            nativeLibPath, userId);
19615                } catch (InstallerException e) {
19616                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19617                }
19618            }
19619        }
19620    }
19621
19622    /**
19623     * For system apps on non-FBE devices, this method migrates any existing
19624     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19625     * requested by the app.
19626     */
19627    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19628        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19629                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19630            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19631                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19632            try {
19633                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19634                        storageTarget);
19635            } catch (InstallerException e) {
19636                logCriticalInfo(Log.WARN,
19637                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19638            }
19639            return true;
19640        } else {
19641            return false;
19642        }
19643    }
19644
19645    public PackageFreezer freezePackage(String packageName, String killReason) {
19646        return new PackageFreezer(packageName, killReason);
19647    }
19648
19649    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19650            String killReason) {
19651        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19652            return new PackageFreezer();
19653        } else {
19654            return freezePackage(packageName, killReason);
19655        }
19656    }
19657
19658    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19659            String killReason) {
19660        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19661            return new PackageFreezer();
19662        } else {
19663            return freezePackage(packageName, killReason);
19664        }
19665    }
19666
19667    /**
19668     * Class that freezes and kills the given package upon creation, and
19669     * unfreezes it upon closing. This is typically used when doing surgery on
19670     * app code/data to prevent the app from running while you're working.
19671     */
19672    private class PackageFreezer implements AutoCloseable {
19673        private final String mPackageName;
19674        private final PackageFreezer[] mChildren;
19675
19676        private final boolean mWeFroze;
19677
19678        private final AtomicBoolean mClosed = new AtomicBoolean();
19679        private final CloseGuard mCloseGuard = CloseGuard.get();
19680
19681        /**
19682         * Create and return a stub freezer that doesn't actually do anything,
19683         * typically used when someone requested
19684         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19685         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19686         */
19687        public PackageFreezer() {
19688            mPackageName = null;
19689            mChildren = null;
19690            mWeFroze = false;
19691            mCloseGuard.open("close");
19692        }
19693
19694        public PackageFreezer(String packageName, String killReason) {
19695            synchronized (mPackages) {
19696                mPackageName = packageName;
19697                mWeFroze = mFrozenPackages.add(mPackageName);
19698
19699                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19700                if (ps != null) {
19701                    killApplication(ps.name, ps.appId, killReason);
19702                }
19703
19704                final PackageParser.Package p = mPackages.get(packageName);
19705                if (p != null && p.childPackages != null) {
19706                    final int N = p.childPackages.size();
19707                    mChildren = new PackageFreezer[N];
19708                    for (int i = 0; i < N; i++) {
19709                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19710                                killReason);
19711                    }
19712                } else {
19713                    mChildren = null;
19714                }
19715            }
19716            mCloseGuard.open("close");
19717        }
19718
19719        @Override
19720        protected void finalize() throws Throwable {
19721            try {
19722                mCloseGuard.warnIfOpen();
19723                close();
19724            } finally {
19725                super.finalize();
19726            }
19727        }
19728
19729        @Override
19730        public void close() {
19731            mCloseGuard.close();
19732            if (mClosed.compareAndSet(false, true)) {
19733                synchronized (mPackages) {
19734                    if (mWeFroze) {
19735                        mFrozenPackages.remove(mPackageName);
19736                    }
19737
19738                    if (mChildren != null) {
19739                        for (PackageFreezer freezer : mChildren) {
19740                            freezer.close();
19741                        }
19742                    }
19743                }
19744            }
19745        }
19746    }
19747
19748    /**
19749     * Verify that given package is currently frozen.
19750     */
19751    private void checkPackageFrozen(String packageName) {
19752        synchronized (mPackages) {
19753            if (!mFrozenPackages.contains(packageName)) {
19754                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19755            }
19756        }
19757    }
19758
19759    @Override
19760    public int movePackage(final String packageName, final String volumeUuid) {
19761        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19762
19763        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19764        final int moveId = mNextMoveId.getAndIncrement();
19765        mHandler.post(new Runnable() {
19766            @Override
19767            public void run() {
19768                try {
19769                    movePackageInternal(packageName, volumeUuid, moveId, user);
19770                } catch (PackageManagerException e) {
19771                    Slog.w(TAG, "Failed to move " + packageName, e);
19772                    mMoveCallbacks.notifyStatusChanged(moveId,
19773                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19774                }
19775            }
19776        });
19777        return moveId;
19778    }
19779
19780    private void movePackageInternal(final String packageName, final String volumeUuid,
19781            final int moveId, UserHandle user) throws PackageManagerException {
19782        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19783        final PackageManager pm = mContext.getPackageManager();
19784
19785        final boolean currentAsec;
19786        final String currentVolumeUuid;
19787        final File codeFile;
19788        final String installerPackageName;
19789        final String packageAbiOverride;
19790        final int appId;
19791        final String seinfo;
19792        final String label;
19793        final int targetSdkVersion;
19794        final PackageFreezer freezer;
19795        final int[] installedUserIds;
19796
19797        // reader
19798        synchronized (mPackages) {
19799            final PackageParser.Package pkg = mPackages.get(packageName);
19800            final PackageSetting ps = mSettings.mPackages.get(packageName);
19801            if (pkg == null || ps == null) {
19802                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19803            }
19804
19805            if (pkg.applicationInfo.isSystemApp()) {
19806                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19807                        "Cannot move system application");
19808            }
19809
19810            if (pkg.applicationInfo.isExternalAsec()) {
19811                currentAsec = true;
19812                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19813            } else if (pkg.applicationInfo.isForwardLocked()) {
19814                currentAsec = true;
19815                currentVolumeUuid = "forward_locked";
19816            } else {
19817                currentAsec = false;
19818                currentVolumeUuid = ps.volumeUuid;
19819
19820                final File probe = new File(pkg.codePath);
19821                final File probeOat = new File(probe, "oat");
19822                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19823                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19824                            "Move only supported for modern cluster style installs");
19825                }
19826            }
19827
19828            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19829                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19830                        "Package already moved to " + volumeUuid);
19831            }
19832            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19833                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19834                        "Device admin cannot be moved");
19835            }
19836
19837            if (mFrozenPackages.contains(packageName)) {
19838                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19839                        "Failed to move already frozen package");
19840            }
19841
19842            codeFile = new File(pkg.codePath);
19843            installerPackageName = ps.installerPackageName;
19844            packageAbiOverride = ps.cpuAbiOverrideString;
19845            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19846            seinfo = pkg.applicationInfo.seinfo;
19847            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19848            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19849            freezer = new PackageFreezer(packageName, "movePackageInternal");
19850            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
19851        }
19852
19853        final Bundle extras = new Bundle();
19854        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19855        extras.putString(Intent.EXTRA_TITLE, label);
19856        mMoveCallbacks.notifyCreated(moveId, extras);
19857
19858        int installFlags;
19859        final boolean moveCompleteApp;
19860        final File measurePath;
19861
19862        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19863            installFlags = INSTALL_INTERNAL;
19864            moveCompleteApp = !currentAsec;
19865            measurePath = Environment.getDataAppDirectory(volumeUuid);
19866        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19867            installFlags = INSTALL_EXTERNAL;
19868            moveCompleteApp = false;
19869            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19870        } else {
19871            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19872            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19873                    || !volume.isMountedWritable()) {
19874                freezer.close();
19875                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19876                        "Move location not mounted private volume");
19877            }
19878
19879            Preconditions.checkState(!currentAsec);
19880
19881            installFlags = INSTALL_INTERNAL;
19882            moveCompleteApp = true;
19883            measurePath = Environment.getDataAppDirectory(volumeUuid);
19884        }
19885
19886        final PackageStats stats = new PackageStats(null, -1);
19887        synchronized (mInstaller) {
19888            for (int userId : installedUserIds) {
19889                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
19890                    freezer.close();
19891                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19892                            "Failed to measure package size");
19893                }
19894            }
19895        }
19896
19897        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19898                + stats.dataSize);
19899
19900        final long startFreeBytes = measurePath.getFreeSpace();
19901        final long sizeBytes;
19902        if (moveCompleteApp) {
19903            sizeBytes = stats.codeSize + stats.dataSize;
19904        } else {
19905            sizeBytes = stats.codeSize;
19906        }
19907
19908        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19909            freezer.close();
19910            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19911                    "Not enough free space to move");
19912        }
19913
19914        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19915
19916        final CountDownLatch installedLatch = new CountDownLatch(1);
19917        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19918            @Override
19919            public void onUserActionRequired(Intent intent) throws RemoteException {
19920                throw new IllegalStateException();
19921            }
19922
19923            @Override
19924            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19925                    Bundle extras) throws RemoteException {
19926                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19927                        + PackageManager.installStatusToString(returnCode, msg));
19928
19929                installedLatch.countDown();
19930                freezer.close();
19931
19932                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19933                switch (status) {
19934                    case PackageInstaller.STATUS_SUCCESS:
19935                        mMoveCallbacks.notifyStatusChanged(moveId,
19936                                PackageManager.MOVE_SUCCEEDED);
19937                        break;
19938                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19939                        mMoveCallbacks.notifyStatusChanged(moveId,
19940                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19941                        break;
19942                    default:
19943                        mMoveCallbacks.notifyStatusChanged(moveId,
19944                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19945                        break;
19946                }
19947            }
19948        };
19949
19950        final MoveInfo move;
19951        if (moveCompleteApp) {
19952            // Kick off a thread to report progress estimates
19953            new Thread() {
19954                @Override
19955                public void run() {
19956                    while (true) {
19957                        try {
19958                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19959                                break;
19960                            }
19961                        } catch (InterruptedException ignored) {
19962                        }
19963
19964                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19965                        final int progress = 10 + (int) MathUtils.constrain(
19966                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19967                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19968                    }
19969                }
19970            }.start();
19971
19972            final String dataAppName = codeFile.getName();
19973            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19974                    dataAppName, appId, seinfo, targetSdkVersion);
19975        } else {
19976            move = null;
19977        }
19978
19979        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19980
19981        final Message msg = mHandler.obtainMessage(INIT_COPY);
19982        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19983        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19984                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19985                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19986        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19987        msg.obj = params;
19988
19989        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19990                System.identityHashCode(msg.obj));
19991        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19992                System.identityHashCode(msg.obj));
19993
19994        mHandler.sendMessage(msg);
19995    }
19996
19997    @Override
19998    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19999        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20000
20001        final int realMoveId = mNextMoveId.getAndIncrement();
20002        final Bundle extras = new Bundle();
20003        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20004        mMoveCallbacks.notifyCreated(realMoveId, extras);
20005
20006        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20007            @Override
20008            public void onCreated(int moveId, Bundle extras) {
20009                // Ignored
20010            }
20011
20012            @Override
20013            public void onStatusChanged(int moveId, int status, long estMillis) {
20014                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20015            }
20016        };
20017
20018        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20019        storage.setPrimaryStorageUuid(volumeUuid, callback);
20020        return realMoveId;
20021    }
20022
20023    @Override
20024    public int getMoveStatus(int moveId) {
20025        mContext.enforceCallingOrSelfPermission(
20026                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20027        return mMoveCallbacks.mLastStatus.get(moveId);
20028    }
20029
20030    @Override
20031    public void registerMoveCallback(IPackageMoveObserver callback) {
20032        mContext.enforceCallingOrSelfPermission(
20033                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20034        mMoveCallbacks.register(callback);
20035    }
20036
20037    @Override
20038    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20039        mContext.enforceCallingOrSelfPermission(
20040                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20041        mMoveCallbacks.unregister(callback);
20042    }
20043
20044    @Override
20045    public boolean setInstallLocation(int loc) {
20046        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20047                null);
20048        if (getInstallLocation() == loc) {
20049            return true;
20050        }
20051        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20052                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20053            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20054                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20055            return true;
20056        }
20057        return false;
20058   }
20059
20060    @Override
20061    public int getInstallLocation() {
20062        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20063                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20064                PackageHelper.APP_INSTALL_AUTO);
20065    }
20066
20067    /** Called by UserManagerService */
20068    void cleanUpUser(UserManagerService userManager, int userHandle) {
20069        synchronized (mPackages) {
20070            mDirtyUsers.remove(userHandle);
20071            mUserNeedsBadging.delete(userHandle);
20072            mSettings.removeUserLPw(userHandle);
20073            mPendingBroadcasts.remove(userHandle);
20074            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20075            removeUnusedPackagesLPw(userManager, userHandle);
20076        }
20077    }
20078
20079    /**
20080     * We're removing userHandle and would like to remove any downloaded packages
20081     * that are no longer in use by any other user.
20082     * @param userHandle the user being removed
20083     */
20084    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20085        final boolean DEBUG_CLEAN_APKS = false;
20086        int [] users = userManager.getUserIds();
20087        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20088        while (psit.hasNext()) {
20089            PackageSetting ps = psit.next();
20090            if (ps.pkg == null) {
20091                continue;
20092            }
20093            final String packageName = ps.pkg.packageName;
20094            // Skip over if system app
20095            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20096                continue;
20097            }
20098            if (DEBUG_CLEAN_APKS) {
20099                Slog.i(TAG, "Checking package " + packageName);
20100            }
20101            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20102            if (keep) {
20103                if (DEBUG_CLEAN_APKS) {
20104                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20105                }
20106            } else {
20107                for (int i = 0; i < users.length; i++) {
20108                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20109                        keep = true;
20110                        if (DEBUG_CLEAN_APKS) {
20111                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20112                                    + users[i]);
20113                        }
20114                        break;
20115                    }
20116                }
20117            }
20118            if (!keep) {
20119                if (DEBUG_CLEAN_APKS) {
20120                    Slog.i(TAG, "  Removing package " + packageName);
20121                }
20122                mHandler.post(new Runnable() {
20123                    public void run() {
20124                        deletePackageX(packageName, userHandle, 0);
20125                    } //end run
20126                });
20127            }
20128        }
20129    }
20130
20131    /** Called by UserManagerService */
20132    void createNewUser(int userId) {
20133        synchronized (mInstallLock) {
20134            mSettings.createNewUserLI(this, mInstaller, userId);
20135        }
20136        synchronized (mPackages) {
20137            scheduleWritePackageRestrictionsLocked(userId);
20138            scheduleWritePackageListLocked(userId);
20139            applyFactoryDefaultBrowserLPw(userId);
20140            primeDomainVerificationsLPw(userId);
20141        }
20142    }
20143
20144    void onBeforeUserStartUninitialized(final int userId) {
20145        synchronized (mPackages) {
20146            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20147                return;
20148            }
20149        }
20150        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20151        // If permission review for legacy apps is required, we represent
20152        // dagerous permissions for such apps as always granted runtime
20153        // permissions to keep per user flag state whether review is needed.
20154        // Hence, if a new user is added we have to propagate dangerous
20155        // permission grants for these legacy apps.
20156        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20157            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20158                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20159        }
20160    }
20161
20162    @Override
20163    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20164        mContext.enforceCallingOrSelfPermission(
20165                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20166                "Only package verification agents can read the verifier device identity");
20167
20168        synchronized (mPackages) {
20169            return mSettings.getVerifierDeviceIdentityLPw();
20170        }
20171    }
20172
20173    @Override
20174    public void setPermissionEnforced(String permission, boolean enforced) {
20175        // TODO: Now that we no longer change GID for storage, this should to away.
20176        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20177                "setPermissionEnforced");
20178        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20179            synchronized (mPackages) {
20180                if (mSettings.mReadExternalStorageEnforced == null
20181                        || mSettings.mReadExternalStorageEnforced != enforced) {
20182                    mSettings.mReadExternalStorageEnforced = enforced;
20183                    mSettings.writeLPr();
20184                }
20185            }
20186            // kill any non-foreground processes so we restart them and
20187            // grant/revoke the GID.
20188            final IActivityManager am = ActivityManagerNative.getDefault();
20189            if (am != null) {
20190                final long token = Binder.clearCallingIdentity();
20191                try {
20192                    am.killProcessesBelowForeground("setPermissionEnforcement");
20193                } catch (RemoteException e) {
20194                } finally {
20195                    Binder.restoreCallingIdentity(token);
20196                }
20197            }
20198        } else {
20199            throw new IllegalArgumentException("No selective enforcement for " + permission);
20200        }
20201    }
20202
20203    @Override
20204    @Deprecated
20205    public boolean isPermissionEnforced(String permission) {
20206        return true;
20207    }
20208
20209    @Override
20210    public boolean isStorageLow() {
20211        final long token = Binder.clearCallingIdentity();
20212        try {
20213            final DeviceStorageMonitorInternal
20214                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20215            if (dsm != null) {
20216                return dsm.isMemoryLow();
20217            } else {
20218                return false;
20219            }
20220        } finally {
20221            Binder.restoreCallingIdentity(token);
20222        }
20223    }
20224
20225    @Override
20226    public IPackageInstaller getPackageInstaller() {
20227        return mInstallerService;
20228    }
20229
20230    private boolean userNeedsBadging(int userId) {
20231        int index = mUserNeedsBadging.indexOfKey(userId);
20232        if (index < 0) {
20233            final UserInfo userInfo;
20234            final long token = Binder.clearCallingIdentity();
20235            try {
20236                userInfo = sUserManager.getUserInfo(userId);
20237            } finally {
20238                Binder.restoreCallingIdentity(token);
20239            }
20240            final boolean b;
20241            if (userInfo != null && userInfo.isManagedProfile()) {
20242                b = true;
20243            } else {
20244                b = false;
20245            }
20246            mUserNeedsBadging.put(userId, b);
20247            return b;
20248        }
20249        return mUserNeedsBadging.valueAt(index);
20250    }
20251
20252    @Override
20253    public KeySet getKeySetByAlias(String packageName, String alias) {
20254        if (packageName == null || alias == null) {
20255            return null;
20256        }
20257        synchronized(mPackages) {
20258            final PackageParser.Package pkg = mPackages.get(packageName);
20259            if (pkg == null) {
20260                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20261                throw new IllegalArgumentException("Unknown package: " + packageName);
20262            }
20263            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20264            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20265        }
20266    }
20267
20268    @Override
20269    public KeySet getSigningKeySet(String packageName) {
20270        if (packageName == null) {
20271            return null;
20272        }
20273        synchronized(mPackages) {
20274            final PackageParser.Package pkg = mPackages.get(packageName);
20275            if (pkg == null) {
20276                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20277                throw new IllegalArgumentException("Unknown package: " + packageName);
20278            }
20279            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20280                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20281                throw new SecurityException("May not access signing KeySet of other apps.");
20282            }
20283            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20284            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20285        }
20286    }
20287
20288    @Override
20289    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20290        if (packageName == null || ks == null) {
20291            return false;
20292        }
20293        synchronized(mPackages) {
20294            final PackageParser.Package pkg = mPackages.get(packageName);
20295            if (pkg == null) {
20296                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20297                throw new IllegalArgumentException("Unknown package: " + packageName);
20298            }
20299            IBinder ksh = ks.getToken();
20300            if (ksh instanceof KeySetHandle) {
20301                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20302                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20303            }
20304            return false;
20305        }
20306    }
20307
20308    @Override
20309    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20310        if (packageName == null || ks == null) {
20311            return false;
20312        }
20313        synchronized(mPackages) {
20314            final PackageParser.Package pkg = mPackages.get(packageName);
20315            if (pkg == null) {
20316                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20317                throw new IllegalArgumentException("Unknown package: " + packageName);
20318            }
20319            IBinder ksh = ks.getToken();
20320            if (ksh instanceof KeySetHandle) {
20321                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20322                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20323            }
20324            return false;
20325        }
20326    }
20327
20328    private void deletePackageIfUnusedLPr(final String packageName) {
20329        PackageSetting ps = mSettings.mPackages.get(packageName);
20330        if (ps == null) {
20331            return;
20332        }
20333        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20334            // TODO Implement atomic delete if package is unused
20335            // It is currently possible that the package will be deleted even if it is installed
20336            // after this method returns.
20337            mHandler.post(new Runnable() {
20338                public void run() {
20339                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20340                }
20341            });
20342        }
20343    }
20344
20345    /**
20346     * Check and throw if the given before/after packages would be considered a
20347     * downgrade.
20348     */
20349    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20350            throws PackageManagerException {
20351        if (after.versionCode < before.mVersionCode) {
20352            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20353                    "Update version code " + after.versionCode + " is older than current "
20354                    + before.mVersionCode);
20355        } else if (after.versionCode == before.mVersionCode) {
20356            if (after.baseRevisionCode < before.baseRevisionCode) {
20357                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20358                        "Update base revision code " + after.baseRevisionCode
20359                        + " is older than current " + before.baseRevisionCode);
20360            }
20361
20362            if (!ArrayUtils.isEmpty(after.splitNames)) {
20363                for (int i = 0; i < after.splitNames.length; i++) {
20364                    final String splitName = after.splitNames[i];
20365                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20366                    if (j != -1) {
20367                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20368                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20369                                    "Update split " + splitName + " revision code "
20370                                    + after.splitRevisionCodes[i] + " is older than current "
20371                                    + before.splitRevisionCodes[j]);
20372                        }
20373                    }
20374                }
20375            }
20376        }
20377    }
20378
20379    private static class MoveCallbacks extends Handler {
20380        private static final int MSG_CREATED = 1;
20381        private static final int MSG_STATUS_CHANGED = 2;
20382
20383        private final RemoteCallbackList<IPackageMoveObserver>
20384                mCallbacks = new RemoteCallbackList<>();
20385
20386        private final SparseIntArray mLastStatus = new SparseIntArray();
20387
20388        public MoveCallbacks(Looper looper) {
20389            super(looper);
20390        }
20391
20392        public void register(IPackageMoveObserver callback) {
20393            mCallbacks.register(callback);
20394        }
20395
20396        public void unregister(IPackageMoveObserver callback) {
20397            mCallbacks.unregister(callback);
20398        }
20399
20400        @Override
20401        public void handleMessage(Message msg) {
20402            final SomeArgs args = (SomeArgs) msg.obj;
20403            final int n = mCallbacks.beginBroadcast();
20404            for (int i = 0; i < n; i++) {
20405                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20406                try {
20407                    invokeCallback(callback, msg.what, args);
20408                } catch (RemoteException ignored) {
20409                }
20410            }
20411            mCallbacks.finishBroadcast();
20412            args.recycle();
20413        }
20414
20415        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20416                throws RemoteException {
20417            switch (what) {
20418                case MSG_CREATED: {
20419                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20420                    break;
20421                }
20422                case MSG_STATUS_CHANGED: {
20423                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20424                    break;
20425                }
20426            }
20427        }
20428
20429        private void notifyCreated(int moveId, Bundle extras) {
20430            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20431
20432            final SomeArgs args = SomeArgs.obtain();
20433            args.argi1 = moveId;
20434            args.arg2 = extras;
20435            obtainMessage(MSG_CREATED, args).sendToTarget();
20436        }
20437
20438        private void notifyStatusChanged(int moveId, int status) {
20439            notifyStatusChanged(moveId, status, -1);
20440        }
20441
20442        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20443            Slog.v(TAG, "Move " + moveId + " status " + status);
20444
20445            final SomeArgs args = SomeArgs.obtain();
20446            args.argi1 = moveId;
20447            args.argi2 = status;
20448            args.arg3 = estMillis;
20449            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20450
20451            synchronized (mLastStatus) {
20452                mLastStatus.put(moveId, status);
20453            }
20454        }
20455    }
20456
20457    private final static class OnPermissionChangeListeners extends Handler {
20458        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20459
20460        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20461                new RemoteCallbackList<>();
20462
20463        public OnPermissionChangeListeners(Looper looper) {
20464            super(looper);
20465        }
20466
20467        @Override
20468        public void handleMessage(Message msg) {
20469            switch (msg.what) {
20470                case MSG_ON_PERMISSIONS_CHANGED: {
20471                    final int uid = msg.arg1;
20472                    handleOnPermissionsChanged(uid);
20473                } break;
20474            }
20475        }
20476
20477        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20478            mPermissionListeners.register(listener);
20479
20480        }
20481
20482        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20483            mPermissionListeners.unregister(listener);
20484        }
20485
20486        public void onPermissionsChanged(int uid) {
20487            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20488                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20489            }
20490        }
20491
20492        private void handleOnPermissionsChanged(int uid) {
20493            final int count = mPermissionListeners.beginBroadcast();
20494            try {
20495                for (int i = 0; i < count; i++) {
20496                    IOnPermissionsChangeListener callback = mPermissionListeners
20497                            .getBroadcastItem(i);
20498                    try {
20499                        callback.onPermissionsChanged(uid);
20500                    } catch (RemoteException e) {
20501                        Log.e(TAG, "Permission listener is dead", e);
20502                    }
20503                }
20504            } finally {
20505                mPermissionListeners.finishBroadcast();
20506            }
20507        }
20508    }
20509
20510    private class PackageManagerInternalImpl extends PackageManagerInternal {
20511        @Override
20512        public void setLocationPackagesProvider(PackagesProvider provider) {
20513            synchronized (mPackages) {
20514                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20515            }
20516        }
20517
20518        @Override
20519        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20520            synchronized (mPackages) {
20521                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20522            }
20523        }
20524
20525        @Override
20526        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20527            synchronized (mPackages) {
20528                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20529            }
20530        }
20531
20532        @Override
20533        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20534            synchronized (mPackages) {
20535                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20536            }
20537        }
20538
20539        @Override
20540        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20541            synchronized (mPackages) {
20542                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20543            }
20544        }
20545
20546        @Override
20547        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20548            synchronized (mPackages) {
20549                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20550            }
20551        }
20552
20553        @Override
20554        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20555            synchronized (mPackages) {
20556                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20557                        packageName, userId);
20558            }
20559        }
20560
20561        @Override
20562        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20563            synchronized (mPackages) {
20564                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20565                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20566                        packageName, userId);
20567            }
20568        }
20569
20570        @Override
20571        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20572            synchronized (mPackages) {
20573                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20574                        packageName, userId);
20575            }
20576        }
20577
20578        @Override
20579        public void setKeepUninstalledPackages(final List<String> packageList) {
20580            Preconditions.checkNotNull(packageList);
20581            List<String> removedFromList = null;
20582            synchronized (mPackages) {
20583                if (mKeepUninstalledPackages != null) {
20584                    final int packagesCount = mKeepUninstalledPackages.size();
20585                    for (int i = 0; i < packagesCount; i++) {
20586                        String oldPackage = mKeepUninstalledPackages.get(i);
20587                        if (packageList != null && packageList.contains(oldPackage)) {
20588                            continue;
20589                        }
20590                        if (removedFromList == null) {
20591                            removedFromList = new ArrayList<>();
20592                        }
20593                        removedFromList.add(oldPackage);
20594                    }
20595                }
20596                mKeepUninstalledPackages = new ArrayList<>(packageList);
20597                if (removedFromList != null) {
20598                    final int removedCount = removedFromList.size();
20599                    for (int i = 0; i < removedCount; i++) {
20600                        deletePackageIfUnusedLPr(removedFromList.get(i));
20601                    }
20602                }
20603            }
20604        }
20605
20606        @Override
20607        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20608            synchronized (mPackages) {
20609                // If we do not support permission review, done.
20610                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20611                    return false;
20612                }
20613
20614                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20615                if (packageSetting == null) {
20616                    return false;
20617                }
20618
20619                // Permission review applies only to apps not supporting the new permission model.
20620                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20621                    return false;
20622                }
20623
20624                // Legacy apps have the permission and get user consent on launch.
20625                PermissionsState permissionsState = packageSetting.getPermissionsState();
20626                return permissionsState.isPermissionReviewRequired(userId);
20627            }
20628        }
20629
20630        @Override
20631        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20632            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20633        }
20634
20635        @Override
20636        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20637                int userId) {
20638            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20639        }
20640    }
20641
20642    @Override
20643    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20644        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20645        synchronized (mPackages) {
20646            final long identity = Binder.clearCallingIdentity();
20647            try {
20648                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20649                        packageNames, userId);
20650            } finally {
20651                Binder.restoreCallingIdentity(identity);
20652            }
20653        }
20654    }
20655
20656    private static void enforceSystemOrPhoneCaller(String tag) {
20657        int callingUid = Binder.getCallingUid();
20658        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20659            throw new SecurityException(
20660                    "Cannot call " + tag + " from UID " + callingUid);
20661        }
20662    }
20663
20664    boolean isHistoricalPackageUsageAvailable() {
20665        return mPackageUsage.isHistoricalPackageUsageAvailable();
20666    }
20667
20668    /**
20669     * Return a <b>copy</b> of the collection of packages known to the package manager.
20670     * @return A copy of the values of mPackages.
20671     */
20672    Collection<PackageParser.Package> getPackages() {
20673        synchronized (mPackages) {
20674            return new ArrayList<>(mPackages.values());
20675        }
20676    }
20677
20678    /**
20679     * Logs process start information (including base APK hash) to the security log.
20680     * @hide
20681     */
20682    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20683            String apkFile, int pid) {
20684        if (!SecurityLog.isLoggingEnabled()) {
20685            return;
20686        }
20687        Bundle data = new Bundle();
20688        data.putLong("startTimestamp", System.currentTimeMillis());
20689        data.putString("processName", processName);
20690        data.putInt("uid", uid);
20691        data.putString("seinfo", seinfo);
20692        data.putString("apkFile", apkFile);
20693        data.putInt("pid", pid);
20694        Message msg = mProcessLoggingHandler.obtainMessage(
20695                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20696        msg.setData(data);
20697        mProcessLoggingHandler.sendMessage(msg);
20698    }
20699}
20700