PackageManagerService.java revision b45d9833aa3e8bbfdb819c7bcd104c95c8424f05
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.INetworkPolicyManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.security.KeyStore;
201import android.security.SystemKeyStore;
202import android.system.ErrnoException;
203import android.system.Os;
204import android.text.TextUtils;
205import android.text.format.DateUtils;
206import android.util.ArrayMap;
207import android.util.ArraySet;
208import android.util.AtomicFile;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.PrintStreamPrinter;
216import android.util.Slog;
217import android.util.SparseArray;
218import android.util.SparseBooleanArray;
219import android.util.SparseIntArray;
220import android.util.Xml;
221import android.util.jar.StrictJarFile;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.logging.MetricsLogger;
231import com.android.internal.os.IParcelFileDescriptorFactory;
232import com.android.internal.os.InstallerConnection.InstallerException;
233import com.android.internal.os.SomeArgs;
234import com.android.internal.os.Zygote;
235import com.android.internal.telephony.CarrierAppUtils;
236import com.android.internal.util.ArrayUtils;
237import com.android.internal.util.FastPrintWriter;
238import com.android.internal.util.FastXmlSerializer;
239import com.android.internal.util.IndentingPrintWriter;
240import com.android.internal.util.Preconditions;
241import com.android.internal.util.XmlUtils;
242import com.android.server.EventLogTags;
243import com.android.server.FgThread;
244import com.android.server.IntentResolver;
245import com.android.server.LocalServices;
246import com.android.server.ServiceThread;
247import com.android.server.SystemConfig;
248import com.android.server.Watchdog;
249import com.android.server.net.NetworkPolicyManagerInternal;
250import com.android.server.pm.PermissionsState.PermissionState;
251import com.android.server.pm.Settings.DatabaseVersion;
252import com.android.server.pm.Settings.VersionInfo;
253import com.android.server.storage.DeviceStorageMonitorInternal;
254
255import dalvik.system.CloseGuard;
256import dalvik.system.DexFile;
257import dalvik.system.VMRuntime;
258
259import libcore.io.IoUtils;
260import libcore.util.EmptyArray;
261
262import org.xmlpull.v1.XmlPullParser;
263import org.xmlpull.v1.XmlPullParserException;
264import org.xmlpull.v1.XmlSerializer;
265
266import java.io.BufferedInputStream;
267import java.io.BufferedOutputStream;
268import java.io.BufferedReader;
269import java.io.ByteArrayInputStream;
270import java.io.ByteArrayOutputStream;
271import java.io.File;
272import java.io.FileDescriptor;
273import java.io.FileInputStream;
274import java.io.FileNotFoundException;
275import java.io.FileOutputStream;
276import java.io.FileReader;
277import java.io.FilenameFilter;
278import java.io.IOException;
279import java.io.InputStream;
280import java.io.PrintWriter;
281import java.nio.charset.StandardCharsets;
282import java.security.DigestInputStream;
283import java.security.MessageDigest;
284import java.security.NoSuchAlgorithmException;
285import java.security.PublicKey;
286import java.security.cert.Certificate;
287import java.security.cert.CertificateEncodingException;
288import java.security.cert.CertificateException;
289import java.text.SimpleDateFormat;
290import java.util.ArrayList;
291import java.util.Arrays;
292import java.util.Collection;
293import java.util.Collections;
294import java.util.Comparator;
295import java.util.Date;
296import java.util.HashSet;
297import java.util.Iterator;
298import java.util.List;
299import java.util.Map;
300import java.util.Objects;
301import java.util.Set;
302import java.util.concurrent.CountDownLatch;
303import java.util.concurrent.TimeUnit;
304import java.util.concurrent.atomic.AtomicBoolean;
305import java.util.concurrent.atomic.AtomicInteger;
306import java.util.concurrent.atomic.AtomicLong;
307
308/**
309 * Keep track of all those APKs everywhere.
310 * <p>
311 * Internally there are two important locks:
312 * <ul>
313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
314 * and other related state. It is a fine-grained lock that should only be held
315 * momentarily, as it's one of the most contended locks in the system.
316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
317 * operations typically involve heavy lifting of application data on disk. Since
318 * {@code installd} is single-threaded, and it's operations can often be slow,
319 * this lock should never be acquired while already holding {@link #mPackages}.
320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
321 * holding {@link #mInstallLock}.
322 * </ul>
323 * Many internal methods rely on the caller to hold the appropriate locks, and
324 * this contract is expressed through method name suffixes:
325 * <ul>
326 * <li>fooLI(): the caller must hold {@link #mInstallLock}
327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
328 * being modified must be frozen
329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
331 * </ul>
332 * <p>
333 * Because this class is very central to the platform's security; please run all
334 * CTS and unit tests whenever making modifications:
335 *
336 * <pre>
337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
339 * </pre>
340 */
341public class PackageManagerService extends IPackageManager.Stub {
342    static final String TAG = "PackageManager";
343    static final boolean DEBUG_SETTINGS = false;
344    static final boolean DEBUG_PREFERRED = false;
345    static final boolean DEBUG_UPGRADE = false;
346    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
347    private static final boolean DEBUG_BACKUP = false;
348    private static final boolean DEBUG_INSTALL = false;
349    private static final boolean DEBUG_REMOVE = false;
350    private static final boolean DEBUG_BROADCASTS = false;
351    private static final boolean DEBUG_SHOW_INFO = false;
352    private static final boolean DEBUG_PACKAGE_INFO = false;
353    private static final boolean DEBUG_INTENT_MATCHING = false;
354    private static final boolean DEBUG_PACKAGE_SCANNING = false;
355    private static final boolean DEBUG_VERIFY = false;
356    private static final boolean DEBUG_FILTERS = false;
357
358    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
359    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
360    // user, but by default initialize to this.
361    static final boolean DEBUG_DEXOPT = false;
362
363    private static final boolean DEBUG_ABI_SELECTION = false;
364    private static final boolean DEBUG_EPHEMERAL = false;
365    private static final boolean DEBUG_TRIAGED_MISSING = false;
366    private static final boolean DEBUG_APP_DATA = false;
367
368    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
369
370    private static final boolean DISABLE_EPHEMERAL_APPS = true;
371
372    private static final int RADIO_UID = Process.PHONE_UID;
373    private static final int LOG_UID = Process.LOG_UID;
374    private static final int NFC_UID = Process.NFC_UID;
375    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
376    private static final int SHELL_UID = Process.SHELL_UID;
377
378    // Cap the size of permission trees that 3rd party apps can define
379    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
380
381    // Suffix used during package installation when copying/moving
382    // package apks to install directory.
383    private static final String INSTALL_PACKAGE_SUFFIX = "-";
384
385    static final int SCAN_NO_DEX = 1<<1;
386    static final int SCAN_FORCE_DEX = 1<<2;
387    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
388    static final int SCAN_NEW_INSTALL = 1<<4;
389    static final int SCAN_NO_PATHS = 1<<5;
390    static final int SCAN_UPDATE_TIME = 1<<6;
391    static final int SCAN_DEFER_DEX = 1<<7;
392    static final int SCAN_BOOTING = 1<<8;
393    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
394    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
395    static final int SCAN_REPLACING = 1<<11;
396    static final int SCAN_REQUIRE_KNOWN = 1<<12;
397    static final int SCAN_MOVE = 1<<13;
398    static final int SCAN_INITIAL = 1<<14;
399    static final int SCAN_CHECK_ONLY = 1<<15;
400    static final int SCAN_DONT_KILL_APP = 1<<17;
401    static final int SCAN_IGNORE_FROZEN = 1<<18;
402
403    static final int REMOVE_CHATTY = 1<<16;
404
405    private static final int[] EMPTY_INT_ARRAY = new int[0];
406
407    /**
408     * Timeout (in milliseconds) after which the watchdog should declare that
409     * our handler thread is wedged.  The usual default for such things is one
410     * minute but we sometimes do very lengthy I/O operations on this thread,
411     * such as installing multi-gigabyte applications, so ours needs to be longer.
412     */
413    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
414
415    /**
416     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
417     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
418     * settings entry if available, otherwise we use the hardcoded default.  If it's been
419     * more than this long since the last fstrim, we force one during the boot sequence.
420     *
421     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
422     * one gets run at the next available charging+idle time.  This final mandatory
423     * no-fstrim check kicks in only of the other scheduling criteria is never met.
424     */
425    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
426
427    /**
428     * Whether verification is enabled by default.
429     */
430    private static final boolean DEFAULT_VERIFY_ENABLE = true;
431
432    /**
433     * The default maximum time to wait for the verification agent to return in
434     * milliseconds.
435     */
436    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
437
438    /**
439     * The default response for package verification timeout.
440     *
441     * This can be either PackageManager.VERIFICATION_ALLOW or
442     * PackageManager.VERIFICATION_REJECT.
443     */
444    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
445
446    static final String PLATFORM_PACKAGE_NAME = "android";
447
448    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
449
450    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
451            DEFAULT_CONTAINER_PACKAGE,
452            "com.android.defcontainer.DefaultContainerService");
453
454    private static final String KILL_APP_REASON_GIDS_CHANGED =
455            "permission grant or revoke changed gids";
456
457    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
458            "permissions revoked";
459
460    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
461
462    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
463
464    /** Permission grant: not grant the permission. */
465    private static final int GRANT_DENIED = 1;
466
467    /** Permission grant: grant the permission as an install permission. */
468    private static final int GRANT_INSTALL = 2;
469
470    /** Permission grant: grant the permission as a runtime one. */
471    private static final int GRANT_RUNTIME = 3;
472
473    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
474    private static final int GRANT_UPGRADE = 4;
475
476    /** Canonical intent used to identify what counts as a "web browser" app */
477    private static final Intent sBrowserIntent;
478    static {
479        sBrowserIntent = new Intent();
480        sBrowserIntent.setAction(Intent.ACTION_VIEW);
481        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
482        sBrowserIntent.setData(Uri.parse("http:"));
483    }
484
485    /**
486     * The set of all protected actions [i.e. those actions for which a high priority
487     * intent filter is disallowed].
488     */
489    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
490    static {
491        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
492        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
494        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
495    }
496
497    // Compilation reasons.
498    public static final int REASON_FIRST_BOOT = 0;
499    public static final int REASON_BOOT = 1;
500    public static final int REASON_INSTALL = 2;
501    public static final int REASON_BACKGROUND_DEXOPT = 3;
502    public static final int REASON_AB_OTA = 4;
503    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
504    public static final int REASON_SHARED_APK = 6;
505    public static final int REASON_FORCED_DEXOPT = 7;
506
507    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
508
509    /** Special library name that skips shared libraries check during compilation. */
510    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
511
512    final ServiceThread mHandlerThread;
513
514    final PackageHandler mHandler;
515
516    private final ProcessLoggingHandler mProcessLoggingHandler;
517
518    /**
519     * Messages for {@link #mHandler} that need to wait for system ready before
520     * being dispatched.
521     */
522    private ArrayList<Message> mPostSystemReadyMessages;
523
524    final int mSdkVersion = Build.VERSION.SDK_INT;
525
526    final Context mContext;
527    final boolean mFactoryTest;
528    final boolean mOnlyCore;
529    final DisplayMetrics mMetrics;
530    final int mDefParseFlags;
531    final String[] mSeparateProcesses;
532    final boolean mIsUpgrade;
533    final boolean mIsPreNUpgrade;
534
535    /** The location for ASEC container files on internal storage. */
536    final String mAsecInternalPath;
537
538    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
539    // LOCK HELD.  Can be called with mInstallLock held.
540    @GuardedBy("mInstallLock")
541    final Installer mInstaller;
542
543    /** Directory where installed third-party apps stored */
544    final File mAppInstallDir;
545    final File mEphemeralInstallDir;
546
547    /**
548     * Directory to which applications installed internally have their
549     * 32 bit native libraries copied.
550     */
551    private File mAppLib32InstallDir;
552
553    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
554    // apps.
555    final File mDrmAppPrivateInstallDir;
556
557    // ----------------------------------------------------------------
558
559    // Lock for state used when installing and doing other long running
560    // operations.  Methods that must be called with this lock held have
561    // the suffix "LI".
562    final Object mInstallLock = new Object();
563
564    // ----------------------------------------------------------------
565
566    // Keys are String (package name), values are Package.  This also serves
567    // as the lock for the global state.  Methods that must be called with
568    // this lock held have the prefix "LP".
569    @GuardedBy("mPackages")
570    final ArrayMap<String, PackageParser.Package> mPackages =
571            new ArrayMap<String, PackageParser.Package>();
572
573    final ArrayMap<String, Set<String>> mKnownCodebase =
574            new ArrayMap<String, Set<String>>();
575
576    // Tracks available target package names -> overlay package paths.
577    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
578        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
579
580    /**
581     * Tracks new system packages [received in an OTA] that we expect to
582     * find updated user-installed versions. Keys are package name, values
583     * are package location.
584     */
585    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
586    /**
587     * Tracks high priority intent filters for protected actions. During boot, certain
588     * filter actions are protected and should never be allowed to have a high priority
589     * intent filter for them. However, there is one, and only one exception -- the
590     * setup wizard. It must be able to define a high priority intent filter for these
591     * actions to ensure there are no escapes from the wizard. We need to delay processing
592     * of these during boot as we need to look at all of the system packages in order
593     * to know which component is the setup wizard.
594     */
595    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
596    /**
597     * Whether or not processing protected filters should be deferred.
598     */
599    private boolean mDeferProtectedFilters = true;
600
601    /**
602     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
603     */
604    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
605    /**
606     * Whether or not system app permissions should be promoted from install to runtime.
607     */
608    boolean mPromoteSystemApps;
609
610    @GuardedBy("mPackages")
611    final Settings mSettings;
612
613    /**
614     * Set of package names that are currently "frozen", which means active
615     * surgery is being done on the code/data for that package. The platform
616     * will refuse to launch frozen packages to avoid race conditions.
617     *
618     * @see PackageFreezer
619     */
620    @GuardedBy("mPackages")
621    final ArraySet<String> mFrozenPackages = new ArraySet<>();
622
623    boolean mRestoredSettings;
624
625    // System configuration read by SystemConfig.
626    final int[] mGlobalGids;
627    final SparseArray<ArraySet<String>> mSystemPermissions;
628    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
629
630    // If mac_permissions.xml was found for seinfo labeling.
631    boolean mFoundPolicyFile;
632
633    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
634
635    public static final class SharedLibraryEntry {
636        public final String path;
637        public final String apk;
638
639        SharedLibraryEntry(String _path, String _apk) {
640            path = _path;
641            apk = _apk;
642        }
643    }
644
645    // Currently known shared libraries.
646    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
647            new ArrayMap<String, SharedLibraryEntry>();
648
649    // All available activities, for your resolving pleasure.
650    final ActivityIntentResolver mActivities =
651            new ActivityIntentResolver();
652
653    // All available receivers, for your resolving pleasure.
654    final ActivityIntentResolver mReceivers =
655            new ActivityIntentResolver();
656
657    // All available services, for your resolving pleasure.
658    final ServiceIntentResolver mServices = new ServiceIntentResolver();
659
660    // All available providers, for your resolving pleasure.
661    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
662
663    // Mapping from provider base names (first directory in content URI codePath)
664    // to the provider information.
665    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
666            new ArrayMap<String, PackageParser.Provider>();
667
668    // Mapping from instrumentation class names to info about them.
669    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
670            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
671
672    // Mapping from permission names to info about them.
673    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
674            new ArrayMap<String, PackageParser.PermissionGroup>();
675
676    // Packages whose data we have transfered into another package, thus
677    // should no longer exist.
678    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
679
680    // Broadcast actions that are only available to the system.
681    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
682
683    /** List of packages waiting for verification. */
684    final SparseArray<PackageVerificationState> mPendingVerification
685            = new SparseArray<PackageVerificationState>();
686
687    /** Set of packages associated with each app op permission. */
688    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
689
690    final PackageInstallerService mInstallerService;
691
692    private final PackageDexOptimizer mPackageDexOptimizer;
693
694    private AtomicInteger mNextMoveId = new AtomicInteger();
695    private final MoveCallbacks mMoveCallbacks;
696
697    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
698
699    // Cache of users who need badging.
700    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
701
702    /** Token for keys in mPendingVerification. */
703    private int mPendingVerificationToken = 0;
704
705    volatile boolean mSystemReady;
706    volatile boolean mSafeMode;
707    volatile boolean mHasSystemUidErrors;
708
709    ApplicationInfo mAndroidApplication;
710    final ActivityInfo mResolveActivity = new ActivityInfo();
711    final ResolveInfo mResolveInfo = new ResolveInfo();
712    ComponentName mResolveComponentName;
713    PackageParser.Package mPlatformPackage;
714    ComponentName mCustomResolverComponentName;
715
716    boolean mResolverReplaced = false;
717
718    private final @Nullable ComponentName mIntentFilterVerifierComponent;
719    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
720
721    private int mIntentFilterVerificationToken = 0;
722
723    /** Component that knows whether or not an ephemeral application exists */
724    final ComponentName mEphemeralResolverComponent;
725    /** The service connection to the ephemeral resolver */
726    final EphemeralResolverConnection mEphemeralResolverConnection;
727
728    /** Component used to install ephemeral applications */
729    final ComponentName mEphemeralInstallerComponent;
730    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
731    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
732
733    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
734            = new SparseArray<IntentFilterVerificationState>();
735
736    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
737            new DefaultPermissionGrantPolicy(this);
738
739    // List of packages names to keep cached, even if they are uninstalled for all users
740    private List<String> mKeepUninstalledPackages;
741
742    private UserManagerInternal mUserManagerInternal;
743
744    private static class IFVerificationParams {
745        PackageParser.Package pkg;
746        boolean replacing;
747        int userId;
748        int verifierUid;
749
750        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
751                int _userId, int _verifierUid) {
752            pkg = _pkg;
753            replacing = _replacing;
754            userId = _userId;
755            replacing = _replacing;
756            verifierUid = _verifierUid;
757        }
758    }
759
760    private interface IntentFilterVerifier<T extends IntentFilter> {
761        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
762                                               T filter, String packageName);
763        void startVerifications(int userId);
764        void receiveVerificationResponse(int verificationId);
765    }
766
767    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
768        private Context mContext;
769        private ComponentName mIntentFilterVerifierComponent;
770        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
771
772        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
773            mContext = context;
774            mIntentFilterVerifierComponent = verifierComponent;
775        }
776
777        private String getDefaultScheme() {
778            return IntentFilter.SCHEME_HTTPS;
779        }
780
781        @Override
782        public void startVerifications(int userId) {
783            // Launch verifications requests
784            int count = mCurrentIntentFilterVerifications.size();
785            for (int n=0; n<count; n++) {
786                int verificationId = mCurrentIntentFilterVerifications.get(n);
787                final IntentFilterVerificationState ivs =
788                        mIntentFilterVerificationStates.get(verificationId);
789
790                String packageName = ivs.getPackageName();
791
792                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
793                final int filterCount = filters.size();
794                ArraySet<String> domainsSet = new ArraySet<>();
795                for (int m=0; m<filterCount; m++) {
796                    PackageParser.ActivityIntentInfo filter = filters.get(m);
797                    domainsSet.addAll(filter.getHostsList());
798                }
799                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
800                synchronized (mPackages) {
801                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
802                            packageName, domainsList) != null) {
803                        scheduleWriteSettingsLocked();
804                    }
805                }
806                sendVerificationRequest(userId, verificationId, ivs);
807            }
808            mCurrentIntentFilterVerifications.clear();
809        }
810
811        private void sendVerificationRequest(int userId, int verificationId,
812                IntentFilterVerificationState ivs) {
813
814            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
815            verificationIntent.putExtra(
816                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
817                    verificationId);
818            verificationIntent.putExtra(
819                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
820                    getDefaultScheme());
821            verificationIntent.putExtra(
822                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
823                    ivs.getHostsString());
824            verificationIntent.putExtra(
825                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
826                    ivs.getPackageName());
827            verificationIntent.setComponent(mIntentFilterVerifierComponent);
828            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
829
830            UserHandle user = new UserHandle(userId);
831            mContext.sendBroadcastAsUser(verificationIntent, user);
832            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
833                    "Sending IntentFilter verification broadcast");
834        }
835
836        public void receiveVerificationResponse(int verificationId) {
837            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
838
839            final boolean verified = ivs.isVerified();
840
841            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
842            final int count = filters.size();
843            if (DEBUG_DOMAIN_VERIFICATION) {
844                Slog.i(TAG, "Received verification response " + verificationId
845                        + " for " + count + " filters, verified=" + verified);
846            }
847            for (int n=0; n<count; n++) {
848                PackageParser.ActivityIntentInfo filter = filters.get(n);
849                filter.setVerified(verified);
850
851                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
852                        + " verified with result:" + verified + " and hosts:"
853                        + ivs.getHostsString());
854            }
855
856            mIntentFilterVerificationStates.remove(verificationId);
857
858            final String packageName = ivs.getPackageName();
859            IntentFilterVerificationInfo ivi = null;
860
861            synchronized (mPackages) {
862                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
863            }
864            if (ivi == null) {
865                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
866                        + verificationId + " packageName:" + packageName);
867                return;
868            }
869            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
870                    "Updating IntentFilterVerificationInfo for package " + packageName
871                            +" verificationId:" + verificationId);
872
873            synchronized (mPackages) {
874                if (verified) {
875                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
876                } else {
877                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
878                }
879                scheduleWriteSettingsLocked();
880
881                final int userId = ivs.getUserId();
882                if (userId != UserHandle.USER_ALL) {
883                    final int userStatus =
884                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
885
886                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
887                    boolean needUpdate = false;
888
889                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
890                    // already been set by the User thru the Disambiguation dialog
891                    switch (userStatus) {
892                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
893                            if (verified) {
894                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
895                            } else {
896                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
897                            }
898                            needUpdate = true;
899                            break;
900
901                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
902                            if (verified) {
903                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
904                                needUpdate = true;
905                            }
906                            break;
907
908                        default:
909                            // Nothing to do
910                    }
911
912                    if (needUpdate) {
913                        mSettings.updateIntentFilterVerificationStatusLPw(
914                                packageName, updatedStatus, userId);
915                        scheduleWritePackageRestrictionsLocked(userId);
916                    }
917                }
918            }
919        }
920
921        @Override
922        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
923                    ActivityIntentInfo filter, String packageName) {
924            if (!hasValidDomains(filter)) {
925                return false;
926            }
927            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
928            if (ivs == null) {
929                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
930                        packageName);
931            }
932            if (DEBUG_DOMAIN_VERIFICATION) {
933                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
934            }
935            ivs.addFilter(filter);
936            return true;
937        }
938
939        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
940                int userId, int verificationId, String packageName) {
941            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
942                    verifierUid, userId, packageName);
943            ivs.setPendingState();
944            synchronized (mPackages) {
945                mIntentFilterVerificationStates.append(verificationId, ivs);
946                mCurrentIntentFilterVerifications.add(verificationId);
947            }
948            return ivs;
949        }
950    }
951
952    private static boolean hasValidDomains(ActivityIntentInfo filter) {
953        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
954                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
955                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
956    }
957
958    // Set of pending broadcasts for aggregating enable/disable of components.
959    static class PendingPackageBroadcasts {
960        // for each user id, a map of <package name -> components within that package>
961        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
962
963        public PendingPackageBroadcasts() {
964            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
965        }
966
967        public ArrayList<String> get(int userId, String packageName) {
968            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
969            return packages.get(packageName);
970        }
971
972        public void put(int userId, String packageName, ArrayList<String> components) {
973            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
974            packages.put(packageName, components);
975        }
976
977        public void remove(int userId, String packageName) {
978            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
979            if (packages != null) {
980                packages.remove(packageName);
981            }
982        }
983
984        public void remove(int userId) {
985            mUidMap.remove(userId);
986        }
987
988        public int userIdCount() {
989            return mUidMap.size();
990        }
991
992        public int userIdAt(int n) {
993            return mUidMap.keyAt(n);
994        }
995
996        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
997            return mUidMap.get(userId);
998        }
999
1000        public int size() {
1001            // total number of pending broadcast entries across all userIds
1002            int num = 0;
1003            for (int i = 0; i< mUidMap.size(); i++) {
1004                num += mUidMap.valueAt(i).size();
1005            }
1006            return num;
1007        }
1008
1009        public void clear() {
1010            mUidMap.clear();
1011        }
1012
1013        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1014            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1015            if (map == null) {
1016                map = new ArrayMap<String, ArrayList<String>>();
1017                mUidMap.put(userId, map);
1018            }
1019            return map;
1020        }
1021    }
1022    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1023
1024    // Service Connection to remote media container service to copy
1025    // package uri's from external media onto secure containers
1026    // or internal storage.
1027    private IMediaContainerService mContainerService = null;
1028
1029    static final int SEND_PENDING_BROADCAST = 1;
1030    static final int MCS_BOUND = 3;
1031    static final int END_COPY = 4;
1032    static final int INIT_COPY = 5;
1033    static final int MCS_UNBIND = 6;
1034    static final int START_CLEANING_PACKAGE = 7;
1035    static final int FIND_INSTALL_LOC = 8;
1036    static final int POST_INSTALL = 9;
1037    static final int MCS_RECONNECT = 10;
1038    static final int MCS_GIVE_UP = 11;
1039    static final int UPDATED_MEDIA_STATUS = 12;
1040    static final int WRITE_SETTINGS = 13;
1041    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1042    static final int PACKAGE_VERIFIED = 15;
1043    static final int CHECK_PENDING_VERIFICATION = 16;
1044    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1045    static final int INTENT_FILTER_VERIFIED = 18;
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 CHECK_PENDING_VERIFICATION: {
1669                    final int verificationId = msg.arg1;
1670                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1671
1672                    if ((state != null) && !state.timeoutExtended()) {
1673                        final InstallArgs args = state.getInstallArgs();
1674                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1675
1676                        Slog.i(TAG, "Verification timed out for " + originUri);
1677                        mPendingVerification.remove(verificationId);
1678
1679                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1680
1681                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1682                            Slog.i(TAG, "Continuing with installation of " + originUri);
1683                            state.setVerifierResponse(Binder.getCallingUid(),
1684                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1685                            broadcastPackageVerified(verificationId, originUri,
1686                                    PackageManager.VERIFICATION_ALLOW,
1687                                    state.getInstallArgs().getUser());
1688                            try {
1689                                ret = args.copyApk(mContainerService, true);
1690                            } catch (RemoteException e) {
1691                                Slog.e(TAG, "Could not contact the ContainerService");
1692                            }
1693                        } else {
1694                            broadcastPackageVerified(verificationId, originUri,
1695                                    PackageManager.VERIFICATION_REJECT,
1696                                    state.getInstallArgs().getUser());
1697                        }
1698
1699                        Trace.asyncTraceEnd(
1700                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1701
1702                        processPendingInstall(args, ret);
1703                        mHandler.sendEmptyMessage(MCS_UNBIND);
1704                    }
1705                    break;
1706                }
1707                case PACKAGE_VERIFIED: {
1708                    final int verificationId = msg.arg1;
1709
1710                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1711                    if (state == null) {
1712                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1713                        break;
1714                    }
1715
1716                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1717
1718                    state.setVerifierResponse(response.callerUid, response.code);
1719
1720                    if (state.isVerificationComplete()) {
1721                        mPendingVerification.remove(verificationId);
1722
1723                        final InstallArgs args = state.getInstallArgs();
1724                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1725
1726                        int ret;
1727                        if (state.isInstallAllowed()) {
1728                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1729                            broadcastPackageVerified(verificationId, originUri,
1730                                    response.code, state.getInstallArgs().getUser());
1731                            try {
1732                                ret = args.copyApk(mContainerService, true);
1733                            } catch (RemoteException e) {
1734                                Slog.e(TAG, "Could not contact the ContainerService");
1735                            }
1736                        } else {
1737                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1738                        }
1739
1740                        Trace.asyncTraceEnd(
1741                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1742
1743                        processPendingInstall(args, ret);
1744                        mHandler.sendEmptyMessage(MCS_UNBIND);
1745                    }
1746
1747                    break;
1748                }
1749                case START_INTENT_FILTER_VERIFICATIONS: {
1750                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1751                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1752                            params.replacing, params.pkg);
1753                    break;
1754                }
1755                case INTENT_FILTER_VERIFIED: {
1756                    final int verificationId = msg.arg1;
1757
1758                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1759                            verificationId);
1760                    if (state == null) {
1761                        Slog.w(TAG, "Invalid IntentFilter verification token "
1762                                + verificationId + " received");
1763                        break;
1764                    }
1765
1766                    final int userId = state.getUserId();
1767
1768                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1769                            "Processing IntentFilter verification with token:"
1770                            + verificationId + " and userId:" + userId);
1771
1772                    final IntentFilterVerificationResponse response =
1773                            (IntentFilterVerificationResponse) msg.obj;
1774
1775                    state.setVerifierResponse(response.callerUid, response.code);
1776
1777                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1778                            "IntentFilter verification with token:" + verificationId
1779                            + " and userId:" + userId
1780                            + " is settings verifier response with response code:"
1781                            + response.code);
1782
1783                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1784                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1785                                + response.getFailedDomainsString());
1786                    }
1787
1788                    if (state.isVerificationComplete()) {
1789                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1790                    } else {
1791                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1792                                "IntentFilter verification with token:" + verificationId
1793                                + " was not said to be complete");
1794                    }
1795
1796                    break;
1797                }
1798            }
1799        }
1800    }
1801
1802    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1803            boolean killApp, String[] grantedPermissions,
1804            boolean launchedForRestore, String installerPackage,
1805            IPackageInstallObserver2 installObserver) {
1806        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1807            // Send the removed broadcasts
1808            if (res.removedInfo != null) {
1809                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1810            }
1811
1812            // Now that we successfully installed the package, grant runtime
1813            // permissions if requested before broadcasting the install.
1814            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1815                    >= Build.VERSION_CODES.M) {
1816                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1817            }
1818
1819            final boolean update = res.removedInfo != null
1820                    && res.removedInfo.removedPackage != null;
1821
1822            // If this is the first time we have child packages for a disabled privileged
1823            // app that had no children, we grant requested runtime permissions to the new
1824            // children if the parent on the system image had them already granted.
1825            if (res.pkg.parentPackage != null) {
1826                synchronized (mPackages) {
1827                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1828                }
1829            }
1830
1831            synchronized (mPackages) {
1832                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1833            }
1834
1835            final String packageName = res.pkg.applicationInfo.packageName;
1836            Bundle extras = new Bundle(1);
1837            extras.putInt(Intent.EXTRA_UID, res.uid);
1838
1839            // Determine the set of users who are adding this package for
1840            // the first time vs. those who are seeing an update.
1841            int[] firstUsers = EMPTY_INT_ARRAY;
1842            int[] updateUsers = EMPTY_INT_ARRAY;
1843            if (res.origUsers == null || res.origUsers.length == 0) {
1844                firstUsers = res.newUsers;
1845            } else {
1846                for (int newUser : res.newUsers) {
1847                    boolean isNew = true;
1848                    for (int origUser : res.origUsers) {
1849                        if (origUser == newUser) {
1850                            isNew = false;
1851                            break;
1852                        }
1853                    }
1854                    if (isNew) {
1855                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1856                    } else {
1857                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1858                    }
1859                }
1860            }
1861
1862            // Send installed broadcasts if the install/update is not ephemeral
1863            if (!isEphemeral(res.pkg)) {
1864                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1865
1866                // Send added for users that see the package for the first time
1867                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1868                        extras, 0 /*flags*/, null /*targetPackage*/,
1869                        null /*finishedReceiver*/, firstUsers);
1870
1871                // Send added for users that don't see the package for the first time
1872                if (update) {
1873                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1874                }
1875                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1876                        extras, 0 /*flags*/, null /*targetPackage*/,
1877                        null /*finishedReceiver*/, updateUsers);
1878
1879                // Send replaced for users that don't see the package for the first time
1880                if (update) {
1881                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1882                            packageName, extras, 0 /*flags*/,
1883                            null /*targetPackage*/, null /*finishedReceiver*/,
1884                            updateUsers);
1885                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1886                            null /*package*/, null /*extras*/, 0 /*flags*/,
1887                            packageName /*targetPackage*/,
1888                            null /*finishedReceiver*/, updateUsers);
1889                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1890                    // First-install and we did a restore, so we're responsible for the
1891                    // first-launch broadcast.
1892                    if (DEBUG_BACKUP) {
1893                        Slog.i(TAG, "Post-restore of " + packageName
1894                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1895                    }
1896                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1897                }
1898
1899                // Send broadcast package appeared if forward locked/external for all users
1900                // treat asec-hosted packages like removable media on upgrade
1901                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1902                    if (DEBUG_INSTALL) {
1903                        Slog.i(TAG, "upgrading pkg " + res.pkg
1904                                + " is ASEC-hosted -> AVAILABLE");
1905                    }
1906                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1907                    ArrayList<String> pkgList = new ArrayList<>(1);
1908                    pkgList.add(packageName);
1909                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1910                }
1911            }
1912
1913            // Work that needs to happen on first install within each user
1914            if (firstUsers != null && firstUsers.length > 0) {
1915                synchronized (mPackages) {
1916                    for (int userId : firstUsers) {
1917                        // If this app is a browser and it's newly-installed for some
1918                        // users, clear any default-browser state in those users. The
1919                        // app's nature doesn't depend on the user, so we can just check
1920                        // its browser nature in any user and generalize.
1921                        if (packageIsBrowser(packageName, userId)) {
1922                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1923                        }
1924
1925                        // We may also need to apply pending (restored) runtime
1926                        // permission grants within these users.
1927                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1928                    }
1929                }
1930            }
1931
1932            // Log current value of "unknown sources" setting
1933            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1934                    getUnknownSourcesSettings());
1935
1936            // Force a gc to clear up things
1937            Runtime.getRuntime().gc();
1938
1939            // Remove the replaced package's older resources safely now
1940            // We delete after a gc for applications  on sdcard.
1941            if (res.removedInfo != null && res.removedInfo.args != null) {
1942                synchronized (mInstallLock) {
1943                    res.removedInfo.args.doPostDeleteLI(true);
1944                }
1945            }
1946        }
1947
1948        // If someone is watching installs - notify them
1949        if (installObserver != null) {
1950            try {
1951                Bundle extras = extrasForInstallResult(res);
1952                installObserver.onPackageInstalled(res.name, res.returnCode,
1953                        res.returnMsg, extras);
1954            } catch (RemoteException e) {
1955                Slog.i(TAG, "Observer no longer exists.");
1956            }
1957        }
1958    }
1959
1960    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1961            PackageParser.Package pkg) {
1962        if (pkg.parentPackage == null) {
1963            return;
1964        }
1965        if (pkg.requestedPermissions == null) {
1966            return;
1967        }
1968        final PackageSetting disabledSysParentPs = mSettings
1969                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1970        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1971                || !disabledSysParentPs.isPrivileged()
1972                || (disabledSysParentPs.childPackageNames != null
1973                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1974            return;
1975        }
1976        final int[] allUserIds = sUserManager.getUserIds();
1977        final int permCount = pkg.requestedPermissions.size();
1978        for (int i = 0; i < permCount; i++) {
1979            String permission = pkg.requestedPermissions.get(i);
1980            BasePermission bp = mSettings.mPermissions.get(permission);
1981            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1982                continue;
1983            }
1984            for (int userId : allUserIds) {
1985                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1986                        permission, userId)) {
1987                    grantRuntimePermission(pkg.packageName, permission, userId);
1988                }
1989            }
1990        }
1991    }
1992
1993    private StorageEventListener mStorageListener = new StorageEventListener() {
1994        @Override
1995        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1996            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1997                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1998                    final String volumeUuid = vol.getFsUuid();
1999
2000                    // Clean up any users or apps that were removed or recreated
2001                    // while this volume was missing
2002                    reconcileUsers(volumeUuid);
2003                    reconcileApps(volumeUuid);
2004
2005                    // Clean up any install sessions that expired or were
2006                    // cancelled while this volume was missing
2007                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2008
2009                    loadPrivatePackages(vol);
2010
2011                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2012                    unloadPrivatePackages(vol);
2013                }
2014            }
2015
2016            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2017                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2018                    updateExternalMediaStatus(true, false);
2019                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2020                    updateExternalMediaStatus(false, false);
2021                }
2022            }
2023        }
2024
2025        @Override
2026        public void onVolumeForgotten(String fsUuid) {
2027            if (TextUtils.isEmpty(fsUuid)) {
2028                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2029                return;
2030            }
2031
2032            // Remove any apps installed on the forgotten volume
2033            synchronized (mPackages) {
2034                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2035                for (PackageSetting ps : packages) {
2036                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2037                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2038                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2039                }
2040
2041                mSettings.onVolumeForgotten(fsUuid);
2042                mSettings.writeLPr();
2043            }
2044        }
2045    };
2046
2047    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2048            String[] grantedPermissions) {
2049        for (int userId : userIds) {
2050            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2051        }
2052
2053        // We could have touched GID membership, so flush out packages.list
2054        synchronized (mPackages) {
2055            mSettings.writePackageListLPr();
2056        }
2057    }
2058
2059    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2060            String[] grantedPermissions) {
2061        SettingBase sb = (SettingBase) pkg.mExtras;
2062        if (sb == null) {
2063            return;
2064        }
2065
2066        PermissionsState permissionsState = sb.getPermissionsState();
2067
2068        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2069                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2070
2071        for (String permission : pkg.requestedPermissions) {
2072            final BasePermission bp;
2073            synchronized (mPackages) {
2074                bp = mSettings.mPermissions.get(permission);
2075            }
2076            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2077                    && (grantedPermissions == null
2078                           || ArrayUtils.contains(grantedPermissions, permission))) {
2079                final int flags = permissionsState.getPermissionFlags(permission, userId);
2080                // Installer cannot change immutable permissions.
2081                if ((flags & immutableFlags) == 0) {
2082                    grantRuntimePermission(pkg.packageName, permission, userId);
2083                }
2084            }
2085        }
2086    }
2087
2088    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2089        Bundle extras = null;
2090        switch (res.returnCode) {
2091            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2092                extras = new Bundle();
2093                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2094                        res.origPermission);
2095                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2096                        res.origPackage);
2097                break;
2098            }
2099            case PackageManager.INSTALL_SUCCEEDED: {
2100                extras = new Bundle();
2101                extras.putBoolean(Intent.EXTRA_REPLACING,
2102                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2103                break;
2104            }
2105        }
2106        return extras;
2107    }
2108
2109    void scheduleWriteSettingsLocked() {
2110        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2111            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2112        }
2113    }
2114
2115    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2116        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2117        scheduleWritePackageRestrictionsLocked(userId);
2118    }
2119
2120    void scheduleWritePackageRestrictionsLocked(int userId) {
2121        final int[] userIds = (userId == UserHandle.USER_ALL)
2122                ? sUserManager.getUserIds() : new int[]{userId};
2123        for (int nextUserId : userIds) {
2124            if (!sUserManager.exists(nextUserId)) return;
2125            mDirtyUsers.add(nextUserId);
2126            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2127                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2128            }
2129        }
2130    }
2131
2132    public static PackageManagerService main(Context context, Installer installer,
2133            boolean factoryTest, boolean onlyCore) {
2134        // Self-check for initial settings.
2135        PackageManagerServiceCompilerMapping.checkProperties();
2136
2137        PackageManagerService m = new PackageManagerService(context, installer,
2138                factoryTest, onlyCore);
2139        m.enableSystemUserPackages();
2140        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2141        // disabled after already being started.
2142        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2143                UserHandle.USER_SYSTEM);
2144        ServiceManager.addService("package", m);
2145        return m;
2146    }
2147
2148    private void enableSystemUserPackages() {
2149        if (!UserManager.isSplitSystemUser()) {
2150            return;
2151        }
2152        // For system user, enable apps based on the following conditions:
2153        // - app is whitelisted or belong to one of these groups:
2154        //   -- system app which has no launcher icons
2155        //   -- system app which has INTERACT_ACROSS_USERS permission
2156        //   -- system IME app
2157        // - app is not in the blacklist
2158        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2159        Set<String> enableApps = new ArraySet<>();
2160        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2161                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2162                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2163        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2164        enableApps.addAll(wlApps);
2165        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2166                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2167        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2168        enableApps.removeAll(blApps);
2169        Log.i(TAG, "Applications installed for system user: " + enableApps);
2170        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2171                UserHandle.SYSTEM);
2172        final int allAppsSize = allAps.size();
2173        synchronized (mPackages) {
2174            for (int i = 0; i < allAppsSize; i++) {
2175                String pName = allAps.get(i);
2176                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2177                // Should not happen, but we shouldn't be failing if it does
2178                if (pkgSetting == null) {
2179                    continue;
2180                }
2181                boolean install = enableApps.contains(pName);
2182                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2183                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2184                            + " for system user");
2185                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2186                }
2187            }
2188        }
2189    }
2190
2191    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2192        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2193                Context.DISPLAY_SERVICE);
2194        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2195    }
2196
2197    public PackageManagerService(Context context, Installer installer,
2198            boolean factoryTest, boolean onlyCore) {
2199        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2200                SystemClock.uptimeMillis());
2201
2202        if (mSdkVersion <= 0) {
2203            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2204        }
2205
2206        mContext = context;
2207        mFactoryTest = factoryTest;
2208        mOnlyCore = onlyCore;
2209        mMetrics = new DisplayMetrics();
2210        mSettings = new Settings(mPackages);
2211        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2212                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2213        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2214                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2215        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2216                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2217        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2218                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2219        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2220                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2221        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2222                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2223
2224        String separateProcesses = SystemProperties.get("debug.separate_processes");
2225        if (separateProcesses != null && separateProcesses.length() > 0) {
2226            if ("*".equals(separateProcesses)) {
2227                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2228                mSeparateProcesses = null;
2229                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2230            } else {
2231                mDefParseFlags = 0;
2232                mSeparateProcesses = separateProcesses.split(",");
2233                Slog.w(TAG, "Running with debug.separate_processes: "
2234                        + separateProcesses);
2235            }
2236        } else {
2237            mDefParseFlags = 0;
2238            mSeparateProcesses = null;
2239        }
2240
2241        mInstaller = installer;
2242        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2243                "*dexopt*");
2244        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2245
2246        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2247                FgThread.get().getLooper());
2248
2249        getDefaultDisplayMetrics(context, mMetrics);
2250
2251        SystemConfig systemConfig = SystemConfig.getInstance();
2252        mGlobalGids = systemConfig.getGlobalGids();
2253        mSystemPermissions = systemConfig.getSystemPermissions();
2254        mAvailableFeatures = systemConfig.getAvailableFeatures();
2255
2256        synchronized (mInstallLock) {
2257        // writer
2258        synchronized (mPackages) {
2259            mHandlerThread = new ServiceThread(TAG,
2260                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2261            mHandlerThread.start();
2262            mHandler = new PackageHandler(mHandlerThread.getLooper());
2263            mProcessLoggingHandler = new ProcessLoggingHandler();
2264            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2265
2266            File dataDir = Environment.getDataDirectory();
2267            mAppInstallDir = new File(dataDir, "app");
2268            mAppLib32InstallDir = new File(dataDir, "app-lib");
2269            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2270            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2271            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2272
2273            sUserManager = new UserManagerService(context, this, mPackages);
2274
2275            // Propagate permission configuration in to package manager.
2276            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2277                    = systemConfig.getPermissions();
2278            for (int i=0; i<permConfig.size(); i++) {
2279                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2280                BasePermission bp = mSettings.mPermissions.get(perm.name);
2281                if (bp == null) {
2282                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2283                    mSettings.mPermissions.put(perm.name, bp);
2284                }
2285                if (perm.gids != null) {
2286                    bp.setGids(perm.gids, perm.perUser);
2287                }
2288            }
2289
2290            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2291            for (int i=0; i<libConfig.size(); i++) {
2292                mSharedLibraries.put(libConfig.keyAt(i),
2293                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2294            }
2295
2296            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2297
2298            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2299
2300            String customResolverActivity = Resources.getSystem().getString(
2301                    R.string.config_customResolverActivity);
2302            if (TextUtils.isEmpty(customResolverActivity)) {
2303                customResolverActivity = null;
2304            } else {
2305                mCustomResolverComponentName = ComponentName.unflattenFromString(
2306                        customResolverActivity);
2307            }
2308
2309            long startTime = SystemClock.uptimeMillis();
2310
2311            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2312                    startTime);
2313
2314            // Set flag to monitor and not change apk file paths when
2315            // scanning install directories.
2316            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2317
2318            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2319            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2320
2321            if (bootClassPath == null) {
2322                Slog.w(TAG, "No BOOTCLASSPATH found!");
2323            }
2324
2325            if (systemServerClassPath == null) {
2326                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2327            }
2328
2329            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2330            final String[] dexCodeInstructionSets =
2331                    getDexCodeInstructionSets(
2332                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2333
2334            /**
2335             * Ensure all external libraries have had dexopt run on them.
2336             */
2337            if (mSharedLibraries.size() > 0) {
2338                // NOTE: For now, we're compiling these system "shared libraries"
2339                // (and framework jars) into all available architectures. It's possible
2340                // to compile them only when we come across an app that uses them (there's
2341                // already logic for that in scanPackageLI) but that adds some complexity.
2342                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2343                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2344                        final String lib = libEntry.path;
2345                        if (lib == null) {
2346                            continue;
2347                        }
2348
2349                        try {
2350                            // Shared libraries do not have profiles so we perform a full
2351                            // AOT compilation (if needed).
2352                            int dexoptNeeded = DexFile.getDexOptNeeded(
2353                                    lib, dexCodeInstructionSet,
2354                                    getCompilerFilterForReason(REASON_SHARED_APK),
2355                                    false /* newProfile */);
2356                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2357                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2358                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2359                                        getCompilerFilterForReason(REASON_SHARED_APK),
2360                                        StorageManager.UUID_PRIVATE_INTERNAL,
2361                                        SKIP_SHARED_LIBRARY_CHECK);
2362                            }
2363                        } catch (FileNotFoundException e) {
2364                            Slog.w(TAG, "Library not found: " + lib);
2365                        } catch (IOException | InstallerException e) {
2366                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2367                                    + e.getMessage());
2368                        }
2369                    }
2370                }
2371            }
2372
2373            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2374
2375            final VersionInfo ver = mSettings.getInternalVersion();
2376            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2377
2378            // when upgrading from pre-M, promote system app permissions from install to runtime
2379            mPromoteSystemApps =
2380                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2381
2382            // save off the names of pre-existing system packages prior to scanning; we don't
2383            // want to automatically grant runtime permissions for new system apps
2384            if (mPromoteSystemApps) {
2385                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2386                while (pkgSettingIter.hasNext()) {
2387                    PackageSetting ps = pkgSettingIter.next();
2388                    if (isSystemApp(ps)) {
2389                        mExistingSystemPackages.add(ps.name);
2390                    }
2391                }
2392            }
2393
2394            // When upgrading from pre-N, we need to handle package extraction like first boot,
2395            // as there is no profiling data available.
2396            mIsPreNUpgrade = !mSettings.isNWorkDone();
2397            mSettings.setNWorkDone();
2398
2399            // Collect vendor overlay packages.
2400            // (Do this before scanning any apps.)
2401            // For security and version matching reason, only consider
2402            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2403            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2404            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2405                    | PackageParser.PARSE_IS_SYSTEM
2406                    | PackageParser.PARSE_IS_SYSTEM_DIR
2407                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2408
2409            // Find base frameworks (resource packages without code).
2410            scanDirTracedLI(frameworkDir, mDefParseFlags
2411                    | PackageParser.PARSE_IS_SYSTEM
2412                    | PackageParser.PARSE_IS_SYSTEM_DIR
2413                    | PackageParser.PARSE_IS_PRIVILEGED,
2414                    scanFlags | SCAN_NO_DEX, 0);
2415
2416            // Collected privileged system packages.
2417            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2418            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2419                    | PackageParser.PARSE_IS_SYSTEM
2420                    | PackageParser.PARSE_IS_SYSTEM_DIR
2421                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2422
2423            // Collect ordinary system packages.
2424            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2425            scanDirTracedLI(systemAppDir, mDefParseFlags
2426                    | PackageParser.PARSE_IS_SYSTEM
2427                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2428
2429            // Collect all vendor packages.
2430            File vendorAppDir = new File("/vendor/app");
2431            try {
2432                vendorAppDir = vendorAppDir.getCanonicalFile();
2433            } catch (IOException e) {
2434                // failed to look up canonical path, continue with original one
2435            }
2436            scanDirTracedLI(vendorAppDir, mDefParseFlags
2437                    | PackageParser.PARSE_IS_SYSTEM
2438                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2439
2440            // Collect all OEM packages.
2441            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2442            scanDirTracedLI(oemAppDir, mDefParseFlags
2443                    | PackageParser.PARSE_IS_SYSTEM
2444                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2445
2446            // Prune any system packages that no longer exist.
2447            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2448            if (!mOnlyCore) {
2449                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2450                while (psit.hasNext()) {
2451                    PackageSetting ps = psit.next();
2452
2453                    /*
2454                     * If this is not a system app, it can't be a
2455                     * disable system app.
2456                     */
2457                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2458                        continue;
2459                    }
2460
2461                    /*
2462                     * If the package is scanned, it's not erased.
2463                     */
2464                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2465                    if (scannedPkg != null) {
2466                        /*
2467                         * If the system app is both scanned and in the
2468                         * disabled packages list, then it must have been
2469                         * added via OTA. Remove it from the currently
2470                         * scanned package so the previously user-installed
2471                         * application can be scanned.
2472                         */
2473                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2474                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2475                                    + ps.name + "; removing system app.  Last known codePath="
2476                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2477                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2478                                    + scannedPkg.mVersionCode);
2479                            removePackageLI(scannedPkg, true);
2480                            mExpectingBetter.put(ps.name, ps.codePath);
2481                        }
2482
2483                        continue;
2484                    }
2485
2486                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2487                        psit.remove();
2488                        logCriticalInfo(Log.WARN, "System package " + ps.name
2489                                + " no longer exists; it's data will be wiped");
2490                        // Actual deletion of code and data will be handled by later
2491                        // reconciliation step
2492                    } else {
2493                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2494                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2495                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2496                        }
2497                    }
2498                }
2499            }
2500
2501            //look for any incomplete package installations
2502            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2503            for (int i = 0; i < deletePkgsList.size(); i++) {
2504                // Actual deletion of code and data will be handled by later
2505                // reconciliation step
2506                final String packageName = deletePkgsList.get(i).name;
2507                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2508                synchronized (mPackages) {
2509                    mSettings.removePackageLPw(packageName);
2510                }
2511            }
2512
2513            //delete tmp files
2514            deleteTempPackageFiles();
2515
2516            // Remove any shared userIDs that have no associated packages
2517            mSettings.pruneSharedUsersLPw();
2518
2519            if (!mOnlyCore) {
2520                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2521                        SystemClock.uptimeMillis());
2522                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2523
2524                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2525                        | PackageParser.PARSE_FORWARD_LOCK,
2526                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2527
2528                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2529                        | PackageParser.PARSE_IS_EPHEMERAL,
2530                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2531
2532                /**
2533                 * Remove disable package settings for any updated system
2534                 * apps that were removed via an OTA. If they're not a
2535                 * previously-updated app, remove them completely.
2536                 * Otherwise, just revoke their system-level permissions.
2537                 */
2538                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2539                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2540                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2541
2542                    String msg;
2543                    if (deletedPkg == null) {
2544                        msg = "Updated system package " + deletedAppName
2545                                + " no longer exists; it's data will be wiped";
2546                        // Actual deletion of code and data will be handled by later
2547                        // reconciliation step
2548                    } else {
2549                        msg = "Updated system app + " + deletedAppName
2550                                + " no longer present; removing system privileges for "
2551                                + deletedAppName;
2552
2553                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2554
2555                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2556                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2557                    }
2558                    logCriticalInfo(Log.WARN, msg);
2559                }
2560
2561                /**
2562                 * Make sure all system apps that we expected to appear on
2563                 * the userdata partition actually showed up. If they never
2564                 * appeared, crawl back and revive the system version.
2565                 */
2566                for (int i = 0; i < mExpectingBetter.size(); i++) {
2567                    final String packageName = mExpectingBetter.keyAt(i);
2568                    if (!mPackages.containsKey(packageName)) {
2569                        final File scanFile = mExpectingBetter.valueAt(i);
2570
2571                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2572                                + " but never showed up; reverting to system");
2573
2574                        int reparseFlags = mDefParseFlags;
2575                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2576                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2577                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2578                                    | PackageParser.PARSE_IS_PRIVILEGED;
2579                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2580                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2581                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2582                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2583                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2584                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2585                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2586                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2587                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2588                        } else {
2589                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2590                            continue;
2591                        }
2592
2593                        mSettings.enableSystemPackageLPw(packageName);
2594
2595                        try {
2596                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2597                        } catch (PackageManagerException e) {
2598                            Slog.e(TAG, "Failed to parse original system package: "
2599                                    + e.getMessage());
2600                        }
2601                    }
2602                }
2603            }
2604            mExpectingBetter.clear();
2605
2606            // Resolve protected action filters. Only the setup wizard is allowed to
2607            // have a high priority filter for these actions.
2608            mSetupWizardPackage = getSetupWizardPackageName();
2609            if (mProtectedFilters.size() > 0) {
2610                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2611                    Slog.i(TAG, "No setup wizard;"
2612                        + " All protected intents capped to priority 0");
2613                }
2614                for (ActivityIntentInfo filter : mProtectedFilters) {
2615                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2616                        if (DEBUG_FILTERS) {
2617                            Slog.i(TAG, "Found setup wizard;"
2618                                + " allow priority " + filter.getPriority() + ";"
2619                                + " package: " + filter.activity.info.packageName
2620                                + " activity: " + filter.activity.className
2621                                + " priority: " + filter.getPriority());
2622                        }
2623                        // skip setup wizard; allow it to keep the high priority filter
2624                        continue;
2625                    }
2626                    Slog.w(TAG, "Protected action; cap priority to 0;"
2627                            + " package: " + filter.activity.info.packageName
2628                            + " activity: " + filter.activity.className
2629                            + " origPrio: " + filter.getPriority());
2630                    filter.setPriority(0);
2631                }
2632            }
2633            mDeferProtectedFilters = false;
2634            mProtectedFilters.clear();
2635
2636            // Now that we know all of the shared libraries, update all clients to have
2637            // the correct library paths.
2638            updateAllSharedLibrariesLPw();
2639
2640            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2641                // NOTE: We ignore potential failures here during a system scan (like
2642                // the rest of the commands above) because there's precious little we
2643                // can do about it. A settings error is reported, though.
2644                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2645                        false /* boot complete */);
2646            }
2647
2648            // Now that we know all the packages we are keeping,
2649            // read and update their last usage times.
2650            mPackageUsage.readLP();
2651
2652            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2653                    SystemClock.uptimeMillis());
2654            Slog.i(TAG, "Time to scan packages: "
2655                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2656                    + " seconds");
2657
2658            // If the platform SDK has changed since the last time we booted,
2659            // we need to re-grant app permission to catch any new ones that
2660            // appear.  This is really a hack, and means that apps can in some
2661            // cases get permissions that the user didn't initially explicitly
2662            // allow...  it would be nice to have some better way to handle
2663            // this situation.
2664            int updateFlags = UPDATE_PERMISSIONS_ALL;
2665            if (ver.sdkVersion != mSdkVersion) {
2666                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2667                        + mSdkVersion + "; regranting permissions for internal storage");
2668                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2669            }
2670            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2671            ver.sdkVersion = mSdkVersion;
2672
2673            // If this is the first boot or an update from pre-M, and it is a normal
2674            // boot, then we need to initialize the default preferred apps across
2675            // all defined users.
2676            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2677                for (UserInfo user : sUserManager.getUsers(true)) {
2678                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2679                    applyFactoryDefaultBrowserLPw(user.id);
2680                    primeDomainVerificationsLPw(user.id);
2681                }
2682            }
2683
2684            // Prepare storage for system user really early during boot,
2685            // since core system apps like SettingsProvider and SystemUI
2686            // can't wait for user to start
2687            final int storageFlags;
2688            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2689                storageFlags = StorageManager.FLAG_STORAGE_DE;
2690            } else {
2691                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2692            }
2693            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2694                    storageFlags);
2695
2696            // If this is first boot after an OTA, and a normal boot, then
2697            // we need to clear code cache directories.
2698            // Note that we do *not* clear the application profiles. These remain valid
2699            // across OTAs and are used to drive profile verification (post OTA) and
2700            // profile compilation (without waiting to collect a fresh set of profiles).
2701            if (mIsUpgrade && !onlyCore) {
2702                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2703                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2704                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2705                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2706                        // No apps are running this early, so no need to freeze
2707                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2708                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2709                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2710                    }
2711                }
2712                ver.fingerprint = Build.FINGERPRINT;
2713            }
2714
2715            checkDefaultBrowser();
2716
2717            // clear only after permissions and other defaults have been updated
2718            mExistingSystemPackages.clear();
2719            mPromoteSystemApps = false;
2720
2721            // All the changes are done during package scanning.
2722            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2723
2724            // can downgrade to reader
2725            mSettings.writeLPr();
2726
2727            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2728                    SystemClock.uptimeMillis());
2729
2730            if (!mOnlyCore) {
2731                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2732                mRequiredInstallerPackage = getRequiredInstallerLPr();
2733                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2734                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2735                        mIntentFilterVerifierComponent);
2736                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2737                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2738                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2739                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2740            } else {
2741                mRequiredVerifierPackage = null;
2742                mRequiredInstallerPackage = null;
2743                mIntentFilterVerifierComponent = null;
2744                mIntentFilterVerifier = null;
2745                mServicesSystemSharedLibraryPackageName = null;
2746                mSharedSystemSharedLibraryPackageName = null;
2747            }
2748
2749            mInstallerService = new PackageInstallerService(context, this);
2750
2751            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2752            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2753            // both the installer and resolver must be present to enable ephemeral
2754            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2755                if (DEBUG_EPHEMERAL) {
2756                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2757                            + " installer:" + ephemeralInstallerComponent);
2758                }
2759                mEphemeralResolverComponent = ephemeralResolverComponent;
2760                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2761                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2762                mEphemeralResolverConnection =
2763                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2764            } else {
2765                if (DEBUG_EPHEMERAL) {
2766                    final String missingComponent =
2767                            (ephemeralResolverComponent == null)
2768                            ? (ephemeralInstallerComponent == null)
2769                                    ? "resolver and installer"
2770                                    : "resolver"
2771                            : "installer";
2772                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2773                }
2774                mEphemeralResolverComponent = null;
2775                mEphemeralInstallerComponent = null;
2776                mEphemeralResolverConnection = null;
2777            }
2778
2779            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2780        } // synchronized (mPackages)
2781        } // synchronized (mInstallLock)
2782
2783        // Now after opening every single application zip, make sure they
2784        // are all flushed.  Not really needed, but keeps things nice and
2785        // tidy.
2786        Runtime.getRuntime().gc();
2787
2788        // The initial scanning above does many calls into installd while
2789        // holding the mPackages lock, but we're mostly interested in yelling
2790        // once we have a booted system.
2791        mInstaller.setWarnIfHeld(mPackages);
2792
2793        // Expose private service for system components to use.
2794        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2795    }
2796
2797    @Override
2798    public boolean isFirstBoot() {
2799        return !mRestoredSettings;
2800    }
2801
2802    @Override
2803    public boolean isOnlyCoreApps() {
2804        return mOnlyCore;
2805    }
2806
2807    @Override
2808    public boolean isUpgrade() {
2809        return mIsUpgrade;
2810    }
2811
2812    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2813        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2814
2815        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2816                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2817                UserHandle.USER_SYSTEM);
2818        if (matches.size() == 1) {
2819            return matches.get(0).getComponentInfo().packageName;
2820        } else {
2821            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2822            return null;
2823        }
2824    }
2825
2826    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2827        synchronized (mPackages) {
2828            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2829            if (libraryEntry == null) {
2830                throw new IllegalStateException("Missing required shared library:" + libraryName);
2831            }
2832            return libraryEntry.apk;
2833        }
2834    }
2835
2836    private @NonNull String getRequiredInstallerLPr() {
2837        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2838        intent.addCategory(Intent.CATEGORY_DEFAULT);
2839        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2840
2841        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2842                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2843                UserHandle.USER_SYSTEM);
2844        if (matches.size() == 1) {
2845            ResolveInfo resolveInfo = matches.get(0);
2846            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2847                throw new RuntimeException("The installer must be a privileged app");
2848            }
2849            return matches.get(0).getComponentInfo().packageName;
2850        } else {
2851            throw new RuntimeException("There must be exactly one installer; found " + matches);
2852        }
2853    }
2854
2855    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2856        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2857
2858        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2859                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2860                UserHandle.USER_SYSTEM);
2861        ResolveInfo best = null;
2862        final int N = matches.size();
2863        for (int i = 0; i < N; i++) {
2864            final ResolveInfo cur = matches.get(i);
2865            final String packageName = cur.getComponentInfo().packageName;
2866            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2867                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2868                continue;
2869            }
2870
2871            if (best == null || cur.priority > best.priority) {
2872                best = cur;
2873            }
2874        }
2875
2876        if (best != null) {
2877            return best.getComponentInfo().getComponentName();
2878        } else {
2879            throw new RuntimeException("There must be at least one intent filter verifier");
2880        }
2881    }
2882
2883    private @Nullable ComponentName getEphemeralResolverLPr() {
2884        final String[] packageArray =
2885                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2886        if (packageArray.length == 0) {
2887            if (DEBUG_EPHEMERAL) {
2888                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2889            }
2890            return null;
2891        }
2892
2893        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2894        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2895                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2896                UserHandle.USER_SYSTEM);
2897
2898        final int N = resolvers.size();
2899        if (N == 0) {
2900            if (DEBUG_EPHEMERAL) {
2901                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2902            }
2903            return null;
2904        }
2905
2906        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2907        for (int i = 0; i < N; i++) {
2908            final ResolveInfo info = resolvers.get(i);
2909
2910            if (info.serviceInfo == null) {
2911                continue;
2912            }
2913
2914            final String packageName = info.serviceInfo.packageName;
2915            if (!possiblePackages.contains(packageName)) {
2916                if (DEBUG_EPHEMERAL) {
2917                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2918                            + " pkg: " + packageName + ", info:" + info);
2919                }
2920                continue;
2921            }
2922
2923            if (DEBUG_EPHEMERAL) {
2924                Slog.v(TAG, "Ephemeral resolver found;"
2925                        + " pkg: " + packageName + ", info:" + info);
2926            }
2927            return new ComponentName(packageName, info.serviceInfo.name);
2928        }
2929        if (DEBUG_EPHEMERAL) {
2930            Slog.v(TAG, "Ephemeral resolver NOT found");
2931        }
2932        return null;
2933    }
2934
2935    private @Nullable ComponentName getEphemeralInstallerLPr() {
2936        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2937        intent.addCategory(Intent.CATEGORY_DEFAULT);
2938        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2939
2940        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2941                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2942                UserHandle.USER_SYSTEM);
2943        if (matches.size() == 0) {
2944            return null;
2945        } else if (matches.size() == 1) {
2946            return matches.get(0).getComponentInfo().getComponentName();
2947        } else {
2948            throw new RuntimeException(
2949                    "There must be at most one ephemeral installer; found " + matches);
2950        }
2951    }
2952
2953    private void primeDomainVerificationsLPw(int userId) {
2954        if (DEBUG_DOMAIN_VERIFICATION) {
2955            Slog.d(TAG, "Priming domain verifications in user " + userId);
2956        }
2957
2958        SystemConfig systemConfig = SystemConfig.getInstance();
2959        ArraySet<String> packages = systemConfig.getLinkedApps();
2960        ArraySet<String> domains = new ArraySet<String>();
2961
2962        for (String packageName : packages) {
2963            PackageParser.Package pkg = mPackages.get(packageName);
2964            if (pkg != null) {
2965                if (!pkg.isSystemApp()) {
2966                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2967                    continue;
2968                }
2969
2970                domains.clear();
2971                for (PackageParser.Activity a : pkg.activities) {
2972                    for (ActivityIntentInfo filter : a.intents) {
2973                        if (hasValidDomains(filter)) {
2974                            domains.addAll(filter.getHostsList());
2975                        }
2976                    }
2977                }
2978
2979                if (domains.size() > 0) {
2980                    if (DEBUG_DOMAIN_VERIFICATION) {
2981                        Slog.v(TAG, "      + " + packageName);
2982                    }
2983                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2984                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2985                    // and then 'always' in the per-user state actually used for intent resolution.
2986                    final IntentFilterVerificationInfo ivi;
2987                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2988                            new ArrayList<String>(domains));
2989                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2990                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2991                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2992                } else {
2993                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2994                            + "' does not handle web links");
2995                }
2996            } else {
2997                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2998            }
2999        }
3000
3001        scheduleWritePackageRestrictionsLocked(userId);
3002        scheduleWriteSettingsLocked();
3003    }
3004
3005    private void applyFactoryDefaultBrowserLPw(int userId) {
3006        // The default browser app's package name is stored in a string resource,
3007        // with a product-specific overlay used for vendor customization.
3008        String browserPkg = mContext.getResources().getString(
3009                com.android.internal.R.string.default_browser);
3010        if (!TextUtils.isEmpty(browserPkg)) {
3011            // non-empty string => required to be a known package
3012            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3013            if (ps == null) {
3014                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3015                browserPkg = null;
3016            } else {
3017                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3018            }
3019        }
3020
3021        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3022        // default.  If there's more than one, just leave everything alone.
3023        if (browserPkg == null) {
3024            calculateDefaultBrowserLPw(userId);
3025        }
3026    }
3027
3028    private void calculateDefaultBrowserLPw(int userId) {
3029        List<String> allBrowsers = resolveAllBrowserApps(userId);
3030        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3031        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3032    }
3033
3034    private List<String> resolveAllBrowserApps(int userId) {
3035        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3036        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3037                PackageManager.MATCH_ALL, userId);
3038
3039        final int count = list.size();
3040        List<String> result = new ArrayList<String>(count);
3041        for (int i=0; i<count; i++) {
3042            ResolveInfo info = list.get(i);
3043            if (info.activityInfo == null
3044                    || !info.handleAllWebDataURI
3045                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3046                    || result.contains(info.activityInfo.packageName)) {
3047                continue;
3048            }
3049            result.add(info.activityInfo.packageName);
3050        }
3051
3052        return result;
3053    }
3054
3055    private boolean packageIsBrowser(String packageName, int userId) {
3056        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3057                PackageManager.MATCH_ALL, userId);
3058        final int N = list.size();
3059        for (int i = 0; i < N; i++) {
3060            ResolveInfo info = list.get(i);
3061            if (packageName.equals(info.activityInfo.packageName)) {
3062                return true;
3063            }
3064        }
3065        return false;
3066    }
3067
3068    private void checkDefaultBrowser() {
3069        final int myUserId = UserHandle.myUserId();
3070        final String packageName = getDefaultBrowserPackageName(myUserId);
3071        if (packageName != null) {
3072            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3073            if (info == null) {
3074                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3075                synchronized (mPackages) {
3076                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3077                }
3078            }
3079        }
3080    }
3081
3082    @Override
3083    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3084            throws RemoteException {
3085        try {
3086            return super.onTransact(code, data, reply, flags);
3087        } catch (RuntimeException e) {
3088            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3089                Slog.wtf(TAG, "Package Manager Crash", e);
3090            }
3091            throw e;
3092        }
3093    }
3094
3095    static int[] appendInts(int[] cur, int[] add) {
3096        if (add == null) return cur;
3097        if (cur == null) return add;
3098        final int N = add.length;
3099        for (int i=0; i<N; i++) {
3100            cur = appendInt(cur, add[i]);
3101        }
3102        return cur;
3103    }
3104
3105    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3106        if (!sUserManager.exists(userId)) return null;
3107        if (ps == null) {
3108            return null;
3109        }
3110        final PackageParser.Package p = ps.pkg;
3111        if (p == null) {
3112            return null;
3113        }
3114
3115        final PermissionsState permissionsState = ps.getPermissionsState();
3116
3117        final int[] gids = permissionsState.computeGids(userId);
3118        final Set<String> permissions = permissionsState.getPermissions(userId);
3119        final PackageUserState state = ps.readUserState(userId);
3120
3121        return PackageParser.generatePackageInfo(p, gids, flags,
3122                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3123    }
3124
3125    @Override
3126    public void checkPackageStartable(String packageName, int userId) {
3127        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3128
3129        synchronized (mPackages) {
3130            final PackageSetting ps = mSettings.mPackages.get(packageName);
3131            if (ps == null) {
3132                throw new SecurityException("Package " + packageName + " was not found!");
3133            }
3134
3135            if (!ps.getInstalled(userId)) {
3136                throw new SecurityException(
3137                        "Package " + packageName + " was not installed for user " + userId + "!");
3138            }
3139
3140            if (mSafeMode && !ps.isSystem()) {
3141                throw new SecurityException("Package " + packageName + " not a system app!");
3142            }
3143
3144            if (mFrozenPackages.contains(packageName)) {
3145                throw new SecurityException("Package " + packageName + " is currently frozen!");
3146            }
3147
3148            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3149                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3150                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3151            }
3152        }
3153    }
3154
3155    @Override
3156    public boolean isPackageAvailable(String packageName, int userId) {
3157        if (!sUserManager.exists(userId)) return false;
3158        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3159                false /* requireFullPermission */, false /* checkShell */, "is package available");
3160        synchronized (mPackages) {
3161            PackageParser.Package p = mPackages.get(packageName);
3162            if (p != null) {
3163                final PackageSetting ps = (PackageSetting) p.mExtras;
3164                if (ps != null) {
3165                    final PackageUserState state = ps.readUserState(userId);
3166                    if (state != null) {
3167                        return PackageParser.isAvailable(state);
3168                    }
3169                }
3170            }
3171        }
3172        return false;
3173    }
3174
3175    @Override
3176    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3177        if (!sUserManager.exists(userId)) return null;
3178        flags = updateFlagsForPackage(flags, userId, packageName);
3179        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3180                false /* requireFullPermission */, false /* checkShell */, "get package info");
3181        // reader
3182        synchronized (mPackages) {
3183            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3184            PackageParser.Package p = null;
3185            if (matchFactoryOnly) {
3186                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3187                if (ps != null) {
3188                    return generatePackageInfo(ps, flags, userId);
3189                }
3190            }
3191            if (p == null) {
3192                p = mPackages.get(packageName);
3193                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3194                    return null;
3195                }
3196            }
3197            if (DEBUG_PACKAGE_INFO)
3198                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3199            if (p != null) {
3200                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3201            }
3202            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3203                final PackageSetting ps = mSettings.mPackages.get(packageName);
3204                return generatePackageInfo(ps, flags, userId);
3205            }
3206        }
3207        return null;
3208    }
3209
3210    @Override
3211    public String[] currentToCanonicalPackageNames(String[] names) {
3212        String[] out = new String[names.length];
3213        // reader
3214        synchronized (mPackages) {
3215            for (int i=names.length-1; i>=0; i--) {
3216                PackageSetting ps = mSettings.mPackages.get(names[i]);
3217                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3218            }
3219        }
3220        return out;
3221    }
3222
3223    @Override
3224    public String[] canonicalToCurrentPackageNames(String[] names) {
3225        String[] out = new String[names.length];
3226        // reader
3227        synchronized (mPackages) {
3228            for (int i=names.length-1; i>=0; i--) {
3229                String cur = mSettings.mRenamedPackages.get(names[i]);
3230                out[i] = cur != null ? cur : names[i];
3231            }
3232        }
3233        return out;
3234    }
3235
3236    @Override
3237    public int getPackageUid(String packageName, int flags, int userId) {
3238        if (!sUserManager.exists(userId)) return -1;
3239        flags = updateFlagsForPackage(flags, userId, packageName);
3240        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3241                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3242
3243        // reader
3244        synchronized (mPackages) {
3245            final PackageParser.Package p = mPackages.get(packageName);
3246            if (p != null && p.isMatch(flags)) {
3247                return UserHandle.getUid(userId, p.applicationInfo.uid);
3248            }
3249            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3250                final PackageSetting ps = mSettings.mPackages.get(packageName);
3251                if (ps != null && ps.isMatch(flags)) {
3252                    return UserHandle.getUid(userId, ps.appId);
3253                }
3254            }
3255        }
3256
3257        return -1;
3258    }
3259
3260    @Override
3261    public int[] getPackageGids(String packageName, int flags, int userId) {
3262        if (!sUserManager.exists(userId)) return null;
3263        flags = updateFlagsForPackage(flags, userId, packageName);
3264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3265                false /* requireFullPermission */, false /* checkShell */,
3266                "getPackageGids");
3267
3268        // reader
3269        synchronized (mPackages) {
3270            final PackageParser.Package p = mPackages.get(packageName);
3271            if (p != null && p.isMatch(flags)) {
3272                PackageSetting ps = (PackageSetting) p.mExtras;
3273                return ps.getPermissionsState().computeGids(userId);
3274            }
3275            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3276                final PackageSetting ps = mSettings.mPackages.get(packageName);
3277                if (ps != null && ps.isMatch(flags)) {
3278                    return ps.getPermissionsState().computeGids(userId);
3279                }
3280            }
3281        }
3282
3283        return null;
3284    }
3285
3286    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3287        if (bp.perm != null) {
3288            return PackageParser.generatePermissionInfo(bp.perm, flags);
3289        }
3290        PermissionInfo pi = new PermissionInfo();
3291        pi.name = bp.name;
3292        pi.packageName = bp.sourcePackage;
3293        pi.nonLocalizedLabel = bp.name;
3294        pi.protectionLevel = bp.protectionLevel;
3295        return pi;
3296    }
3297
3298    @Override
3299    public PermissionInfo getPermissionInfo(String name, int flags) {
3300        // reader
3301        synchronized (mPackages) {
3302            final BasePermission p = mSettings.mPermissions.get(name);
3303            if (p != null) {
3304                return generatePermissionInfo(p, flags);
3305            }
3306            return null;
3307        }
3308    }
3309
3310    @Override
3311    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3312            int flags) {
3313        // reader
3314        synchronized (mPackages) {
3315            if (group != null && !mPermissionGroups.containsKey(group)) {
3316                // This is thrown as NameNotFoundException
3317                return null;
3318            }
3319
3320            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3321            for (BasePermission p : mSettings.mPermissions.values()) {
3322                if (group == null) {
3323                    if (p.perm == null || p.perm.info.group == null) {
3324                        out.add(generatePermissionInfo(p, flags));
3325                    }
3326                } else {
3327                    if (p.perm != null && group.equals(p.perm.info.group)) {
3328                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3329                    }
3330                }
3331            }
3332            return new ParceledListSlice<>(out);
3333        }
3334    }
3335
3336    @Override
3337    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3338        // reader
3339        synchronized (mPackages) {
3340            return PackageParser.generatePermissionGroupInfo(
3341                    mPermissionGroups.get(name), flags);
3342        }
3343    }
3344
3345    @Override
3346    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3347        // reader
3348        synchronized (mPackages) {
3349            final int N = mPermissionGroups.size();
3350            ArrayList<PermissionGroupInfo> out
3351                    = new ArrayList<PermissionGroupInfo>(N);
3352            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3353                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3354            }
3355            return new ParceledListSlice<>(out);
3356        }
3357    }
3358
3359    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3360            int userId) {
3361        if (!sUserManager.exists(userId)) return null;
3362        PackageSetting ps = mSettings.mPackages.get(packageName);
3363        if (ps != null) {
3364            if (ps.pkg == null) {
3365                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3366                if (pInfo != null) {
3367                    return pInfo.applicationInfo;
3368                }
3369                return null;
3370            }
3371            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3372                    ps.readUserState(userId), userId);
3373        }
3374        return null;
3375    }
3376
3377    @Override
3378    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3379        if (!sUserManager.exists(userId)) return null;
3380        flags = updateFlagsForApplication(flags, userId, packageName);
3381        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3382                false /* requireFullPermission */, false /* checkShell */, "get application info");
3383        // writer
3384        synchronized (mPackages) {
3385            PackageParser.Package p = mPackages.get(packageName);
3386            if (DEBUG_PACKAGE_INFO) Log.v(
3387                    TAG, "getApplicationInfo " + packageName
3388                    + ": " + p);
3389            if (p != null) {
3390                PackageSetting ps = mSettings.mPackages.get(packageName);
3391                if (ps == null) return null;
3392                // Note: isEnabledLP() does not apply here - always return info
3393                return PackageParser.generateApplicationInfo(
3394                        p, flags, ps.readUserState(userId), userId);
3395            }
3396            if ("android".equals(packageName)||"system".equals(packageName)) {
3397                return mAndroidApplication;
3398            }
3399            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3400                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3401            }
3402        }
3403        return null;
3404    }
3405
3406    @Override
3407    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3408            final IPackageDataObserver observer) {
3409        mContext.enforceCallingOrSelfPermission(
3410                android.Manifest.permission.CLEAR_APP_CACHE, null);
3411        // Queue up an async operation since clearing cache may take a little while.
3412        mHandler.post(new Runnable() {
3413            public void run() {
3414                mHandler.removeCallbacks(this);
3415                boolean success = true;
3416                synchronized (mInstallLock) {
3417                    try {
3418                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3419                    } catch (InstallerException e) {
3420                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3421                        success = false;
3422                    }
3423                }
3424                if (observer != null) {
3425                    try {
3426                        observer.onRemoveCompleted(null, success);
3427                    } catch (RemoteException e) {
3428                        Slog.w(TAG, "RemoveException when invoking call back");
3429                    }
3430                }
3431            }
3432        });
3433    }
3434
3435    @Override
3436    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3437            final IntentSender pi) {
3438        mContext.enforceCallingOrSelfPermission(
3439                android.Manifest.permission.CLEAR_APP_CACHE, null);
3440        // Queue up an async operation since clearing cache may take a little while.
3441        mHandler.post(new Runnable() {
3442            public void run() {
3443                mHandler.removeCallbacks(this);
3444                boolean success = true;
3445                synchronized (mInstallLock) {
3446                    try {
3447                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3448                    } catch (InstallerException e) {
3449                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3450                        success = false;
3451                    }
3452                }
3453                if(pi != null) {
3454                    try {
3455                        // Callback via pending intent
3456                        int code = success ? 1 : 0;
3457                        pi.sendIntent(null, code, null,
3458                                null, null);
3459                    } catch (SendIntentException e1) {
3460                        Slog.i(TAG, "Failed to send pending intent");
3461                    }
3462                }
3463            }
3464        });
3465    }
3466
3467    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3468        synchronized (mInstallLock) {
3469            try {
3470                mInstaller.freeCache(volumeUuid, freeStorageSize);
3471            } catch (InstallerException e) {
3472                throw new IOException("Failed to free enough space", e);
3473            }
3474        }
3475    }
3476
3477    /**
3478     * Update given flags based on encryption status of current user.
3479     */
3480    private int updateFlags(int flags, int userId) {
3481        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3482                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3483            // Caller expressed an explicit opinion about what encryption
3484            // aware/unaware components they want to see, so fall through and
3485            // give them what they want
3486        } else {
3487            // Caller expressed no opinion, so match based on user state
3488            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3489                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3490            } else {
3491                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3492            }
3493        }
3494        return flags;
3495    }
3496
3497    private UserManagerInternal getUserManagerInternal() {
3498        if (mUserManagerInternal == null) {
3499            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3500        }
3501        return mUserManagerInternal;
3502    }
3503
3504    /**
3505     * Update given flags when being used to request {@link PackageInfo}.
3506     */
3507    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3508        boolean triaged = true;
3509        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3510                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3511            // Caller is asking for component details, so they'd better be
3512            // asking for specific encryption matching behavior, or be triaged
3513            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3514                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3515                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3516                triaged = false;
3517            }
3518        }
3519        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3520                | PackageManager.MATCH_SYSTEM_ONLY
3521                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3522            triaged = false;
3523        }
3524        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3525            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3526                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3527        }
3528        return updateFlags(flags, userId);
3529    }
3530
3531    /**
3532     * Update given flags when being used to request {@link ApplicationInfo}.
3533     */
3534    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3535        return updateFlagsForPackage(flags, userId, cookie);
3536    }
3537
3538    /**
3539     * Update given flags when being used to request {@link ComponentInfo}.
3540     */
3541    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3542        if (cookie instanceof Intent) {
3543            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3544                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3545            }
3546        }
3547
3548        boolean triaged = true;
3549        // Caller is asking for component details, so they'd better be
3550        // asking for specific encryption matching behavior, or be triaged
3551        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3552                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3553                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3554            triaged = false;
3555        }
3556        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3557            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3558                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3559        }
3560
3561        return updateFlags(flags, userId);
3562    }
3563
3564    /**
3565     * Update given flags when being used to request {@link ResolveInfo}.
3566     */
3567    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3568        // Safe mode means we shouldn't match any third-party components
3569        if (mSafeMode) {
3570            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3571        }
3572
3573        return updateFlagsForComponent(flags, userId, cookie);
3574    }
3575
3576    @Override
3577    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3578        if (!sUserManager.exists(userId)) return null;
3579        flags = updateFlagsForComponent(flags, userId, component);
3580        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3581                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3582        synchronized (mPackages) {
3583            PackageParser.Activity a = mActivities.mActivities.get(component);
3584
3585            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3586            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3587                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3588                if (ps == null) return null;
3589                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3590                        userId);
3591            }
3592            if (mResolveComponentName.equals(component)) {
3593                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3594                        new PackageUserState(), userId);
3595            }
3596        }
3597        return null;
3598    }
3599
3600    @Override
3601    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3602            String resolvedType) {
3603        synchronized (mPackages) {
3604            if (component.equals(mResolveComponentName)) {
3605                // The resolver supports EVERYTHING!
3606                return true;
3607            }
3608            PackageParser.Activity a = mActivities.mActivities.get(component);
3609            if (a == null) {
3610                return false;
3611            }
3612            for (int i=0; i<a.intents.size(); i++) {
3613                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3614                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3615                    return true;
3616                }
3617            }
3618            return false;
3619        }
3620    }
3621
3622    @Override
3623    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3624        if (!sUserManager.exists(userId)) return null;
3625        flags = updateFlagsForComponent(flags, userId, component);
3626        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3627                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3628        synchronized (mPackages) {
3629            PackageParser.Activity a = mReceivers.mActivities.get(component);
3630            if (DEBUG_PACKAGE_INFO) Log.v(
3631                TAG, "getReceiverInfo " + component + ": " + a);
3632            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3633                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3634                if (ps == null) return null;
3635                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3636                        userId);
3637            }
3638        }
3639        return null;
3640    }
3641
3642    @Override
3643    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3644        if (!sUserManager.exists(userId)) return null;
3645        flags = updateFlagsForComponent(flags, userId, component);
3646        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3647                false /* requireFullPermission */, false /* checkShell */, "get service info");
3648        synchronized (mPackages) {
3649            PackageParser.Service s = mServices.mServices.get(component);
3650            if (DEBUG_PACKAGE_INFO) Log.v(
3651                TAG, "getServiceInfo " + component + ": " + s);
3652            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3653                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3654                if (ps == null) return null;
3655                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3656                        userId);
3657            }
3658        }
3659        return null;
3660    }
3661
3662    @Override
3663    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3664        if (!sUserManager.exists(userId)) return null;
3665        flags = updateFlagsForComponent(flags, userId, component);
3666        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3667                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3668        synchronized (mPackages) {
3669            PackageParser.Provider p = mProviders.mProviders.get(component);
3670            if (DEBUG_PACKAGE_INFO) Log.v(
3671                TAG, "getProviderInfo " + component + ": " + p);
3672            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3673                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3674                if (ps == null) return null;
3675                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3676                        userId);
3677            }
3678        }
3679        return null;
3680    }
3681
3682    @Override
3683    public String[] getSystemSharedLibraryNames() {
3684        Set<String> libSet;
3685        synchronized (mPackages) {
3686            libSet = mSharedLibraries.keySet();
3687            int size = libSet.size();
3688            if (size > 0) {
3689                String[] libs = new String[size];
3690                libSet.toArray(libs);
3691                return libs;
3692            }
3693        }
3694        return null;
3695    }
3696
3697    @Override
3698    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3699        synchronized (mPackages) {
3700            return mServicesSystemSharedLibraryPackageName;
3701        }
3702    }
3703
3704    @Override
3705    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3706        synchronized (mPackages) {
3707            return mSharedSystemSharedLibraryPackageName;
3708        }
3709    }
3710
3711    @Override
3712    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3713        synchronized (mPackages) {
3714            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3715
3716            final FeatureInfo fi = new FeatureInfo();
3717            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3718                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3719            res.add(fi);
3720
3721            return new ParceledListSlice<>(res);
3722        }
3723    }
3724
3725    @Override
3726    public boolean hasSystemFeature(String name, int version) {
3727        synchronized (mPackages) {
3728            final FeatureInfo feat = mAvailableFeatures.get(name);
3729            if (feat == null) {
3730                return false;
3731            } else {
3732                return feat.version >= version;
3733            }
3734        }
3735    }
3736
3737    @Override
3738    public int checkPermission(String permName, String pkgName, int userId) {
3739        if (!sUserManager.exists(userId)) {
3740            return PackageManager.PERMISSION_DENIED;
3741        }
3742
3743        synchronized (mPackages) {
3744            final PackageParser.Package p = mPackages.get(pkgName);
3745            if (p != null && p.mExtras != null) {
3746                final PackageSetting ps = (PackageSetting) p.mExtras;
3747                final PermissionsState permissionsState = ps.getPermissionsState();
3748                if (permissionsState.hasPermission(permName, userId)) {
3749                    return PackageManager.PERMISSION_GRANTED;
3750                }
3751                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3752                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3753                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3754                    return PackageManager.PERMISSION_GRANTED;
3755                }
3756            }
3757        }
3758
3759        return PackageManager.PERMISSION_DENIED;
3760    }
3761
3762    @Override
3763    public int checkUidPermission(String permName, int uid) {
3764        final int userId = UserHandle.getUserId(uid);
3765
3766        if (!sUserManager.exists(userId)) {
3767            return PackageManager.PERMISSION_DENIED;
3768        }
3769
3770        synchronized (mPackages) {
3771            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3772            if (obj != null) {
3773                final SettingBase ps = (SettingBase) obj;
3774                final PermissionsState permissionsState = ps.getPermissionsState();
3775                if (permissionsState.hasPermission(permName, userId)) {
3776                    return PackageManager.PERMISSION_GRANTED;
3777                }
3778                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3779                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3780                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3781                    return PackageManager.PERMISSION_GRANTED;
3782                }
3783            } else {
3784                ArraySet<String> perms = mSystemPermissions.get(uid);
3785                if (perms != null) {
3786                    if (perms.contains(permName)) {
3787                        return PackageManager.PERMISSION_GRANTED;
3788                    }
3789                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3790                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3791                        return PackageManager.PERMISSION_GRANTED;
3792                    }
3793                }
3794            }
3795        }
3796
3797        return PackageManager.PERMISSION_DENIED;
3798    }
3799
3800    @Override
3801    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3802        if (UserHandle.getCallingUserId() != userId) {
3803            mContext.enforceCallingPermission(
3804                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3805                    "isPermissionRevokedByPolicy for user " + userId);
3806        }
3807
3808        if (checkPermission(permission, packageName, userId)
3809                == PackageManager.PERMISSION_GRANTED) {
3810            return false;
3811        }
3812
3813        final long identity = Binder.clearCallingIdentity();
3814        try {
3815            final int flags = getPermissionFlags(permission, packageName, userId);
3816            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3817        } finally {
3818            Binder.restoreCallingIdentity(identity);
3819        }
3820    }
3821
3822    @Override
3823    public String getPermissionControllerPackageName() {
3824        synchronized (mPackages) {
3825            return mRequiredInstallerPackage;
3826        }
3827    }
3828
3829    /**
3830     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3831     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3832     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3833     * @param message the message to log on security exception
3834     */
3835    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3836            boolean checkShell, String message) {
3837        if (userId < 0) {
3838            throw new IllegalArgumentException("Invalid userId " + userId);
3839        }
3840        if (checkShell) {
3841            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3842        }
3843        if (userId == UserHandle.getUserId(callingUid)) return;
3844        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3845            if (requireFullPermission) {
3846                mContext.enforceCallingOrSelfPermission(
3847                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3848            } else {
3849                try {
3850                    mContext.enforceCallingOrSelfPermission(
3851                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3852                } catch (SecurityException se) {
3853                    mContext.enforceCallingOrSelfPermission(
3854                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3855                }
3856            }
3857        }
3858    }
3859
3860    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3861        if (callingUid == Process.SHELL_UID) {
3862            if (userHandle >= 0
3863                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3864                throw new SecurityException("Shell does not have permission to access user "
3865                        + userHandle);
3866            } else if (userHandle < 0) {
3867                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3868                        + Debug.getCallers(3));
3869            }
3870        }
3871    }
3872
3873    private BasePermission findPermissionTreeLP(String permName) {
3874        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3875            if (permName.startsWith(bp.name) &&
3876                    permName.length() > bp.name.length() &&
3877                    permName.charAt(bp.name.length()) == '.') {
3878                return bp;
3879            }
3880        }
3881        return null;
3882    }
3883
3884    private BasePermission checkPermissionTreeLP(String permName) {
3885        if (permName != null) {
3886            BasePermission bp = findPermissionTreeLP(permName);
3887            if (bp != null) {
3888                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3889                    return bp;
3890                }
3891                throw new SecurityException("Calling uid "
3892                        + Binder.getCallingUid()
3893                        + " is not allowed to add to permission tree "
3894                        + bp.name + " owned by uid " + bp.uid);
3895            }
3896        }
3897        throw new SecurityException("No permission tree found for " + permName);
3898    }
3899
3900    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3901        if (s1 == null) {
3902            return s2 == null;
3903        }
3904        if (s2 == null) {
3905            return false;
3906        }
3907        if (s1.getClass() != s2.getClass()) {
3908            return false;
3909        }
3910        return s1.equals(s2);
3911    }
3912
3913    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3914        if (pi1.icon != pi2.icon) return false;
3915        if (pi1.logo != pi2.logo) return false;
3916        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3917        if (!compareStrings(pi1.name, pi2.name)) return false;
3918        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3919        // We'll take care of setting this one.
3920        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3921        // These are not currently stored in settings.
3922        //if (!compareStrings(pi1.group, pi2.group)) return false;
3923        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3924        //if (pi1.labelRes != pi2.labelRes) return false;
3925        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3926        return true;
3927    }
3928
3929    int permissionInfoFootprint(PermissionInfo info) {
3930        int size = info.name.length();
3931        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3932        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3933        return size;
3934    }
3935
3936    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3937        int size = 0;
3938        for (BasePermission perm : mSettings.mPermissions.values()) {
3939            if (perm.uid == tree.uid) {
3940                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3941            }
3942        }
3943        return size;
3944    }
3945
3946    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3947        // We calculate the max size of permissions defined by this uid and throw
3948        // if that plus the size of 'info' would exceed our stated maximum.
3949        if (tree.uid != Process.SYSTEM_UID) {
3950            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3951            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3952                throw new SecurityException("Permission tree size cap exceeded");
3953            }
3954        }
3955    }
3956
3957    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3958        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3959            throw new SecurityException("Label must be specified in permission");
3960        }
3961        BasePermission tree = checkPermissionTreeLP(info.name);
3962        BasePermission bp = mSettings.mPermissions.get(info.name);
3963        boolean added = bp == null;
3964        boolean changed = true;
3965        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3966        if (added) {
3967            enforcePermissionCapLocked(info, tree);
3968            bp = new BasePermission(info.name, tree.sourcePackage,
3969                    BasePermission.TYPE_DYNAMIC);
3970        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3971            throw new SecurityException(
3972                    "Not allowed to modify non-dynamic permission "
3973                    + info.name);
3974        } else {
3975            if (bp.protectionLevel == fixedLevel
3976                    && bp.perm.owner.equals(tree.perm.owner)
3977                    && bp.uid == tree.uid
3978                    && comparePermissionInfos(bp.perm.info, info)) {
3979                changed = false;
3980            }
3981        }
3982        bp.protectionLevel = fixedLevel;
3983        info = new PermissionInfo(info);
3984        info.protectionLevel = fixedLevel;
3985        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3986        bp.perm.info.packageName = tree.perm.info.packageName;
3987        bp.uid = tree.uid;
3988        if (added) {
3989            mSettings.mPermissions.put(info.name, bp);
3990        }
3991        if (changed) {
3992            if (!async) {
3993                mSettings.writeLPr();
3994            } else {
3995                scheduleWriteSettingsLocked();
3996            }
3997        }
3998        return added;
3999    }
4000
4001    @Override
4002    public boolean addPermission(PermissionInfo info) {
4003        synchronized (mPackages) {
4004            return addPermissionLocked(info, false);
4005        }
4006    }
4007
4008    @Override
4009    public boolean addPermissionAsync(PermissionInfo info) {
4010        synchronized (mPackages) {
4011            return addPermissionLocked(info, true);
4012        }
4013    }
4014
4015    @Override
4016    public void removePermission(String name) {
4017        synchronized (mPackages) {
4018            checkPermissionTreeLP(name);
4019            BasePermission bp = mSettings.mPermissions.get(name);
4020            if (bp != null) {
4021                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4022                    throw new SecurityException(
4023                            "Not allowed to modify non-dynamic permission "
4024                            + name);
4025                }
4026                mSettings.mPermissions.remove(name);
4027                mSettings.writeLPr();
4028            }
4029        }
4030    }
4031
4032    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4033            BasePermission bp) {
4034        int index = pkg.requestedPermissions.indexOf(bp.name);
4035        if (index == -1) {
4036            throw new SecurityException("Package " + pkg.packageName
4037                    + " has not requested permission " + bp.name);
4038        }
4039        if (!bp.isRuntime() && !bp.isDevelopment()) {
4040            throw new SecurityException("Permission " + bp.name
4041                    + " is not a changeable permission type");
4042        }
4043    }
4044
4045    @Override
4046    public void grantRuntimePermission(String packageName, String name, final int userId) {
4047        if (!sUserManager.exists(userId)) {
4048            Log.e(TAG, "No such user:" + userId);
4049            return;
4050        }
4051
4052        mContext.enforceCallingOrSelfPermission(
4053                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4054                "grantRuntimePermission");
4055
4056        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4057                true /* requireFullPermission */, true /* checkShell */,
4058                "grantRuntimePermission");
4059
4060        final int uid;
4061        final SettingBase sb;
4062
4063        synchronized (mPackages) {
4064            final PackageParser.Package pkg = mPackages.get(packageName);
4065            if (pkg == null) {
4066                throw new IllegalArgumentException("Unknown package: " + packageName);
4067            }
4068
4069            final BasePermission bp = mSettings.mPermissions.get(name);
4070            if (bp == null) {
4071                throw new IllegalArgumentException("Unknown permission: " + name);
4072            }
4073
4074            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4075
4076            // If a permission review is required for legacy apps we represent
4077            // their permissions as always granted runtime ones since we need
4078            // to keep the review required permission flag per user while an
4079            // install permission's state is shared across all users.
4080            if (Build.PERMISSIONS_REVIEW_REQUIRED
4081                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4082                    && bp.isRuntime()) {
4083                return;
4084            }
4085
4086            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4087            sb = (SettingBase) pkg.mExtras;
4088            if (sb == null) {
4089                throw new IllegalArgumentException("Unknown package: " + packageName);
4090            }
4091
4092            final PermissionsState permissionsState = sb.getPermissionsState();
4093
4094            final int flags = permissionsState.getPermissionFlags(name, userId);
4095            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4096                throw new SecurityException("Cannot grant system fixed permission "
4097                        + name + " for package " + packageName);
4098            }
4099
4100            if (bp.isDevelopment()) {
4101                // Development permissions must be handled specially, since they are not
4102                // normal runtime permissions.  For now they apply to all users.
4103                if (permissionsState.grantInstallPermission(bp) !=
4104                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4105                    scheduleWriteSettingsLocked();
4106                }
4107                return;
4108            }
4109
4110            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4111                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4112                return;
4113            }
4114
4115            final int result = permissionsState.grantRuntimePermission(bp, userId);
4116            switch (result) {
4117                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4118                    return;
4119                }
4120
4121                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4122                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4123                    mHandler.post(new Runnable() {
4124                        @Override
4125                        public void run() {
4126                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4127                        }
4128                    });
4129                }
4130                break;
4131            }
4132
4133            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4134
4135            // Not critical if that is lost - app has to request again.
4136            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4137        }
4138
4139        // Only need to do this if user is initialized. Otherwise it's a new user
4140        // and there are no processes running as the user yet and there's no need
4141        // to make an expensive call to remount processes for the changed permissions.
4142        if (READ_EXTERNAL_STORAGE.equals(name)
4143                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4144            final long token = Binder.clearCallingIdentity();
4145            try {
4146                if (sUserManager.isInitialized(userId)) {
4147                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4148                            MountServiceInternal.class);
4149                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4150                }
4151            } finally {
4152                Binder.restoreCallingIdentity(token);
4153            }
4154        }
4155    }
4156
4157    @Override
4158    public void revokeRuntimePermission(String packageName, String name, int userId) {
4159        if (!sUserManager.exists(userId)) {
4160            Log.e(TAG, "No such user:" + userId);
4161            return;
4162        }
4163
4164        mContext.enforceCallingOrSelfPermission(
4165                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4166                "revokeRuntimePermission");
4167
4168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4169                true /* requireFullPermission */, true /* checkShell */,
4170                "revokeRuntimePermission");
4171
4172        final int appId;
4173
4174        synchronized (mPackages) {
4175            final PackageParser.Package pkg = mPackages.get(packageName);
4176            if (pkg == null) {
4177                throw new IllegalArgumentException("Unknown package: " + packageName);
4178            }
4179
4180            final BasePermission bp = mSettings.mPermissions.get(name);
4181            if (bp == null) {
4182                throw new IllegalArgumentException("Unknown permission: " + name);
4183            }
4184
4185            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4186
4187            // If a permission review is required for legacy apps we represent
4188            // their permissions as always granted runtime ones since we need
4189            // to keep the review required permission flag per user while an
4190            // install permission's state is shared across all users.
4191            if (Build.PERMISSIONS_REVIEW_REQUIRED
4192                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4193                    && bp.isRuntime()) {
4194                return;
4195            }
4196
4197            SettingBase sb = (SettingBase) pkg.mExtras;
4198            if (sb == null) {
4199                throw new IllegalArgumentException("Unknown package: " + packageName);
4200            }
4201
4202            final PermissionsState permissionsState = sb.getPermissionsState();
4203
4204            final int flags = permissionsState.getPermissionFlags(name, userId);
4205            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4206                throw new SecurityException("Cannot revoke system fixed permission "
4207                        + name + " for package " + packageName);
4208            }
4209
4210            if (bp.isDevelopment()) {
4211                // Development permissions must be handled specially, since they are not
4212                // normal runtime permissions.  For now they apply to all users.
4213                if (permissionsState.revokeInstallPermission(bp) !=
4214                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4215                    scheduleWriteSettingsLocked();
4216                }
4217                return;
4218            }
4219
4220            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4221                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4222                return;
4223            }
4224
4225            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4226
4227            // Critical, after this call app should never have the permission.
4228            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4229
4230            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4231        }
4232
4233        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4234    }
4235
4236    @Override
4237    public void resetRuntimePermissions() {
4238        mContext.enforceCallingOrSelfPermission(
4239                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4240                "revokeRuntimePermission");
4241
4242        int callingUid = Binder.getCallingUid();
4243        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4244            mContext.enforceCallingOrSelfPermission(
4245                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4246                    "resetRuntimePermissions");
4247        }
4248
4249        synchronized (mPackages) {
4250            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4251            for (int userId : UserManagerService.getInstance().getUserIds()) {
4252                final int packageCount = mPackages.size();
4253                for (int i = 0; i < packageCount; i++) {
4254                    PackageParser.Package pkg = mPackages.valueAt(i);
4255                    if (!(pkg.mExtras instanceof PackageSetting)) {
4256                        continue;
4257                    }
4258                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4259                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4260                }
4261            }
4262        }
4263    }
4264
4265    @Override
4266    public int getPermissionFlags(String name, String packageName, int userId) {
4267        if (!sUserManager.exists(userId)) {
4268            return 0;
4269        }
4270
4271        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4272
4273        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4274                true /* requireFullPermission */, false /* checkShell */,
4275                "getPermissionFlags");
4276
4277        synchronized (mPackages) {
4278            final PackageParser.Package pkg = mPackages.get(packageName);
4279            if (pkg == null) {
4280                return 0;
4281            }
4282
4283            final BasePermission bp = mSettings.mPermissions.get(name);
4284            if (bp == null) {
4285                return 0;
4286            }
4287
4288            SettingBase sb = (SettingBase) pkg.mExtras;
4289            if (sb == null) {
4290                return 0;
4291            }
4292
4293            PermissionsState permissionsState = sb.getPermissionsState();
4294            return permissionsState.getPermissionFlags(name, userId);
4295        }
4296    }
4297
4298    @Override
4299    public void updatePermissionFlags(String name, String packageName, int flagMask,
4300            int flagValues, int userId) {
4301        if (!sUserManager.exists(userId)) {
4302            return;
4303        }
4304
4305        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4306
4307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4308                true /* requireFullPermission */, true /* checkShell */,
4309                "updatePermissionFlags");
4310
4311        // Only the system can change these flags and nothing else.
4312        if (getCallingUid() != Process.SYSTEM_UID) {
4313            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4314            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4315            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4316            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4317            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4318        }
4319
4320        synchronized (mPackages) {
4321            final PackageParser.Package pkg = mPackages.get(packageName);
4322            if (pkg == null) {
4323                throw new IllegalArgumentException("Unknown package: " + packageName);
4324            }
4325
4326            final BasePermission bp = mSettings.mPermissions.get(name);
4327            if (bp == null) {
4328                throw new IllegalArgumentException("Unknown permission: " + name);
4329            }
4330
4331            SettingBase sb = (SettingBase) pkg.mExtras;
4332            if (sb == null) {
4333                throw new IllegalArgumentException("Unknown package: " + packageName);
4334            }
4335
4336            PermissionsState permissionsState = sb.getPermissionsState();
4337
4338            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4339
4340            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4341                // Install and runtime permissions are stored in different places,
4342                // so figure out what permission changed and persist the change.
4343                if (permissionsState.getInstallPermissionState(name) != null) {
4344                    scheduleWriteSettingsLocked();
4345                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4346                        || hadState) {
4347                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4348                }
4349            }
4350        }
4351    }
4352
4353    /**
4354     * Update the permission flags for all packages and runtime permissions of a user in order
4355     * to allow device or profile owner to remove POLICY_FIXED.
4356     */
4357    @Override
4358    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4359        if (!sUserManager.exists(userId)) {
4360            return;
4361        }
4362
4363        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4364
4365        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4366                true /* requireFullPermission */, true /* checkShell */,
4367                "updatePermissionFlagsForAllApps");
4368
4369        // Only the system can change system fixed flags.
4370        if (getCallingUid() != Process.SYSTEM_UID) {
4371            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4372            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4373        }
4374
4375        synchronized (mPackages) {
4376            boolean changed = false;
4377            final int packageCount = mPackages.size();
4378            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4379                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4380                SettingBase sb = (SettingBase) pkg.mExtras;
4381                if (sb == null) {
4382                    continue;
4383                }
4384                PermissionsState permissionsState = sb.getPermissionsState();
4385                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4386                        userId, flagMask, flagValues);
4387            }
4388            if (changed) {
4389                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4390            }
4391        }
4392    }
4393
4394    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4395        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4396                != PackageManager.PERMISSION_GRANTED
4397            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4398                != PackageManager.PERMISSION_GRANTED) {
4399            throw new SecurityException(message + " requires "
4400                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4401                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4402        }
4403    }
4404
4405    @Override
4406    public boolean shouldShowRequestPermissionRationale(String permissionName,
4407            String packageName, int userId) {
4408        if (UserHandle.getCallingUserId() != userId) {
4409            mContext.enforceCallingPermission(
4410                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4411                    "canShowRequestPermissionRationale for user " + userId);
4412        }
4413
4414        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4415        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4416            return false;
4417        }
4418
4419        if (checkPermission(permissionName, packageName, userId)
4420                == PackageManager.PERMISSION_GRANTED) {
4421            return false;
4422        }
4423
4424        final int flags;
4425
4426        final long identity = Binder.clearCallingIdentity();
4427        try {
4428            flags = getPermissionFlags(permissionName,
4429                    packageName, userId);
4430        } finally {
4431            Binder.restoreCallingIdentity(identity);
4432        }
4433
4434        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4435                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4436                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4437
4438        if ((flags & fixedFlags) != 0) {
4439            return false;
4440        }
4441
4442        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4443    }
4444
4445    @Override
4446    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4447        mContext.enforceCallingOrSelfPermission(
4448                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4449                "addOnPermissionsChangeListener");
4450
4451        synchronized (mPackages) {
4452            mOnPermissionChangeListeners.addListenerLocked(listener);
4453        }
4454    }
4455
4456    @Override
4457    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4458        synchronized (mPackages) {
4459            mOnPermissionChangeListeners.removeListenerLocked(listener);
4460        }
4461    }
4462
4463    @Override
4464    public boolean isProtectedBroadcast(String actionName) {
4465        synchronized (mPackages) {
4466            if (mProtectedBroadcasts.contains(actionName)) {
4467                return true;
4468            } else if (actionName != null) {
4469                // TODO: remove these terrible hacks
4470                if (actionName.startsWith("android.net.netmon.lingerExpired")
4471                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4472                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4473                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4474                    return true;
4475                }
4476            }
4477        }
4478        return false;
4479    }
4480
4481    @Override
4482    public int checkSignatures(String pkg1, String pkg2) {
4483        synchronized (mPackages) {
4484            final PackageParser.Package p1 = mPackages.get(pkg1);
4485            final PackageParser.Package p2 = mPackages.get(pkg2);
4486            if (p1 == null || p1.mExtras == null
4487                    || p2 == null || p2.mExtras == null) {
4488                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4489            }
4490            return compareSignatures(p1.mSignatures, p2.mSignatures);
4491        }
4492    }
4493
4494    @Override
4495    public int checkUidSignatures(int uid1, int uid2) {
4496        // Map to base uids.
4497        uid1 = UserHandle.getAppId(uid1);
4498        uid2 = UserHandle.getAppId(uid2);
4499        // reader
4500        synchronized (mPackages) {
4501            Signature[] s1;
4502            Signature[] s2;
4503            Object obj = mSettings.getUserIdLPr(uid1);
4504            if (obj != null) {
4505                if (obj instanceof SharedUserSetting) {
4506                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4507                } else if (obj instanceof PackageSetting) {
4508                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4509                } else {
4510                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4511                }
4512            } else {
4513                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4514            }
4515            obj = mSettings.getUserIdLPr(uid2);
4516            if (obj != null) {
4517                if (obj instanceof SharedUserSetting) {
4518                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4519                } else if (obj instanceof PackageSetting) {
4520                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4521                } else {
4522                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4523                }
4524            } else {
4525                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4526            }
4527            return compareSignatures(s1, s2);
4528        }
4529    }
4530
4531    /**
4532     * This method should typically only be used when granting or revoking
4533     * permissions, since the app may immediately restart after this call.
4534     * <p>
4535     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4536     * guard your work against the app being relaunched.
4537     */
4538    private void killUid(int appId, int userId, String reason) {
4539        final long identity = Binder.clearCallingIdentity();
4540        try {
4541            IActivityManager am = ActivityManagerNative.getDefault();
4542            if (am != null) {
4543                try {
4544                    am.killUid(appId, userId, reason);
4545                } catch (RemoteException e) {
4546                    /* ignore - same process */
4547                }
4548            }
4549        } finally {
4550            Binder.restoreCallingIdentity(identity);
4551        }
4552    }
4553
4554    /**
4555     * Compares two sets of signatures. Returns:
4556     * <br />
4557     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4558     * <br />
4559     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4560     * <br />
4561     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4562     * <br />
4563     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4564     * <br />
4565     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4566     */
4567    static int compareSignatures(Signature[] s1, Signature[] s2) {
4568        if (s1 == null) {
4569            return s2 == null
4570                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4571                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4572        }
4573
4574        if (s2 == null) {
4575            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4576        }
4577
4578        if (s1.length != s2.length) {
4579            return PackageManager.SIGNATURE_NO_MATCH;
4580        }
4581
4582        // Since both signature sets are of size 1, we can compare without HashSets.
4583        if (s1.length == 1) {
4584            return s1[0].equals(s2[0]) ?
4585                    PackageManager.SIGNATURE_MATCH :
4586                    PackageManager.SIGNATURE_NO_MATCH;
4587        }
4588
4589        ArraySet<Signature> set1 = new ArraySet<Signature>();
4590        for (Signature sig : s1) {
4591            set1.add(sig);
4592        }
4593        ArraySet<Signature> set2 = new ArraySet<Signature>();
4594        for (Signature sig : s2) {
4595            set2.add(sig);
4596        }
4597        // Make sure s2 contains all signatures in s1.
4598        if (set1.equals(set2)) {
4599            return PackageManager.SIGNATURE_MATCH;
4600        }
4601        return PackageManager.SIGNATURE_NO_MATCH;
4602    }
4603
4604    /**
4605     * If the database version for this type of package (internal storage or
4606     * external storage) is less than the version where package signatures
4607     * were updated, return true.
4608     */
4609    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4610        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4611        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4612    }
4613
4614    /**
4615     * Used for backward compatibility to make sure any packages with
4616     * certificate chains get upgraded to the new style. {@code existingSigs}
4617     * will be in the old format (since they were stored on disk from before the
4618     * system upgrade) and {@code scannedSigs} will be in the newer format.
4619     */
4620    private int compareSignaturesCompat(PackageSignatures existingSigs,
4621            PackageParser.Package scannedPkg) {
4622        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4623            return PackageManager.SIGNATURE_NO_MATCH;
4624        }
4625
4626        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4627        for (Signature sig : existingSigs.mSignatures) {
4628            existingSet.add(sig);
4629        }
4630        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4631        for (Signature sig : scannedPkg.mSignatures) {
4632            try {
4633                Signature[] chainSignatures = sig.getChainSignatures();
4634                for (Signature chainSig : chainSignatures) {
4635                    scannedCompatSet.add(chainSig);
4636                }
4637            } catch (CertificateEncodingException e) {
4638                scannedCompatSet.add(sig);
4639            }
4640        }
4641        /*
4642         * Make sure the expanded scanned set contains all signatures in the
4643         * existing one.
4644         */
4645        if (scannedCompatSet.equals(existingSet)) {
4646            // Migrate the old signatures to the new scheme.
4647            existingSigs.assignSignatures(scannedPkg.mSignatures);
4648            // The new KeySets will be re-added later in the scanning process.
4649            synchronized (mPackages) {
4650                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4651            }
4652            return PackageManager.SIGNATURE_MATCH;
4653        }
4654        return PackageManager.SIGNATURE_NO_MATCH;
4655    }
4656
4657    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4658        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4659        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4660    }
4661
4662    private int compareSignaturesRecover(PackageSignatures existingSigs,
4663            PackageParser.Package scannedPkg) {
4664        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4665            return PackageManager.SIGNATURE_NO_MATCH;
4666        }
4667
4668        String msg = null;
4669        try {
4670            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4671                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4672                        + scannedPkg.packageName);
4673                return PackageManager.SIGNATURE_MATCH;
4674            }
4675        } catch (CertificateException e) {
4676            msg = e.getMessage();
4677        }
4678
4679        logCriticalInfo(Log.INFO,
4680                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4681        return PackageManager.SIGNATURE_NO_MATCH;
4682    }
4683
4684    @Override
4685    public List<String> getAllPackages() {
4686        synchronized (mPackages) {
4687            return new ArrayList<String>(mPackages.keySet());
4688        }
4689    }
4690
4691    @Override
4692    public String[] getPackagesForUid(int uid) {
4693        uid = UserHandle.getAppId(uid);
4694        // reader
4695        synchronized (mPackages) {
4696            Object obj = mSettings.getUserIdLPr(uid);
4697            if (obj instanceof SharedUserSetting) {
4698                final SharedUserSetting sus = (SharedUserSetting) obj;
4699                final int N = sus.packages.size();
4700                final String[] res = new String[N];
4701                final Iterator<PackageSetting> it = sus.packages.iterator();
4702                int i = 0;
4703                while (it.hasNext()) {
4704                    res[i++] = it.next().name;
4705                }
4706                return res;
4707            } else if (obj instanceof PackageSetting) {
4708                final PackageSetting ps = (PackageSetting) obj;
4709                return new String[] { ps.name };
4710            }
4711        }
4712        return null;
4713    }
4714
4715    @Override
4716    public String getNameForUid(int uid) {
4717        // reader
4718        synchronized (mPackages) {
4719            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4720            if (obj instanceof SharedUserSetting) {
4721                final SharedUserSetting sus = (SharedUserSetting) obj;
4722                return sus.name + ":" + sus.userId;
4723            } else if (obj instanceof PackageSetting) {
4724                final PackageSetting ps = (PackageSetting) obj;
4725                return ps.name;
4726            }
4727        }
4728        return null;
4729    }
4730
4731    @Override
4732    public int getUidForSharedUser(String sharedUserName) {
4733        if(sharedUserName == null) {
4734            return -1;
4735        }
4736        // reader
4737        synchronized (mPackages) {
4738            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4739            if (suid == null) {
4740                return -1;
4741            }
4742            return suid.userId;
4743        }
4744    }
4745
4746    @Override
4747    public int getFlagsForUid(int uid) {
4748        synchronized (mPackages) {
4749            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4750            if (obj instanceof SharedUserSetting) {
4751                final SharedUserSetting sus = (SharedUserSetting) obj;
4752                return sus.pkgFlags;
4753            } else if (obj instanceof PackageSetting) {
4754                final PackageSetting ps = (PackageSetting) obj;
4755                return ps.pkgFlags;
4756            }
4757        }
4758        return 0;
4759    }
4760
4761    @Override
4762    public int getPrivateFlagsForUid(int uid) {
4763        synchronized (mPackages) {
4764            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4765            if (obj instanceof SharedUserSetting) {
4766                final SharedUserSetting sus = (SharedUserSetting) obj;
4767                return sus.pkgPrivateFlags;
4768            } else if (obj instanceof PackageSetting) {
4769                final PackageSetting ps = (PackageSetting) obj;
4770                return ps.pkgPrivateFlags;
4771            }
4772        }
4773        return 0;
4774    }
4775
4776    @Override
4777    public boolean isUidPrivileged(int uid) {
4778        uid = UserHandle.getAppId(uid);
4779        // reader
4780        synchronized (mPackages) {
4781            Object obj = mSettings.getUserIdLPr(uid);
4782            if (obj instanceof SharedUserSetting) {
4783                final SharedUserSetting sus = (SharedUserSetting) obj;
4784                final Iterator<PackageSetting> it = sus.packages.iterator();
4785                while (it.hasNext()) {
4786                    if (it.next().isPrivileged()) {
4787                        return true;
4788                    }
4789                }
4790            } else if (obj instanceof PackageSetting) {
4791                final PackageSetting ps = (PackageSetting) obj;
4792                return ps.isPrivileged();
4793            }
4794        }
4795        return false;
4796    }
4797
4798    @Override
4799    public String[] getAppOpPermissionPackages(String permissionName) {
4800        synchronized (mPackages) {
4801            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4802            if (pkgs == null) {
4803                return null;
4804            }
4805            return pkgs.toArray(new String[pkgs.size()]);
4806        }
4807    }
4808
4809    @Override
4810    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4811            int flags, int userId) {
4812        try {
4813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4814
4815            if (!sUserManager.exists(userId)) return null;
4816            flags = updateFlagsForResolve(flags, userId, intent);
4817            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4818                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4819
4820            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4821            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4822                    flags, userId);
4823            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4824
4825            final ResolveInfo bestChoice =
4826                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4827
4828            if (isEphemeralAllowed(intent, query, userId)) {
4829                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4830                final EphemeralResolveInfo ai =
4831                        getEphemeralResolveInfo(intent, resolvedType, userId);
4832                if (ai != null) {
4833                    if (DEBUG_EPHEMERAL) {
4834                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4835                    }
4836                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4837                    bestChoice.ephemeralResolveInfo = ai;
4838                }
4839                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4840            }
4841            return bestChoice;
4842        } finally {
4843            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4844        }
4845    }
4846
4847    @Override
4848    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4849            IntentFilter filter, int match, ComponentName activity) {
4850        final int userId = UserHandle.getCallingUserId();
4851        if (DEBUG_PREFERRED) {
4852            Log.v(TAG, "setLastChosenActivity intent=" + intent
4853                + " resolvedType=" + resolvedType
4854                + " flags=" + flags
4855                + " filter=" + filter
4856                + " match=" + match
4857                + " activity=" + activity);
4858            filter.dump(new PrintStreamPrinter(System.out), "    ");
4859        }
4860        intent.setComponent(null);
4861        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4862                userId);
4863        // Find any earlier preferred or last chosen entries and nuke them
4864        findPreferredActivity(intent, resolvedType,
4865                flags, query, 0, false, true, false, userId);
4866        // Add the new activity as the last chosen for this filter
4867        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4868                "Setting last chosen");
4869    }
4870
4871    @Override
4872    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4873        final int userId = UserHandle.getCallingUserId();
4874        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4875        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4876                userId);
4877        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4878                false, false, false, userId);
4879    }
4880
4881
4882    private boolean isEphemeralAllowed(
4883            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4884        // Short circuit and return early if possible.
4885        if (DISABLE_EPHEMERAL_APPS) {
4886            return false;
4887        }
4888        final int callingUser = UserHandle.getCallingUserId();
4889        if (callingUser != UserHandle.USER_SYSTEM) {
4890            return false;
4891        }
4892        if (mEphemeralResolverConnection == null) {
4893            return false;
4894        }
4895        if (intent.getComponent() != null) {
4896            return false;
4897        }
4898        if (intent.getPackage() != null) {
4899            return false;
4900        }
4901        final boolean isWebUri = hasWebURI(intent);
4902        if (!isWebUri) {
4903            return false;
4904        }
4905        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4906        synchronized (mPackages) {
4907            final int count = resolvedActivites.size();
4908            for (int n = 0; n < count; n++) {
4909                ResolveInfo info = resolvedActivites.get(n);
4910                String packageName = info.activityInfo.packageName;
4911                PackageSetting ps = mSettings.mPackages.get(packageName);
4912                if (ps != null) {
4913                    // Try to get the status from User settings first
4914                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4915                    int status = (int) (packedStatus >> 32);
4916                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4917                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4918                        if (DEBUG_EPHEMERAL) {
4919                            Slog.v(TAG, "DENY ephemeral apps;"
4920                                + " pkg: " + packageName + ", status: " + status);
4921                        }
4922                        return false;
4923                    }
4924                }
4925            }
4926        }
4927        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4928        return true;
4929    }
4930
4931    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4932            int userId) {
4933        MessageDigest digest = null;
4934        try {
4935            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4936        } catch (NoSuchAlgorithmException e) {
4937            // If we can't create a digest, ignore ephemeral apps.
4938            return null;
4939        }
4940
4941        final byte[] hostBytes = intent.getData().getHost().getBytes();
4942        final byte[] digestBytes = digest.digest(hostBytes);
4943        int shaPrefix =
4944                digestBytes[0] << 24
4945                | digestBytes[1] << 16
4946                | digestBytes[2] << 8
4947                | digestBytes[3] << 0;
4948        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4949                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4950        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4951            // No hash prefix match; there are no ephemeral apps for this domain.
4952            return null;
4953        }
4954        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4955            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4956            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4957                continue;
4958            }
4959            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4960            // No filters; this should never happen.
4961            if (filters.isEmpty()) {
4962                continue;
4963            }
4964            // We have a domain match; resolve the filters to see if anything matches.
4965            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4966            for (int j = filters.size() - 1; j >= 0; --j) {
4967                final EphemeralResolveIntentInfo intentInfo =
4968                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4969                ephemeralResolver.addFilter(intentInfo);
4970            }
4971            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4972                    intent, resolvedType, false /*defaultOnly*/, userId);
4973            if (!matchedResolveInfoList.isEmpty()) {
4974                return matchedResolveInfoList.get(0);
4975            }
4976        }
4977        // Hash or filter mis-match; no ephemeral apps for this domain.
4978        return null;
4979    }
4980
4981    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4982            int flags, List<ResolveInfo> query, int userId) {
4983        if (query != null) {
4984            final int N = query.size();
4985            if (N == 1) {
4986                return query.get(0);
4987            } else if (N > 1) {
4988                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4989                // If there is more than one activity with the same priority,
4990                // then let the user decide between them.
4991                ResolveInfo r0 = query.get(0);
4992                ResolveInfo r1 = query.get(1);
4993                if (DEBUG_INTENT_MATCHING || debug) {
4994                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4995                            + r1.activityInfo.name + "=" + r1.priority);
4996                }
4997                // If the first activity has a higher priority, or a different
4998                // default, then it is always desirable to pick it.
4999                if (r0.priority != r1.priority
5000                        || r0.preferredOrder != r1.preferredOrder
5001                        || r0.isDefault != r1.isDefault) {
5002                    return query.get(0);
5003                }
5004                // If we have saved a preference for a preferred activity for
5005                // this Intent, use that.
5006                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5007                        flags, query, r0.priority, true, false, debug, userId);
5008                if (ri != null) {
5009                    return ri;
5010                }
5011                ri = new ResolveInfo(mResolveInfo);
5012                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5013                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5014                // If all of the options come from the same package, show the application's
5015                // label and icon instead of the generic resolver's.
5016                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5017                // and then throw away the ResolveInfo itself, meaning that the caller loses
5018                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5019                // a fallback for this case; we only set the target package's resources on
5020                // the ResolveInfo, not the ActivityInfo.
5021                final String intentPackage = intent.getPackage();
5022                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5023                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5024                    ri.resolvePackageName = intentPackage;
5025                    if (userNeedsBadging(userId)) {
5026                        ri.noResourceId = true;
5027                    } else {
5028                        ri.icon = appi.icon;
5029                    }
5030                    ri.iconResourceId = appi.icon;
5031                    ri.labelRes = appi.labelRes;
5032                }
5033                ri.activityInfo.applicationInfo = new ApplicationInfo(
5034                        ri.activityInfo.applicationInfo);
5035                if (userId != 0) {
5036                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5037                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5038                }
5039                // Make sure that the resolver is displayable in car mode
5040                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5041                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5042                return ri;
5043            }
5044        }
5045        return null;
5046    }
5047
5048    /**
5049     * Return true if the given list is not empty and all of its contents have
5050     * an activityInfo with the given package name.
5051     */
5052    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5053        if (ArrayUtils.isEmpty(list)) {
5054            return false;
5055        }
5056        for (int i = 0, N = list.size(); i < N; i++) {
5057            final ResolveInfo ri = list.get(i);
5058            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5059            if (ai == null || !packageName.equals(ai.packageName)) {
5060                return false;
5061            }
5062        }
5063        return true;
5064    }
5065
5066    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5067            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5068        final int N = query.size();
5069        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5070                .get(userId);
5071        // Get the list of persistent preferred activities that handle the intent
5072        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5073        List<PersistentPreferredActivity> pprefs = ppir != null
5074                ? ppir.queryIntent(intent, resolvedType,
5075                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5076                : null;
5077        if (pprefs != null && pprefs.size() > 0) {
5078            final int M = pprefs.size();
5079            for (int i=0; i<M; i++) {
5080                final PersistentPreferredActivity ppa = pprefs.get(i);
5081                if (DEBUG_PREFERRED || debug) {
5082                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5083                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5084                            + "\n  component=" + ppa.mComponent);
5085                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5086                }
5087                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5088                        flags | MATCH_DISABLED_COMPONENTS, userId);
5089                if (DEBUG_PREFERRED || debug) {
5090                    Slog.v(TAG, "Found persistent preferred activity:");
5091                    if (ai != null) {
5092                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5093                    } else {
5094                        Slog.v(TAG, "  null");
5095                    }
5096                }
5097                if (ai == null) {
5098                    // This previously registered persistent preferred activity
5099                    // component is no longer known. Ignore it and do NOT remove it.
5100                    continue;
5101                }
5102                for (int j=0; j<N; j++) {
5103                    final ResolveInfo ri = query.get(j);
5104                    if (!ri.activityInfo.applicationInfo.packageName
5105                            .equals(ai.applicationInfo.packageName)) {
5106                        continue;
5107                    }
5108                    if (!ri.activityInfo.name.equals(ai.name)) {
5109                        continue;
5110                    }
5111                    //  Found a persistent preference that can handle the intent.
5112                    if (DEBUG_PREFERRED || debug) {
5113                        Slog.v(TAG, "Returning persistent preferred activity: " +
5114                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5115                    }
5116                    return ri;
5117                }
5118            }
5119        }
5120        return null;
5121    }
5122
5123    // TODO: handle preferred activities missing while user has amnesia
5124    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5125            List<ResolveInfo> query, int priority, boolean always,
5126            boolean removeMatches, boolean debug, int userId) {
5127        if (!sUserManager.exists(userId)) return null;
5128        flags = updateFlagsForResolve(flags, userId, intent);
5129        // writer
5130        synchronized (mPackages) {
5131            if (intent.getSelector() != null) {
5132                intent = intent.getSelector();
5133            }
5134            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5135
5136            // Try to find a matching persistent preferred activity.
5137            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5138                    debug, userId);
5139
5140            // If a persistent preferred activity matched, use it.
5141            if (pri != null) {
5142                return pri;
5143            }
5144
5145            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5146            // Get the list of preferred activities that handle the intent
5147            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5148            List<PreferredActivity> prefs = pir != null
5149                    ? pir.queryIntent(intent, resolvedType,
5150                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5151                    : null;
5152            if (prefs != null && prefs.size() > 0) {
5153                boolean changed = false;
5154                try {
5155                    // First figure out how good the original match set is.
5156                    // We will only allow preferred activities that came
5157                    // from the same match quality.
5158                    int match = 0;
5159
5160                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5161
5162                    final int N = query.size();
5163                    for (int j=0; j<N; j++) {
5164                        final ResolveInfo ri = query.get(j);
5165                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5166                                + ": 0x" + Integer.toHexString(match));
5167                        if (ri.match > match) {
5168                            match = ri.match;
5169                        }
5170                    }
5171
5172                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5173                            + Integer.toHexString(match));
5174
5175                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5176                    final int M = prefs.size();
5177                    for (int i=0; i<M; i++) {
5178                        final PreferredActivity pa = prefs.get(i);
5179                        if (DEBUG_PREFERRED || debug) {
5180                            Slog.v(TAG, "Checking PreferredActivity ds="
5181                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5182                                    + "\n  component=" + pa.mPref.mComponent);
5183                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5184                        }
5185                        if (pa.mPref.mMatch != match) {
5186                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5187                                    + Integer.toHexString(pa.mPref.mMatch));
5188                            continue;
5189                        }
5190                        // If it's not an "always" type preferred activity and that's what we're
5191                        // looking for, skip it.
5192                        if (always && !pa.mPref.mAlways) {
5193                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5194                            continue;
5195                        }
5196                        final ActivityInfo ai = getActivityInfo(
5197                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5198                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5199                                userId);
5200                        if (DEBUG_PREFERRED || debug) {
5201                            Slog.v(TAG, "Found preferred activity:");
5202                            if (ai != null) {
5203                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5204                            } else {
5205                                Slog.v(TAG, "  null");
5206                            }
5207                        }
5208                        if (ai == null) {
5209                            // This previously registered preferred activity
5210                            // component is no longer known.  Most likely an update
5211                            // to the app was installed and in the new version this
5212                            // component no longer exists.  Clean it up by removing
5213                            // it from the preferred activities list, and skip it.
5214                            Slog.w(TAG, "Removing dangling preferred activity: "
5215                                    + pa.mPref.mComponent);
5216                            pir.removeFilter(pa);
5217                            changed = true;
5218                            continue;
5219                        }
5220                        for (int j=0; j<N; j++) {
5221                            final ResolveInfo ri = query.get(j);
5222                            if (!ri.activityInfo.applicationInfo.packageName
5223                                    .equals(ai.applicationInfo.packageName)) {
5224                                continue;
5225                            }
5226                            if (!ri.activityInfo.name.equals(ai.name)) {
5227                                continue;
5228                            }
5229
5230                            if (removeMatches) {
5231                                pir.removeFilter(pa);
5232                                changed = true;
5233                                if (DEBUG_PREFERRED) {
5234                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5235                                }
5236                                break;
5237                            }
5238
5239                            // Okay we found a previously set preferred or last chosen app.
5240                            // If the result set is different from when this
5241                            // was created, we need to clear it and re-ask the
5242                            // user their preference, if we're looking for an "always" type entry.
5243                            if (always && !pa.mPref.sameSet(query)) {
5244                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5245                                        + intent + " type " + resolvedType);
5246                                if (DEBUG_PREFERRED) {
5247                                    Slog.v(TAG, "Removing preferred activity since set changed "
5248                                            + pa.mPref.mComponent);
5249                                }
5250                                pir.removeFilter(pa);
5251                                // Re-add the filter as a "last chosen" entry (!always)
5252                                PreferredActivity lastChosen = new PreferredActivity(
5253                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5254                                pir.addFilter(lastChosen);
5255                                changed = true;
5256                                return null;
5257                            }
5258
5259                            // Yay! Either the set matched or we're looking for the last chosen
5260                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5261                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5262                            return ri;
5263                        }
5264                    }
5265                } finally {
5266                    if (changed) {
5267                        if (DEBUG_PREFERRED) {
5268                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5269                        }
5270                        scheduleWritePackageRestrictionsLocked(userId);
5271                    }
5272                }
5273            }
5274        }
5275        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5276        return null;
5277    }
5278
5279    /*
5280     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5281     */
5282    @Override
5283    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5284            int targetUserId) {
5285        mContext.enforceCallingOrSelfPermission(
5286                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5287        List<CrossProfileIntentFilter> matches =
5288                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5289        if (matches != null) {
5290            int size = matches.size();
5291            for (int i = 0; i < size; i++) {
5292                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5293            }
5294        }
5295        if (hasWebURI(intent)) {
5296            // cross-profile app linking works only towards the parent.
5297            final UserInfo parent = getProfileParent(sourceUserId);
5298            synchronized(mPackages) {
5299                int flags = updateFlagsForResolve(0, parent.id, intent);
5300                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5301                        intent, resolvedType, flags, sourceUserId, parent.id);
5302                return xpDomainInfo != null;
5303            }
5304        }
5305        return false;
5306    }
5307
5308    private UserInfo getProfileParent(int userId) {
5309        final long identity = Binder.clearCallingIdentity();
5310        try {
5311            return sUserManager.getProfileParent(userId);
5312        } finally {
5313            Binder.restoreCallingIdentity(identity);
5314        }
5315    }
5316
5317    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5318            String resolvedType, int userId) {
5319        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5320        if (resolver != null) {
5321            return resolver.queryIntent(intent, resolvedType, false, userId);
5322        }
5323        return null;
5324    }
5325
5326    @Override
5327    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5328            String resolvedType, int flags, int userId) {
5329        try {
5330            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5331
5332            return new ParceledListSlice<>(
5333                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5334        } finally {
5335            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5336        }
5337    }
5338
5339    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5340            String resolvedType, int flags, int userId) {
5341        if (!sUserManager.exists(userId)) return Collections.emptyList();
5342        flags = updateFlagsForResolve(flags, userId, intent);
5343        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5344                false /* requireFullPermission */, false /* checkShell */,
5345                "query intent activities");
5346        ComponentName comp = intent.getComponent();
5347        if (comp == null) {
5348            if (intent.getSelector() != null) {
5349                intent = intent.getSelector();
5350                comp = intent.getComponent();
5351            }
5352        }
5353
5354        if (comp != null) {
5355            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5356            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5357            if (ai != null) {
5358                final ResolveInfo ri = new ResolveInfo();
5359                ri.activityInfo = ai;
5360                list.add(ri);
5361            }
5362            return list;
5363        }
5364
5365        // reader
5366        synchronized (mPackages) {
5367            final String pkgName = intent.getPackage();
5368            if (pkgName == null) {
5369                List<CrossProfileIntentFilter> matchingFilters =
5370                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5371                // Check for results that need to skip the current profile.
5372                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5373                        resolvedType, flags, userId);
5374                if (xpResolveInfo != null) {
5375                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5376                    result.add(xpResolveInfo);
5377                    return filterIfNotSystemUser(result, userId);
5378                }
5379
5380                // Check for results in the current profile.
5381                List<ResolveInfo> result = mActivities.queryIntent(
5382                        intent, resolvedType, flags, userId);
5383                result = filterIfNotSystemUser(result, userId);
5384
5385                // Check for cross profile results.
5386                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5387                xpResolveInfo = queryCrossProfileIntents(
5388                        matchingFilters, intent, resolvedType, flags, userId,
5389                        hasNonNegativePriorityResult);
5390                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5391                    boolean isVisibleToUser = filterIfNotSystemUser(
5392                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5393                    if (isVisibleToUser) {
5394                        result.add(xpResolveInfo);
5395                        Collections.sort(result, mResolvePrioritySorter);
5396                    }
5397                }
5398                if (hasWebURI(intent)) {
5399                    CrossProfileDomainInfo xpDomainInfo = null;
5400                    final UserInfo parent = getProfileParent(userId);
5401                    if (parent != null) {
5402                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5403                                flags, userId, parent.id);
5404                    }
5405                    if (xpDomainInfo != null) {
5406                        if (xpResolveInfo != null) {
5407                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5408                            // in the result.
5409                            result.remove(xpResolveInfo);
5410                        }
5411                        if (result.size() == 0) {
5412                            result.add(xpDomainInfo.resolveInfo);
5413                            return result;
5414                        }
5415                    } else if (result.size() <= 1) {
5416                        return result;
5417                    }
5418                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5419                            xpDomainInfo, userId);
5420                    Collections.sort(result, mResolvePrioritySorter);
5421                }
5422                return result;
5423            }
5424            final PackageParser.Package pkg = mPackages.get(pkgName);
5425            if (pkg != null) {
5426                return filterIfNotSystemUser(
5427                        mActivities.queryIntentForPackage(
5428                                intent, resolvedType, flags, pkg.activities, userId),
5429                        userId);
5430            }
5431            return new ArrayList<ResolveInfo>();
5432        }
5433    }
5434
5435    private static class CrossProfileDomainInfo {
5436        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5437        ResolveInfo resolveInfo;
5438        /* Best domain verification status of the activities found in the other profile */
5439        int bestDomainVerificationStatus;
5440    }
5441
5442    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5443            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5444        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5445                sourceUserId)) {
5446            return null;
5447        }
5448        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5449                resolvedType, flags, parentUserId);
5450
5451        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5452            return null;
5453        }
5454        CrossProfileDomainInfo result = null;
5455        int size = resultTargetUser.size();
5456        for (int i = 0; i < size; i++) {
5457            ResolveInfo riTargetUser = resultTargetUser.get(i);
5458            // Intent filter verification is only for filters that specify a host. So don't return
5459            // those that handle all web uris.
5460            if (riTargetUser.handleAllWebDataURI) {
5461                continue;
5462            }
5463            String packageName = riTargetUser.activityInfo.packageName;
5464            PackageSetting ps = mSettings.mPackages.get(packageName);
5465            if (ps == null) {
5466                continue;
5467            }
5468            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5469            int status = (int)(verificationState >> 32);
5470            if (result == null) {
5471                result = new CrossProfileDomainInfo();
5472                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5473                        sourceUserId, parentUserId);
5474                result.bestDomainVerificationStatus = status;
5475            } else {
5476                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5477                        result.bestDomainVerificationStatus);
5478            }
5479        }
5480        // Don't consider matches with status NEVER across profiles.
5481        if (result != null && result.bestDomainVerificationStatus
5482                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5483            return null;
5484        }
5485        return result;
5486    }
5487
5488    /**
5489     * Verification statuses are ordered from the worse to the best, except for
5490     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5491     */
5492    private int bestDomainVerificationStatus(int status1, int status2) {
5493        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5494            return status2;
5495        }
5496        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5497            return status1;
5498        }
5499        return (int) MathUtils.max(status1, status2);
5500    }
5501
5502    private boolean isUserEnabled(int userId) {
5503        long callingId = Binder.clearCallingIdentity();
5504        try {
5505            UserInfo userInfo = sUserManager.getUserInfo(userId);
5506            return userInfo != null && userInfo.isEnabled();
5507        } finally {
5508            Binder.restoreCallingIdentity(callingId);
5509        }
5510    }
5511
5512    /**
5513     * Filter out activities with systemUserOnly flag set, when current user is not System.
5514     *
5515     * @return filtered list
5516     */
5517    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5518        if (userId == UserHandle.USER_SYSTEM) {
5519            return resolveInfos;
5520        }
5521        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5522            ResolveInfo info = resolveInfos.get(i);
5523            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5524                resolveInfos.remove(i);
5525            }
5526        }
5527        return resolveInfos;
5528    }
5529
5530    /**
5531     * @param resolveInfos list of resolve infos in descending priority order
5532     * @return if the list contains a resolve info with non-negative priority
5533     */
5534    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5535        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5536    }
5537
5538    private static boolean hasWebURI(Intent intent) {
5539        if (intent.getData() == null) {
5540            return false;
5541        }
5542        final String scheme = intent.getScheme();
5543        if (TextUtils.isEmpty(scheme)) {
5544            return false;
5545        }
5546        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5547    }
5548
5549    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5550            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5551            int userId) {
5552        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5553
5554        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5555            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5556                    candidates.size());
5557        }
5558
5559        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5560        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5561        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5562        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5563        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5564        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5565
5566        synchronized (mPackages) {
5567            final int count = candidates.size();
5568            // First, try to use linked apps. Partition the candidates into four lists:
5569            // one for the final results, one for the "do not use ever", one for "undefined status"
5570            // and finally one for "browser app type".
5571            for (int n=0; n<count; n++) {
5572                ResolveInfo info = candidates.get(n);
5573                String packageName = info.activityInfo.packageName;
5574                PackageSetting ps = mSettings.mPackages.get(packageName);
5575                if (ps != null) {
5576                    // Add to the special match all list (Browser use case)
5577                    if (info.handleAllWebDataURI) {
5578                        matchAllList.add(info);
5579                        continue;
5580                    }
5581                    // Try to get the status from User settings first
5582                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5583                    int status = (int)(packedStatus >> 32);
5584                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5585                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5586                        if (DEBUG_DOMAIN_VERIFICATION) {
5587                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5588                                    + " : linkgen=" + linkGeneration);
5589                        }
5590                        // Use link-enabled generation as preferredOrder, i.e.
5591                        // prefer newly-enabled over earlier-enabled.
5592                        info.preferredOrder = linkGeneration;
5593                        alwaysList.add(info);
5594                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5595                        if (DEBUG_DOMAIN_VERIFICATION) {
5596                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5597                        }
5598                        neverList.add(info);
5599                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5600                        if (DEBUG_DOMAIN_VERIFICATION) {
5601                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5602                        }
5603                        alwaysAskList.add(info);
5604                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5605                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5606                        if (DEBUG_DOMAIN_VERIFICATION) {
5607                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5608                        }
5609                        undefinedList.add(info);
5610                    }
5611                }
5612            }
5613
5614            // We'll want to include browser possibilities in a few cases
5615            boolean includeBrowser = false;
5616
5617            // First try to add the "always" resolution(s) for the current user, if any
5618            if (alwaysList.size() > 0) {
5619                result.addAll(alwaysList);
5620            } else {
5621                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5622                result.addAll(undefinedList);
5623                // Maybe add one for the other profile.
5624                if (xpDomainInfo != null && (
5625                        xpDomainInfo.bestDomainVerificationStatus
5626                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5627                    result.add(xpDomainInfo.resolveInfo);
5628                }
5629                includeBrowser = true;
5630            }
5631
5632            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5633            // If there were 'always' entries their preferred order has been set, so we also
5634            // back that off to make the alternatives equivalent
5635            if (alwaysAskList.size() > 0) {
5636                for (ResolveInfo i : result) {
5637                    i.preferredOrder = 0;
5638                }
5639                result.addAll(alwaysAskList);
5640                includeBrowser = true;
5641            }
5642
5643            if (includeBrowser) {
5644                // Also add browsers (all of them or only the default one)
5645                if (DEBUG_DOMAIN_VERIFICATION) {
5646                    Slog.v(TAG, "   ...including browsers in candidate set");
5647                }
5648                if ((matchFlags & MATCH_ALL) != 0) {
5649                    result.addAll(matchAllList);
5650                } else {
5651                    // Browser/generic handling case.  If there's a default browser, go straight
5652                    // to that (but only if there is no other higher-priority match).
5653                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5654                    int maxMatchPrio = 0;
5655                    ResolveInfo defaultBrowserMatch = null;
5656                    final int numCandidates = matchAllList.size();
5657                    for (int n = 0; n < numCandidates; n++) {
5658                        ResolveInfo info = matchAllList.get(n);
5659                        // track the highest overall match priority...
5660                        if (info.priority > maxMatchPrio) {
5661                            maxMatchPrio = info.priority;
5662                        }
5663                        // ...and the highest-priority default browser match
5664                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5665                            if (defaultBrowserMatch == null
5666                                    || (defaultBrowserMatch.priority < info.priority)) {
5667                                if (debug) {
5668                                    Slog.v(TAG, "Considering default browser match " + info);
5669                                }
5670                                defaultBrowserMatch = info;
5671                            }
5672                        }
5673                    }
5674                    if (defaultBrowserMatch != null
5675                            && defaultBrowserMatch.priority >= maxMatchPrio
5676                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5677                    {
5678                        if (debug) {
5679                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5680                        }
5681                        result.add(defaultBrowserMatch);
5682                    } else {
5683                        result.addAll(matchAllList);
5684                    }
5685                }
5686
5687                // If there is nothing selected, add all candidates and remove the ones that the user
5688                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5689                if (result.size() == 0) {
5690                    result.addAll(candidates);
5691                    result.removeAll(neverList);
5692                }
5693            }
5694        }
5695        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5696            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5697                    result.size());
5698            for (ResolveInfo info : result) {
5699                Slog.v(TAG, "  + " + info.activityInfo);
5700            }
5701        }
5702        return result;
5703    }
5704
5705    // Returns a packed value as a long:
5706    //
5707    // high 'int'-sized word: link status: undefined/ask/never/always.
5708    // low 'int'-sized word: relative priority among 'always' results.
5709    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5710        long result = ps.getDomainVerificationStatusForUser(userId);
5711        // if none available, get the master status
5712        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5713            if (ps.getIntentFilterVerificationInfo() != null) {
5714                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5715            }
5716        }
5717        return result;
5718    }
5719
5720    private ResolveInfo querySkipCurrentProfileIntents(
5721            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5722            int flags, int sourceUserId) {
5723        if (matchingFilters != null) {
5724            int size = matchingFilters.size();
5725            for (int i = 0; i < size; i ++) {
5726                CrossProfileIntentFilter filter = matchingFilters.get(i);
5727                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5728                    // Checking if there are activities in the target user that can handle the
5729                    // intent.
5730                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5731                            resolvedType, flags, sourceUserId);
5732                    if (resolveInfo != null) {
5733                        return resolveInfo;
5734                    }
5735                }
5736            }
5737        }
5738        return null;
5739    }
5740
5741    // Return matching ResolveInfo in target user if any.
5742    private ResolveInfo queryCrossProfileIntents(
5743            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5744            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5745        if (matchingFilters != null) {
5746            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5747            // match the same intent. For performance reasons, it is better not to
5748            // run queryIntent twice for the same userId
5749            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5750            int size = matchingFilters.size();
5751            for (int i = 0; i < size; i++) {
5752                CrossProfileIntentFilter filter = matchingFilters.get(i);
5753                int targetUserId = filter.getTargetUserId();
5754                boolean skipCurrentProfile =
5755                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5756                boolean skipCurrentProfileIfNoMatchFound =
5757                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5758                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5759                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5760                    // Checking if there are activities in the target user that can handle the
5761                    // intent.
5762                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5763                            resolvedType, flags, sourceUserId);
5764                    if (resolveInfo != null) return resolveInfo;
5765                    alreadyTriedUserIds.put(targetUserId, true);
5766                }
5767            }
5768        }
5769        return null;
5770    }
5771
5772    /**
5773     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5774     * will forward the intent to the filter's target user.
5775     * Otherwise, returns null.
5776     */
5777    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5778            String resolvedType, int flags, int sourceUserId) {
5779        int targetUserId = filter.getTargetUserId();
5780        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5781                resolvedType, flags, targetUserId);
5782        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5783            // If all the matches in the target profile are suspended, return null.
5784            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5785                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5786                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5787                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5788                            targetUserId);
5789                }
5790            }
5791        }
5792        return null;
5793    }
5794
5795    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5796            int sourceUserId, int targetUserId) {
5797        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5798        long ident = Binder.clearCallingIdentity();
5799        boolean targetIsProfile;
5800        try {
5801            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5802        } finally {
5803            Binder.restoreCallingIdentity(ident);
5804        }
5805        String className;
5806        if (targetIsProfile) {
5807            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5808        } else {
5809            className = FORWARD_INTENT_TO_PARENT;
5810        }
5811        ComponentName forwardingActivityComponentName = new ComponentName(
5812                mAndroidApplication.packageName, className);
5813        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5814                sourceUserId);
5815        if (!targetIsProfile) {
5816            forwardingActivityInfo.showUserIcon = targetUserId;
5817            forwardingResolveInfo.noResourceId = true;
5818        }
5819        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5820        forwardingResolveInfo.priority = 0;
5821        forwardingResolveInfo.preferredOrder = 0;
5822        forwardingResolveInfo.match = 0;
5823        forwardingResolveInfo.isDefault = true;
5824        forwardingResolveInfo.filter = filter;
5825        forwardingResolveInfo.targetUserId = targetUserId;
5826        return forwardingResolveInfo;
5827    }
5828
5829    @Override
5830    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5831            Intent[] specifics, String[] specificTypes, Intent intent,
5832            String resolvedType, int flags, int userId) {
5833        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5834                specificTypes, intent, resolvedType, flags, userId));
5835    }
5836
5837    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5838            Intent[] specifics, String[] specificTypes, Intent intent,
5839            String resolvedType, int flags, int userId) {
5840        if (!sUserManager.exists(userId)) return Collections.emptyList();
5841        flags = updateFlagsForResolve(flags, userId, intent);
5842        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5843                false /* requireFullPermission */, false /* checkShell */,
5844                "query intent activity options");
5845        final String resultsAction = intent.getAction();
5846
5847        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5848                | PackageManager.GET_RESOLVED_FILTER, userId);
5849
5850        if (DEBUG_INTENT_MATCHING) {
5851            Log.v(TAG, "Query " + intent + ": " + results);
5852        }
5853
5854        int specificsPos = 0;
5855        int N;
5856
5857        // todo: note that the algorithm used here is O(N^2).  This
5858        // isn't a problem in our current environment, but if we start running
5859        // into situations where we have more than 5 or 10 matches then this
5860        // should probably be changed to something smarter...
5861
5862        // First we go through and resolve each of the specific items
5863        // that were supplied, taking care of removing any corresponding
5864        // duplicate items in the generic resolve list.
5865        if (specifics != null) {
5866            for (int i=0; i<specifics.length; i++) {
5867                final Intent sintent = specifics[i];
5868                if (sintent == null) {
5869                    continue;
5870                }
5871
5872                if (DEBUG_INTENT_MATCHING) {
5873                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5874                }
5875
5876                String action = sintent.getAction();
5877                if (resultsAction != null && resultsAction.equals(action)) {
5878                    // If this action was explicitly requested, then don't
5879                    // remove things that have it.
5880                    action = null;
5881                }
5882
5883                ResolveInfo ri = null;
5884                ActivityInfo ai = null;
5885
5886                ComponentName comp = sintent.getComponent();
5887                if (comp == null) {
5888                    ri = resolveIntent(
5889                        sintent,
5890                        specificTypes != null ? specificTypes[i] : null,
5891                            flags, userId);
5892                    if (ri == null) {
5893                        continue;
5894                    }
5895                    if (ri == mResolveInfo) {
5896                        // ACK!  Must do something better with this.
5897                    }
5898                    ai = ri.activityInfo;
5899                    comp = new ComponentName(ai.applicationInfo.packageName,
5900                            ai.name);
5901                } else {
5902                    ai = getActivityInfo(comp, flags, userId);
5903                    if (ai == null) {
5904                        continue;
5905                    }
5906                }
5907
5908                // Look for any generic query activities that are duplicates
5909                // of this specific one, and remove them from the results.
5910                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5911                N = results.size();
5912                int j;
5913                for (j=specificsPos; j<N; j++) {
5914                    ResolveInfo sri = results.get(j);
5915                    if ((sri.activityInfo.name.equals(comp.getClassName())
5916                            && sri.activityInfo.applicationInfo.packageName.equals(
5917                                    comp.getPackageName()))
5918                        || (action != null && sri.filter.matchAction(action))) {
5919                        results.remove(j);
5920                        if (DEBUG_INTENT_MATCHING) Log.v(
5921                            TAG, "Removing duplicate item from " + j
5922                            + " due to specific " + specificsPos);
5923                        if (ri == null) {
5924                            ri = sri;
5925                        }
5926                        j--;
5927                        N--;
5928                    }
5929                }
5930
5931                // Add this specific item to its proper place.
5932                if (ri == null) {
5933                    ri = new ResolveInfo();
5934                    ri.activityInfo = ai;
5935                }
5936                results.add(specificsPos, ri);
5937                ri.specificIndex = i;
5938                specificsPos++;
5939            }
5940        }
5941
5942        // Now we go through the remaining generic results and remove any
5943        // duplicate actions that are found here.
5944        N = results.size();
5945        for (int i=specificsPos; i<N-1; i++) {
5946            final ResolveInfo rii = results.get(i);
5947            if (rii.filter == null) {
5948                continue;
5949            }
5950
5951            // Iterate over all of the actions of this result's intent
5952            // filter...  typically this should be just one.
5953            final Iterator<String> it = rii.filter.actionsIterator();
5954            if (it == null) {
5955                continue;
5956            }
5957            while (it.hasNext()) {
5958                final String action = it.next();
5959                if (resultsAction != null && resultsAction.equals(action)) {
5960                    // If this action was explicitly requested, then don't
5961                    // remove things that have it.
5962                    continue;
5963                }
5964                for (int j=i+1; j<N; j++) {
5965                    final ResolveInfo rij = results.get(j);
5966                    if (rij.filter != null && rij.filter.hasAction(action)) {
5967                        results.remove(j);
5968                        if (DEBUG_INTENT_MATCHING) Log.v(
5969                            TAG, "Removing duplicate item from " + j
5970                            + " due to action " + action + " at " + i);
5971                        j--;
5972                        N--;
5973                    }
5974                }
5975            }
5976
5977            // If the caller didn't request filter information, drop it now
5978            // so we don't have to marshall/unmarshall it.
5979            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5980                rii.filter = null;
5981            }
5982        }
5983
5984        // Filter out the caller activity if so requested.
5985        if (caller != null) {
5986            N = results.size();
5987            for (int i=0; i<N; i++) {
5988                ActivityInfo ainfo = results.get(i).activityInfo;
5989                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5990                        && caller.getClassName().equals(ainfo.name)) {
5991                    results.remove(i);
5992                    break;
5993                }
5994            }
5995        }
5996
5997        // If the caller didn't request filter information,
5998        // drop them now so we don't have to
5999        // marshall/unmarshall it.
6000        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6001            N = results.size();
6002            for (int i=0; i<N; i++) {
6003                results.get(i).filter = null;
6004            }
6005        }
6006
6007        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6008        return results;
6009    }
6010
6011    @Override
6012    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6013            String resolvedType, int flags, int userId) {
6014        return new ParceledListSlice<>(
6015                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6016    }
6017
6018    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6019            String resolvedType, int flags, int userId) {
6020        if (!sUserManager.exists(userId)) return Collections.emptyList();
6021        flags = updateFlagsForResolve(flags, userId, intent);
6022        ComponentName comp = intent.getComponent();
6023        if (comp == null) {
6024            if (intent.getSelector() != null) {
6025                intent = intent.getSelector();
6026                comp = intent.getComponent();
6027            }
6028        }
6029        if (comp != null) {
6030            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6031            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6032            if (ai != null) {
6033                ResolveInfo ri = new ResolveInfo();
6034                ri.activityInfo = ai;
6035                list.add(ri);
6036            }
6037            return list;
6038        }
6039
6040        // reader
6041        synchronized (mPackages) {
6042            String pkgName = intent.getPackage();
6043            if (pkgName == null) {
6044                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6045            }
6046            final PackageParser.Package pkg = mPackages.get(pkgName);
6047            if (pkg != null) {
6048                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6049                        userId);
6050            }
6051            return Collections.emptyList();
6052        }
6053    }
6054
6055    @Override
6056    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6057        if (!sUserManager.exists(userId)) return null;
6058        flags = updateFlagsForResolve(flags, userId, intent);
6059        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6060        if (query != null) {
6061            if (query.size() >= 1) {
6062                // If there is more than one service with the same priority,
6063                // just arbitrarily pick the first one.
6064                return query.get(0);
6065            }
6066        }
6067        return null;
6068    }
6069
6070    @Override
6071    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6072            String resolvedType, int flags, int userId) {
6073        return new ParceledListSlice<>(
6074                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6075    }
6076
6077    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6078            String resolvedType, int flags, int userId) {
6079        if (!sUserManager.exists(userId)) return Collections.emptyList();
6080        flags = updateFlagsForResolve(flags, userId, intent);
6081        ComponentName comp = intent.getComponent();
6082        if (comp == null) {
6083            if (intent.getSelector() != null) {
6084                intent = intent.getSelector();
6085                comp = intent.getComponent();
6086            }
6087        }
6088        if (comp != null) {
6089            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6090            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6091            if (si != null) {
6092                final ResolveInfo ri = new ResolveInfo();
6093                ri.serviceInfo = si;
6094                list.add(ri);
6095            }
6096            return list;
6097        }
6098
6099        // reader
6100        synchronized (mPackages) {
6101            String pkgName = intent.getPackage();
6102            if (pkgName == null) {
6103                return mServices.queryIntent(intent, resolvedType, flags, userId);
6104            }
6105            final PackageParser.Package pkg = mPackages.get(pkgName);
6106            if (pkg != null) {
6107                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6108                        userId);
6109            }
6110            return Collections.emptyList();
6111        }
6112    }
6113
6114    @Override
6115    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6116            String resolvedType, int flags, int userId) {
6117        return new ParceledListSlice<>(
6118                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6119    }
6120
6121    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6122            Intent intent, String resolvedType, int flags, int userId) {
6123        if (!sUserManager.exists(userId)) return Collections.emptyList();
6124        flags = updateFlagsForResolve(flags, userId, intent);
6125        ComponentName comp = intent.getComponent();
6126        if (comp == null) {
6127            if (intent.getSelector() != null) {
6128                intent = intent.getSelector();
6129                comp = intent.getComponent();
6130            }
6131        }
6132        if (comp != null) {
6133            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6134            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6135            if (pi != null) {
6136                final ResolveInfo ri = new ResolveInfo();
6137                ri.providerInfo = pi;
6138                list.add(ri);
6139            }
6140            return list;
6141        }
6142
6143        // reader
6144        synchronized (mPackages) {
6145            String pkgName = intent.getPackage();
6146            if (pkgName == null) {
6147                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6148            }
6149            final PackageParser.Package pkg = mPackages.get(pkgName);
6150            if (pkg != null) {
6151                return mProviders.queryIntentForPackage(
6152                        intent, resolvedType, flags, pkg.providers, userId);
6153            }
6154            return Collections.emptyList();
6155        }
6156    }
6157
6158    @Override
6159    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6160        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6161        flags = updateFlagsForPackage(flags, userId, null);
6162        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6163        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6164                true /* requireFullPermission */, false /* checkShell */,
6165                "get installed packages");
6166
6167        // writer
6168        synchronized (mPackages) {
6169            ArrayList<PackageInfo> list;
6170            if (listUninstalled) {
6171                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6172                for (PackageSetting ps : mSettings.mPackages.values()) {
6173                    final PackageInfo pi;
6174                    if (ps.pkg != null) {
6175                        pi = generatePackageInfo(ps, flags, userId);
6176                    } else {
6177                        pi = generatePackageInfo(ps, flags, userId);
6178                    }
6179                    if (pi != null) {
6180                        list.add(pi);
6181                    }
6182                }
6183            } else {
6184                list = new ArrayList<PackageInfo>(mPackages.size());
6185                for (PackageParser.Package p : mPackages.values()) {
6186                    final PackageInfo pi =
6187                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6188                    if (pi != null) {
6189                        list.add(pi);
6190                    }
6191                }
6192            }
6193
6194            return new ParceledListSlice<PackageInfo>(list);
6195        }
6196    }
6197
6198    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6199            String[] permissions, boolean[] tmp, int flags, int userId) {
6200        int numMatch = 0;
6201        final PermissionsState permissionsState = ps.getPermissionsState();
6202        for (int i=0; i<permissions.length; i++) {
6203            final String permission = permissions[i];
6204            if (permissionsState.hasPermission(permission, userId)) {
6205                tmp[i] = true;
6206                numMatch++;
6207            } else {
6208                tmp[i] = false;
6209            }
6210        }
6211        if (numMatch == 0) {
6212            return;
6213        }
6214        final PackageInfo pi;
6215        if (ps.pkg != null) {
6216            pi = generatePackageInfo(ps, flags, userId);
6217        } else {
6218            pi = generatePackageInfo(ps, flags, userId);
6219        }
6220        // The above might return null in cases of uninstalled apps or install-state
6221        // skew across users/profiles.
6222        if (pi != null) {
6223            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6224                if (numMatch == permissions.length) {
6225                    pi.requestedPermissions = permissions;
6226                } else {
6227                    pi.requestedPermissions = new String[numMatch];
6228                    numMatch = 0;
6229                    for (int i=0; i<permissions.length; i++) {
6230                        if (tmp[i]) {
6231                            pi.requestedPermissions[numMatch] = permissions[i];
6232                            numMatch++;
6233                        }
6234                    }
6235                }
6236            }
6237            list.add(pi);
6238        }
6239    }
6240
6241    @Override
6242    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6243            String[] permissions, int flags, int userId) {
6244        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6245        flags = updateFlagsForPackage(flags, userId, permissions);
6246        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6247
6248        // writer
6249        synchronized (mPackages) {
6250            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6251            boolean[] tmpBools = new boolean[permissions.length];
6252            if (listUninstalled) {
6253                for (PackageSetting ps : mSettings.mPackages.values()) {
6254                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6255                }
6256            } else {
6257                for (PackageParser.Package pkg : mPackages.values()) {
6258                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6259                    if (ps != null) {
6260                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6261                                userId);
6262                    }
6263                }
6264            }
6265
6266            return new ParceledListSlice<PackageInfo>(list);
6267        }
6268    }
6269
6270    @Override
6271    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6272        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6273        flags = updateFlagsForApplication(flags, userId, null);
6274        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6275
6276        // writer
6277        synchronized (mPackages) {
6278            ArrayList<ApplicationInfo> list;
6279            if (listUninstalled) {
6280                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6281                for (PackageSetting ps : mSettings.mPackages.values()) {
6282                    ApplicationInfo ai;
6283                    if (ps.pkg != null) {
6284                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6285                                ps.readUserState(userId), userId);
6286                    } else {
6287                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6288                    }
6289                    if (ai != null) {
6290                        list.add(ai);
6291                    }
6292                }
6293            } else {
6294                list = new ArrayList<ApplicationInfo>(mPackages.size());
6295                for (PackageParser.Package p : mPackages.values()) {
6296                    if (p.mExtras != null) {
6297                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6298                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6299                        if (ai != null) {
6300                            list.add(ai);
6301                        }
6302                    }
6303                }
6304            }
6305
6306            return new ParceledListSlice<ApplicationInfo>(list);
6307        }
6308    }
6309
6310    @Override
6311    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6312        if (DISABLE_EPHEMERAL_APPS) {
6313            return null;
6314        }
6315
6316        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6317                "getEphemeralApplications");
6318        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6319                true /* requireFullPermission */, false /* checkShell */,
6320                "getEphemeralApplications");
6321        synchronized (mPackages) {
6322            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6323                    .getEphemeralApplicationsLPw(userId);
6324            if (ephemeralApps != null) {
6325                return new ParceledListSlice<>(ephemeralApps);
6326            }
6327        }
6328        return null;
6329    }
6330
6331    @Override
6332    public boolean isEphemeralApplication(String packageName, int userId) {
6333        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6334                true /* requireFullPermission */, false /* checkShell */,
6335                "isEphemeral");
6336        if (DISABLE_EPHEMERAL_APPS) {
6337            return false;
6338        }
6339
6340        if (!isCallerSameApp(packageName)) {
6341            return false;
6342        }
6343        synchronized (mPackages) {
6344            PackageParser.Package pkg = mPackages.get(packageName);
6345            if (pkg != null) {
6346                return pkg.applicationInfo.isEphemeralApp();
6347            }
6348        }
6349        return false;
6350    }
6351
6352    @Override
6353    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6354        if (DISABLE_EPHEMERAL_APPS) {
6355            return null;
6356        }
6357
6358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6359                true /* requireFullPermission */, false /* checkShell */,
6360                "getCookie");
6361        if (!isCallerSameApp(packageName)) {
6362            return null;
6363        }
6364        synchronized (mPackages) {
6365            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6366                    packageName, userId);
6367        }
6368    }
6369
6370    @Override
6371    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6372        if (DISABLE_EPHEMERAL_APPS) {
6373            return true;
6374        }
6375
6376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6377                true /* requireFullPermission */, true /* checkShell */,
6378                "setCookie");
6379        if (!isCallerSameApp(packageName)) {
6380            return false;
6381        }
6382        synchronized (mPackages) {
6383            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6384                    packageName, cookie, userId);
6385        }
6386    }
6387
6388    @Override
6389    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6390        if (DISABLE_EPHEMERAL_APPS) {
6391            return null;
6392        }
6393
6394        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6395                "getEphemeralApplicationIcon");
6396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6397                true /* requireFullPermission */, false /* checkShell */,
6398                "getEphemeralApplicationIcon");
6399        synchronized (mPackages) {
6400            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6401                    packageName, userId);
6402        }
6403    }
6404
6405    private boolean isCallerSameApp(String packageName) {
6406        PackageParser.Package pkg = mPackages.get(packageName);
6407        return pkg != null
6408                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6409    }
6410
6411    @Override
6412    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6413        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6414    }
6415
6416    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6417        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6418
6419        // reader
6420        synchronized (mPackages) {
6421            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6422            final int userId = UserHandle.getCallingUserId();
6423            while (i.hasNext()) {
6424                final PackageParser.Package p = i.next();
6425                if (p.applicationInfo == null) continue;
6426
6427                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6428                        && !p.applicationInfo.isDirectBootAware();
6429                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6430                        && p.applicationInfo.isDirectBootAware();
6431
6432                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6433                        && (!mSafeMode || isSystemApp(p))
6434                        && (matchesUnaware || matchesAware)) {
6435                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6436                    if (ps != null) {
6437                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6438                                ps.readUserState(userId), userId);
6439                        if (ai != null) {
6440                            finalList.add(ai);
6441                        }
6442                    }
6443                }
6444            }
6445        }
6446
6447        return finalList;
6448    }
6449
6450    @Override
6451    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6452        if (!sUserManager.exists(userId)) return null;
6453        flags = updateFlagsForComponent(flags, userId, name);
6454        // reader
6455        synchronized (mPackages) {
6456            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6457            PackageSetting ps = provider != null
6458                    ? mSettings.mPackages.get(provider.owner.packageName)
6459                    : null;
6460            return ps != null
6461                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6462                    ? PackageParser.generateProviderInfo(provider, flags,
6463                            ps.readUserState(userId), userId)
6464                    : null;
6465        }
6466    }
6467
6468    /**
6469     * @deprecated
6470     */
6471    @Deprecated
6472    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6473        // reader
6474        synchronized (mPackages) {
6475            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6476                    .entrySet().iterator();
6477            final int userId = UserHandle.getCallingUserId();
6478            while (i.hasNext()) {
6479                Map.Entry<String, PackageParser.Provider> entry = i.next();
6480                PackageParser.Provider p = entry.getValue();
6481                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6482
6483                if (ps != null && p.syncable
6484                        && (!mSafeMode || (p.info.applicationInfo.flags
6485                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6486                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6487                            ps.readUserState(userId), userId);
6488                    if (info != null) {
6489                        outNames.add(entry.getKey());
6490                        outInfo.add(info);
6491                    }
6492                }
6493            }
6494        }
6495    }
6496
6497    @Override
6498    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6499            int uid, int flags) {
6500        final int userId = processName != null ? UserHandle.getUserId(uid)
6501                : UserHandle.getCallingUserId();
6502        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6503        flags = updateFlagsForComponent(flags, userId, processName);
6504
6505        ArrayList<ProviderInfo> finalList = null;
6506        // reader
6507        synchronized (mPackages) {
6508            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6509            while (i.hasNext()) {
6510                final PackageParser.Provider p = i.next();
6511                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6512                if (ps != null && p.info.authority != null
6513                        && (processName == null
6514                                || (p.info.processName.equals(processName)
6515                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6516                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6517                    if (finalList == null) {
6518                        finalList = new ArrayList<ProviderInfo>(3);
6519                    }
6520                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6521                            ps.readUserState(userId), userId);
6522                    if (info != null) {
6523                        finalList.add(info);
6524                    }
6525                }
6526            }
6527        }
6528
6529        if (finalList != null) {
6530            Collections.sort(finalList, mProviderInitOrderSorter);
6531            return new ParceledListSlice<ProviderInfo>(finalList);
6532        }
6533
6534        return ParceledListSlice.emptyList();
6535    }
6536
6537    @Override
6538    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6539        // reader
6540        synchronized (mPackages) {
6541            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6542            return PackageParser.generateInstrumentationInfo(i, flags);
6543        }
6544    }
6545
6546    @Override
6547    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6548            String targetPackage, int flags) {
6549        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6550    }
6551
6552    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6553            int flags) {
6554        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6555
6556        // reader
6557        synchronized (mPackages) {
6558            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6559            while (i.hasNext()) {
6560                final PackageParser.Instrumentation p = i.next();
6561                if (targetPackage == null
6562                        || targetPackage.equals(p.info.targetPackage)) {
6563                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6564                            flags);
6565                    if (ii != null) {
6566                        finalList.add(ii);
6567                    }
6568                }
6569            }
6570        }
6571
6572        return finalList;
6573    }
6574
6575    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6576        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6577        if (overlays == null) {
6578            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6579            return;
6580        }
6581        for (PackageParser.Package opkg : overlays.values()) {
6582            // Not much to do if idmap fails: we already logged the error
6583            // and we certainly don't want to abort installation of pkg simply
6584            // because an overlay didn't fit properly. For these reasons,
6585            // ignore the return value of createIdmapForPackagePairLI.
6586            createIdmapForPackagePairLI(pkg, opkg);
6587        }
6588    }
6589
6590    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6591            PackageParser.Package opkg) {
6592        if (!opkg.mTrustedOverlay) {
6593            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6594                    opkg.baseCodePath + ": overlay not trusted");
6595            return false;
6596        }
6597        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6598        if (overlaySet == null) {
6599            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6600                    opkg.baseCodePath + " but target package has no known overlays");
6601            return false;
6602        }
6603        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6604        // TODO: generate idmap for split APKs
6605        try {
6606            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6607        } catch (InstallerException e) {
6608            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6609                    + opkg.baseCodePath);
6610            return false;
6611        }
6612        PackageParser.Package[] overlayArray =
6613            overlaySet.values().toArray(new PackageParser.Package[0]);
6614        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6615            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6616                return p1.mOverlayPriority - p2.mOverlayPriority;
6617            }
6618        };
6619        Arrays.sort(overlayArray, cmp);
6620
6621        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6622        int i = 0;
6623        for (PackageParser.Package p : overlayArray) {
6624            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6625        }
6626        return true;
6627    }
6628
6629    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6630        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6631        try {
6632            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6633        } finally {
6634            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6635        }
6636    }
6637
6638    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6639        final File[] files = dir.listFiles();
6640        if (ArrayUtils.isEmpty(files)) {
6641            Log.d(TAG, "No files in app dir " + dir);
6642            return;
6643        }
6644
6645        if (DEBUG_PACKAGE_SCANNING) {
6646            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6647                    + " flags=0x" + Integer.toHexString(parseFlags));
6648        }
6649
6650        for (File file : files) {
6651            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6652                    && !PackageInstallerService.isStageName(file.getName());
6653            if (!isPackage) {
6654                // Ignore entries which are not packages
6655                continue;
6656            }
6657            try {
6658                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6659                        scanFlags, currentTime, null);
6660            } catch (PackageManagerException e) {
6661                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6662
6663                // Delete invalid userdata apps
6664                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6665                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6666                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6667                    removeCodePathLI(file);
6668                }
6669            }
6670        }
6671    }
6672
6673    private static File getSettingsProblemFile() {
6674        File dataDir = Environment.getDataDirectory();
6675        File systemDir = new File(dataDir, "system");
6676        File fname = new File(systemDir, "uiderrors.txt");
6677        return fname;
6678    }
6679
6680    static void reportSettingsProblem(int priority, String msg) {
6681        logCriticalInfo(priority, msg);
6682    }
6683
6684    static void logCriticalInfo(int priority, String msg) {
6685        Slog.println(priority, TAG, msg);
6686        EventLogTags.writePmCriticalInfo(msg);
6687        try {
6688            File fname = getSettingsProblemFile();
6689            FileOutputStream out = new FileOutputStream(fname, true);
6690            PrintWriter pw = new FastPrintWriter(out);
6691            SimpleDateFormat formatter = new SimpleDateFormat();
6692            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6693            pw.println(dateString + ": " + msg);
6694            pw.close();
6695            FileUtils.setPermissions(
6696                    fname.toString(),
6697                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6698                    -1, -1);
6699        } catch (java.io.IOException e) {
6700        }
6701    }
6702
6703    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6704            final int policyFlags) throws PackageManagerException {
6705        if (ps != null
6706                && ps.codePath.equals(srcFile)
6707                && ps.timeStamp == srcFile.lastModified()
6708                && !isCompatSignatureUpdateNeeded(pkg)
6709                && !isRecoverSignatureUpdateNeeded(pkg)) {
6710            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6711            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6712            ArraySet<PublicKey> signingKs;
6713            synchronized (mPackages) {
6714                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6715            }
6716            if (ps.signatures.mSignatures != null
6717                    && ps.signatures.mSignatures.length != 0
6718                    && signingKs != null) {
6719                // Optimization: reuse the existing cached certificates
6720                // if the package appears to be unchanged.
6721                pkg.mSignatures = ps.signatures.mSignatures;
6722                pkg.mSigningKeys = signingKs;
6723                return;
6724            }
6725
6726            Slog.w(TAG, "PackageSetting for " + ps.name
6727                    + " is missing signatures.  Collecting certs again to recover them.");
6728        } else {
6729            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6730        }
6731
6732        try {
6733            PackageParser.collectCertificates(pkg, policyFlags);
6734        } catch (PackageParserException e) {
6735            throw PackageManagerException.from(e);
6736        }
6737    }
6738
6739    /**
6740     *  Traces a package scan.
6741     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6742     */
6743    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6744            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6745        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6746        try {
6747            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6748        } finally {
6749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6750        }
6751    }
6752
6753    /**
6754     *  Scans a package and returns the newly parsed package.
6755     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6756     */
6757    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6758            long currentTime, UserHandle user) throws PackageManagerException {
6759        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6760        PackageParser pp = new PackageParser();
6761        pp.setSeparateProcesses(mSeparateProcesses);
6762        pp.setOnlyCoreApps(mOnlyCore);
6763        pp.setDisplayMetrics(mMetrics);
6764
6765        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6766            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6767        }
6768
6769        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6770        final PackageParser.Package pkg;
6771        try {
6772            pkg = pp.parsePackage(scanFile, parseFlags);
6773        } catch (PackageParserException e) {
6774            throw PackageManagerException.from(e);
6775        } finally {
6776            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6777        }
6778
6779        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6780    }
6781
6782    /**
6783     *  Scans a package and returns the newly parsed package.
6784     *  @throws PackageManagerException on a parse error.
6785     */
6786    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6787            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6788            throws PackageManagerException {
6789        // If the package has children and this is the first dive in the function
6790        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6791        // packages (parent and children) would be successfully scanned before the
6792        // actual scan since scanning mutates internal state and we want to atomically
6793        // install the package and its children.
6794        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6795            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6796                scanFlags |= SCAN_CHECK_ONLY;
6797            }
6798        } else {
6799            scanFlags &= ~SCAN_CHECK_ONLY;
6800        }
6801
6802        // Scan the parent
6803        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6804                scanFlags, currentTime, user);
6805
6806        // Scan the children
6807        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6808        for (int i = 0; i < childCount; i++) {
6809            PackageParser.Package childPackage = pkg.childPackages.get(i);
6810            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6811                    currentTime, user);
6812        }
6813
6814
6815        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6816            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6817        }
6818
6819        return scannedPkg;
6820    }
6821
6822    /**
6823     *  Scans a package and returns the newly parsed package.
6824     *  @throws PackageManagerException on a parse error.
6825     */
6826    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6827            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6828            throws PackageManagerException {
6829        PackageSetting ps = null;
6830        PackageSetting updatedPkg;
6831        // reader
6832        synchronized (mPackages) {
6833            // Look to see if we already know about this package.
6834            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6835            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6836                // This package has been renamed to its original name.  Let's
6837                // use that.
6838                ps = mSettings.peekPackageLPr(oldName);
6839            }
6840            // If there was no original package, see one for the real package name.
6841            if (ps == null) {
6842                ps = mSettings.peekPackageLPr(pkg.packageName);
6843            }
6844            // Check to see if this package could be hiding/updating a system
6845            // package.  Must look for it either under the original or real
6846            // package name depending on our state.
6847            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6848            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6849
6850            // If this is a package we don't know about on the system partition, we
6851            // may need to remove disabled child packages on the system partition
6852            // or may need to not add child packages if the parent apk is updated
6853            // on the data partition and no longer defines this child package.
6854            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6855                // If this is a parent package for an updated system app and this system
6856                // app got an OTA update which no longer defines some of the child packages
6857                // we have to prune them from the disabled system packages.
6858                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6859                if (disabledPs != null) {
6860                    final int scannedChildCount = (pkg.childPackages != null)
6861                            ? pkg.childPackages.size() : 0;
6862                    final int disabledChildCount = disabledPs.childPackageNames != null
6863                            ? disabledPs.childPackageNames.size() : 0;
6864                    for (int i = 0; i < disabledChildCount; i++) {
6865                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6866                        boolean disabledPackageAvailable = false;
6867                        for (int j = 0; j < scannedChildCount; j++) {
6868                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6869                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6870                                disabledPackageAvailable = true;
6871                                break;
6872                            }
6873                         }
6874                         if (!disabledPackageAvailable) {
6875                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6876                         }
6877                    }
6878                }
6879            }
6880        }
6881
6882        boolean updatedPkgBetter = false;
6883        // First check if this is a system package that may involve an update
6884        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6885            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6886            // it needs to drop FLAG_PRIVILEGED.
6887            if (locationIsPrivileged(scanFile)) {
6888                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6889            } else {
6890                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6891            }
6892
6893            if (ps != null && !ps.codePath.equals(scanFile)) {
6894                // The path has changed from what was last scanned...  check the
6895                // version of the new path against what we have stored to determine
6896                // what to do.
6897                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6898                if (pkg.mVersionCode <= ps.versionCode) {
6899                    // The system package has been updated and the code path does not match
6900                    // Ignore entry. Skip it.
6901                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6902                            + " ignored: updated version " + ps.versionCode
6903                            + " better than this " + pkg.mVersionCode);
6904                    if (!updatedPkg.codePath.equals(scanFile)) {
6905                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6906                                + ps.name + " changing from " + updatedPkg.codePathString
6907                                + " to " + scanFile);
6908                        updatedPkg.codePath = scanFile;
6909                        updatedPkg.codePathString = scanFile.toString();
6910                        updatedPkg.resourcePath = scanFile;
6911                        updatedPkg.resourcePathString = scanFile.toString();
6912                    }
6913                    updatedPkg.pkg = pkg;
6914                    updatedPkg.versionCode = pkg.mVersionCode;
6915
6916                    // Update the disabled system child packages to point to the package too.
6917                    final int childCount = updatedPkg.childPackageNames != null
6918                            ? updatedPkg.childPackageNames.size() : 0;
6919                    for (int i = 0; i < childCount; i++) {
6920                        String childPackageName = updatedPkg.childPackageNames.get(i);
6921                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6922                                childPackageName);
6923                        if (updatedChildPkg != null) {
6924                            updatedChildPkg.pkg = pkg;
6925                            updatedChildPkg.versionCode = pkg.mVersionCode;
6926                        }
6927                    }
6928
6929                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6930                            + scanFile + " ignored: updated version " + ps.versionCode
6931                            + " better than this " + pkg.mVersionCode);
6932                } else {
6933                    // The current app on the system partition is better than
6934                    // what we have updated to on the data partition; switch
6935                    // back to the system partition version.
6936                    // At this point, its safely assumed that package installation for
6937                    // apps in system partition will go through. If not there won't be a working
6938                    // version of the app
6939                    // writer
6940                    synchronized (mPackages) {
6941                        // Just remove the loaded entries from package lists.
6942                        mPackages.remove(ps.name);
6943                    }
6944
6945                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6946                            + " reverting from " + ps.codePathString
6947                            + ": new version " + pkg.mVersionCode
6948                            + " better than installed " + ps.versionCode);
6949
6950                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6951                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6952                    synchronized (mInstallLock) {
6953                        args.cleanUpResourcesLI();
6954                    }
6955                    synchronized (mPackages) {
6956                        mSettings.enableSystemPackageLPw(ps.name);
6957                    }
6958                    updatedPkgBetter = true;
6959                }
6960            }
6961        }
6962
6963        if (updatedPkg != null) {
6964            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6965            // initially
6966            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6967
6968            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6969            // flag set initially
6970            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6971                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6972            }
6973        }
6974
6975        // Verify certificates against what was last scanned
6976        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6977
6978        /*
6979         * A new system app appeared, but we already had a non-system one of the
6980         * same name installed earlier.
6981         */
6982        boolean shouldHideSystemApp = false;
6983        if (updatedPkg == null && ps != null
6984                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6985            /*
6986             * Check to make sure the signatures match first. If they don't,
6987             * wipe the installed application and its data.
6988             */
6989            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6990                    != PackageManager.SIGNATURE_MATCH) {
6991                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6992                        + " signatures don't match existing userdata copy; removing");
6993                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6994                        "scanPackageInternalLI")) {
6995                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6996                }
6997                ps = null;
6998            } else {
6999                /*
7000                 * If the newly-added system app is an older version than the
7001                 * already installed version, hide it. It will be scanned later
7002                 * and re-added like an update.
7003                 */
7004                if (pkg.mVersionCode <= ps.versionCode) {
7005                    shouldHideSystemApp = true;
7006                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7007                            + " but new version " + pkg.mVersionCode + " better than installed "
7008                            + ps.versionCode + "; hiding system");
7009                } else {
7010                    /*
7011                     * The newly found system app is a newer version that the
7012                     * one previously installed. Simply remove the
7013                     * already-installed application and replace it with our own
7014                     * while keeping the application data.
7015                     */
7016                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7017                            + " reverting from " + ps.codePathString + ": new version "
7018                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7019                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7020                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7021                    synchronized (mInstallLock) {
7022                        args.cleanUpResourcesLI();
7023                    }
7024                }
7025            }
7026        }
7027
7028        // The apk is forward locked (not public) if its code and resources
7029        // are kept in different files. (except for app in either system or
7030        // vendor path).
7031        // TODO grab this value from PackageSettings
7032        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7033            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7034                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7035            }
7036        }
7037
7038        // TODO: extend to support forward-locked splits
7039        String resourcePath = null;
7040        String baseResourcePath = null;
7041        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7042            if (ps != null && ps.resourcePathString != null) {
7043                resourcePath = ps.resourcePathString;
7044                baseResourcePath = ps.resourcePathString;
7045            } else {
7046                // Should not happen at all. Just log an error.
7047                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7048            }
7049        } else {
7050            resourcePath = pkg.codePath;
7051            baseResourcePath = pkg.baseCodePath;
7052        }
7053
7054        // Set application objects path explicitly.
7055        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7056        pkg.setApplicationInfoCodePath(pkg.codePath);
7057        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7058        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7059        pkg.setApplicationInfoResourcePath(resourcePath);
7060        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7061        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7062
7063        // Note that we invoke the following method only if we are about to unpack an application
7064        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7065                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7066
7067        /*
7068         * If the system app should be overridden by a previously installed
7069         * data, hide the system app now and let the /data/app scan pick it up
7070         * again.
7071         */
7072        if (shouldHideSystemApp) {
7073            synchronized (mPackages) {
7074                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7075            }
7076        }
7077
7078        return scannedPkg;
7079    }
7080
7081    private static String fixProcessName(String defProcessName,
7082            String processName, int uid) {
7083        if (processName == null) {
7084            return defProcessName;
7085        }
7086        return processName;
7087    }
7088
7089    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7090            throws PackageManagerException {
7091        if (pkgSetting.signatures.mSignatures != null) {
7092            // Already existing package. Make sure signatures match
7093            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7094                    == PackageManager.SIGNATURE_MATCH;
7095            if (!match) {
7096                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7097                        == PackageManager.SIGNATURE_MATCH;
7098            }
7099            if (!match) {
7100                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7101                        == PackageManager.SIGNATURE_MATCH;
7102            }
7103            if (!match) {
7104                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7105                        + pkg.packageName + " signatures do not match the "
7106                        + "previously installed version; ignoring!");
7107            }
7108        }
7109
7110        // Check for shared user signatures
7111        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7112            // Already existing package. Make sure signatures match
7113            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7114                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7115            if (!match) {
7116                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7117                        == PackageManager.SIGNATURE_MATCH;
7118            }
7119            if (!match) {
7120                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7121                        == PackageManager.SIGNATURE_MATCH;
7122            }
7123            if (!match) {
7124                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7125                        "Package " + pkg.packageName
7126                        + " has no signatures that match those in shared user "
7127                        + pkgSetting.sharedUser.name + "; ignoring!");
7128            }
7129        }
7130    }
7131
7132    /**
7133     * Enforces that only the system UID or root's UID can call a method exposed
7134     * via Binder.
7135     *
7136     * @param message used as message if SecurityException is thrown
7137     * @throws SecurityException if the caller is not system or root
7138     */
7139    private static final void enforceSystemOrRoot(String message) {
7140        final int uid = Binder.getCallingUid();
7141        if (uid != Process.SYSTEM_UID && uid != 0) {
7142            throw new SecurityException(message);
7143        }
7144    }
7145
7146    @Override
7147    public void performFstrimIfNeeded() {
7148        enforceSystemOrRoot("Only the system can request fstrim");
7149
7150        // Before everything else, see whether we need to fstrim.
7151        try {
7152            IMountService ms = PackageHelper.getMountService();
7153            if (ms != null) {
7154                final boolean isUpgrade = isUpgrade();
7155                boolean doTrim = isUpgrade;
7156                if (doTrim) {
7157                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7158                } else {
7159                    final long interval = android.provider.Settings.Global.getLong(
7160                            mContext.getContentResolver(),
7161                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7162                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7163                    if (interval > 0) {
7164                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7165                        if (timeSinceLast > interval) {
7166                            doTrim = true;
7167                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7168                                    + "; running immediately");
7169                        }
7170                    }
7171                }
7172                if (doTrim) {
7173                    if (!isFirstBoot()) {
7174                        try {
7175                            ActivityManagerNative.getDefault().showBootMessage(
7176                                    mContext.getResources().getString(
7177                                            R.string.android_upgrading_fstrim), true);
7178                        } catch (RemoteException e) {
7179                        }
7180                    }
7181                    ms.runMaintenance();
7182                }
7183            } else {
7184                Slog.e(TAG, "Mount service unavailable!");
7185            }
7186        } catch (RemoteException e) {
7187            // Can't happen; MountService is local
7188        }
7189    }
7190
7191    @Override
7192    public void updatePackagesIfNeeded() {
7193        enforceSystemOrRoot("Only the system can request package update");
7194
7195        // We need to re-extract after an OTA.
7196        boolean causeUpgrade = isUpgrade();
7197
7198        // First boot or factory reset.
7199        // Note: we also handle devices that are upgrading to N right now as if it is their
7200        //       first boot, as they do not have profile data.
7201        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7202
7203        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7204        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7205
7206        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7207            return;
7208        }
7209
7210        List<PackageParser.Package> pkgs;
7211        synchronized (mPackages) {
7212            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7213        }
7214
7215        int numberOfPackagesVisited = 0;
7216        int numberOfPackagesOptimized = 0;
7217        int numberOfPackagesSkipped = 0;
7218        int numberOfPackagesFailed = 0;
7219        final int numberOfPackagesToDexopt = pkgs.size();
7220        final long startTime = System.nanoTime();
7221
7222        for (PackageParser.Package pkg : pkgs) {
7223            numberOfPackagesVisited++;
7224
7225            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7226                if (DEBUG_DEXOPT) {
7227                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7228                }
7229                numberOfPackagesSkipped++;
7230                continue;
7231            }
7232
7233            if (DEBUG_DEXOPT) {
7234                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7235                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7236            }
7237
7238            if (mIsPreNUpgrade) {
7239                try {
7240                    ActivityManagerNative.getDefault().showBootMessage(
7241                            mContext.getResources().getString(R.string.android_upgrading_apk,
7242                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7243                } catch (RemoteException e) {
7244                }
7245            }
7246
7247            // checkProfiles is false to avoid merging profiles during boot which
7248            // might interfere with background compilation (b/28612421).
7249            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7250            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7251            // trade-off worth doing to save boot time work.
7252            int dexOptStatus = performDexOptTraced(pkg.packageName,
7253                    null /* instructionSet */,
7254                    false /* checkProfiles */,
7255                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
7256                    false /* force */);
7257            switch (dexOptStatus) {
7258                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7259                    numberOfPackagesOptimized++;
7260                    break;
7261                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7262                    numberOfPackagesSkipped++;
7263                    break;
7264                case PackageDexOptimizer.DEX_OPT_FAILED:
7265                    numberOfPackagesFailed++;
7266                    break;
7267                default:
7268                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7269                    break;
7270            }
7271        }
7272
7273        final int elapsedTimeSeconds =
7274                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7275        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized);
7276        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped);
7277        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed);
7278        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7279        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7280    }
7281
7282    @Override
7283    public void notifyPackageUse(String packageName, int reason) {
7284        synchronized (mPackages) {
7285            PackageParser.Package p = mPackages.get(packageName);
7286            if (p == null) {
7287                return;
7288            }
7289            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7290        }
7291    }
7292
7293    // TODO: this is not used nor needed. Delete it.
7294    @Override
7295    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7296        int dexOptStatus = performDexOptTraced(packageName, instructionSet,
7297                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7298        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7299    }
7300
7301    @Override
7302    public boolean performDexOpt(String packageName, String instructionSet,
7303            boolean checkProfiles, int compileReason, boolean force) {
7304        int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles,
7305                getCompilerFilterForReason(compileReason), force);
7306        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7307    }
7308
7309    @Override
7310    public boolean performDexOptMode(String packageName, String instructionSet,
7311            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7312        int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles,
7313                targetCompilerFilter, force);
7314        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7315    }
7316
7317    private int performDexOptTraced(String packageName, String instructionSet,
7318                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7319        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7320        try {
7321            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7322                    targetCompilerFilter, force);
7323        } finally {
7324            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7325        }
7326    }
7327
7328    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7329    // if the package can now be considered up to date for the given filter.
7330    private int performDexOptInternal(String packageName, String instructionSet,
7331                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7332        PackageParser.Package p;
7333        final String targetInstructionSet;
7334        synchronized (mPackages) {
7335            p = mPackages.get(packageName);
7336            if (p == null) {
7337                // Package could not be found. Report failure.
7338                return PackageDexOptimizer.DEX_OPT_FAILED;
7339            }
7340            mPackageUsage.write(false);
7341
7342            targetInstructionSet = instructionSet != null ? instructionSet :
7343                    getPrimaryInstructionSet(p.applicationInfo);
7344        }
7345        long callingId = Binder.clearCallingIdentity();
7346        try {
7347            synchronized (mInstallLock) {
7348                final String[] instructionSets = new String[] { targetInstructionSet };
7349                return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles,
7350                        targetCompilerFilter, force);
7351            }
7352        } finally {
7353            Binder.restoreCallingIdentity(callingId);
7354        }
7355    }
7356
7357    public ArraySet<String> getOptimizablePackages() {
7358        ArraySet<String> pkgs = new ArraySet<String>();
7359        synchronized (mPackages) {
7360            for (PackageParser.Package p : mPackages.values()) {
7361                if (PackageDexOptimizer.canOptimizePackage(p)) {
7362                    pkgs.add(p.packageName);
7363                }
7364            }
7365        }
7366        return pkgs;
7367    }
7368
7369    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7370            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7371            boolean force) {
7372        // Select the dex optimizer based on the force parameter.
7373        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7374        //       allocate an object here.
7375        PackageDexOptimizer pdo = force
7376                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7377                : mPackageDexOptimizer;
7378
7379        // Optimize all dependencies first. Note: we ignore the return value and march on
7380        // on errors.
7381        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7382        if (!deps.isEmpty()) {
7383            for (PackageParser.Package depPackage : deps) {
7384                // TODO: Analyze and investigate if we (should) profile libraries.
7385                // Currently this will do a full compilation of the library by default.
7386                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7387                        false /* checkProfiles */,
7388                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7389            }
7390        }
7391
7392        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7393                targetCompilerFilter);
7394    }
7395
7396    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7397        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7398            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7399            Set<String> collectedNames = new HashSet<>();
7400            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7401
7402            retValue.remove(p);
7403
7404            return retValue;
7405        } else {
7406            return Collections.emptyList();
7407        }
7408    }
7409
7410    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7411            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7412        if (!collectedNames.contains(p.packageName)) {
7413            collectedNames.add(p.packageName);
7414            collected.add(p);
7415
7416            if (p.usesLibraries != null) {
7417                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7418            }
7419            if (p.usesOptionalLibraries != null) {
7420                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7421                        collectedNames);
7422            }
7423        }
7424    }
7425
7426    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7427            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7428        for (String libName : libs) {
7429            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7430            if (libPkg != null) {
7431                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7432            }
7433        }
7434    }
7435
7436    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7437        synchronized (mPackages) {
7438            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7439            if (lib != null && lib.apk != null) {
7440                return mPackages.get(lib.apk);
7441            }
7442        }
7443        return null;
7444    }
7445
7446    public void shutdown() {
7447        mPackageUsage.write(true);
7448    }
7449
7450    @Override
7451    public void forceDexOpt(String packageName) {
7452        enforceSystemOrRoot("forceDexOpt");
7453
7454        PackageParser.Package pkg;
7455        synchronized (mPackages) {
7456            pkg = mPackages.get(packageName);
7457            if (pkg == null) {
7458                throw new IllegalArgumentException("Unknown package: " + packageName);
7459            }
7460        }
7461
7462        synchronized (mInstallLock) {
7463            final String[] instructionSets = new String[] {
7464                    getPrimaryInstructionSet(pkg.applicationInfo) };
7465
7466            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7467
7468            // Whoever is calling forceDexOpt wants a fully compiled package.
7469            // Don't use profiles since that may cause compilation to be skipped.
7470            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7471                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7472                    true /* force */);
7473
7474            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7475            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7476                throw new IllegalStateException("Failed to dexopt: " + res);
7477            }
7478        }
7479    }
7480
7481    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7482        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7483            Slog.w(TAG, "Unable to update from " + oldPkg.name
7484                    + " to " + newPkg.packageName
7485                    + ": old package not in system partition");
7486            return false;
7487        } else if (mPackages.get(oldPkg.name) != null) {
7488            Slog.w(TAG, "Unable to update from " + oldPkg.name
7489                    + " to " + newPkg.packageName
7490                    + ": old package still exists");
7491            return false;
7492        }
7493        return true;
7494    }
7495
7496    void removeCodePathLI(File codePath) {
7497        if (codePath.isDirectory()) {
7498            try {
7499                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7500            } catch (InstallerException e) {
7501                Slog.w(TAG, "Failed to remove code path", e);
7502            }
7503        } else {
7504            codePath.delete();
7505        }
7506    }
7507
7508    private int[] resolveUserIds(int userId) {
7509        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7510    }
7511
7512    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7513        if (pkg == null) {
7514            Slog.wtf(TAG, "Package was null!", new Throwable());
7515            return;
7516        }
7517        clearAppDataLeafLIF(pkg, userId, flags);
7518        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7519        for (int i = 0; i < childCount; i++) {
7520            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7521        }
7522    }
7523
7524    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7525        final PackageSetting ps;
7526        synchronized (mPackages) {
7527            ps = mSettings.mPackages.get(pkg.packageName);
7528        }
7529        for (int realUserId : resolveUserIds(userId)) {
7530            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7531            try {
7532                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7533                        ceDataInode);
7534            } catch (InstallerException e) {
7535                Slog.w(TAG, String.valueOf(e));
7536            }
7537        }
7538    }
7539
7540    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7541        if (pkg == null) {
7542            Slog.wtf(TAG, "Package was null!", new Throwable());
7543            return;
7544        }
7545        destroyAppDataLeafLIF(pkg, userId, flags);
7546        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7547        for (int i = 0; i < childCount; i++) {
7548            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7549        }
7550    }
7551
7552    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7553        final PackageSetting ps;
7554        synchronized (mPackages) {
7555            ps = mSettings.mPackages.get(pkg.packageName);
7556        }
7557        for (int realUserId : resolveUserIds(userId)) {
7558            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7559            try {
7560                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7561                        ceDataInode);
7562            } catch (InstallerException e) {
7563                Slog.w(TAG, String.valueOf(e));
7564            }
7565        }
7566    }
7567
7568    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7569        if (pkg == null) {
7570            Slog.wtf(TAG, "Package was null!", new Throwable());
7571            return;
7572        }
7573        destroyAppProfilesLeafLIF(pkg);
7574        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7575        for (int i = 0; i < childCount; i++) {
7576            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7577        }
7578    }
7579
7580    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7581        try {
7582            mInstaller.destroyAppProfiles(pkg.packageName);
7583        } catch (InstallerException e) {
7584            Slog.w(TAG, String.valueOf(e));
7585        }
7586    }
7587
7588    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7589        if (pkg == null) {
7590            Slog.wtf(TAG, "Package was null!", new Throwable());
7591            return;
7592        }
7593        clearAppProfilesLeafLIF(pkg);
7594        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7595        for (int i = 0; i < childCount; i++) {
7596            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7597        }
7598    }
7599
7600    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7601        try {
7602            mInstaller.clearAppProfiles(pkg.packageName);
7603        } catch (InstallerException e) {
7604            Slog.w(TAG, String.valueOf(e));
7605        }
7606    }
7607
7608    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7609            long lastUpdateTime) {
7610        // Set parent install/update time
7611        PackageSetting ps = (PackageSetting) pkg.mExtras;
7612        if (ps != null) {
7613            ps.firstInstallTime = firstInstallTime;
7614            ps.lastUpdateTime = lastUpdateTime;
7615        }
7616        // Set children install/update time
7617        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7618        for (int i = 0; i < childCount; i++) {
7619            PackageParser.Package childPkg = pkg.childPackages.get(i);
7620            ps = (PackageSetting) childPkg.mExtras;
7621            if (ps != null) {
7622                ps.firstInstallTime = firstInstallTime;
7623                ps.lastUpdateTime = lastUpdateTime;
7624            }
7625        }
7626    }
7627
7628    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7629            PackageParser.Package changingLib) {
7630        if (file.path != null) {
7631            usesLibraryFiles.add(file.path);
7632            return;
7633        }
7634        PackageParser.Package p = mPackages.get(file.apk);
7635        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7636            // If we are doing this while in the middle of updating a library apk,
7637            // then we need to make sure to use that new apk for determining the
7638            // dependencies here.  (We haven't yet finished committing the new apk
7639            // to the package manager state.)
7640            if (p == null || p.packageName.equals(changingLib.packageName)) {
7641                p = changingLib;
7642            }
7643        }
7644        if (p != null) {
7645            usesLibraryFiles.addAll(p.getAllCodePaths());
7646        }
7647    }
7648
7649    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7650            PackageParser.Package changingLib) throws PackageManagerException {
7651        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7652            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7653            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7654            for (int i=0; i<N; i++) {
7655                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7656                if (file == null) {
7657                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7658                            "Package " + pkg.packageName + " requires unavailable shared library "
7659                            + pkg.usesLibraries.get(i) + "; failing!");
7660                }
7661                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7662            }
7663            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7664            for (int i=0; i<N; i++) {
7665                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7666                if (file == null) {
7667                    Slog.w(TAG, "Package " + pkg.packageName
7668                            + " desires unavailable shared library "
7669                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7670                } else {
7671                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7672                }
7673            }
7674            N = usesLibraryFiles.size();
7675            if (N > 0) {
7676                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7677            } else {
7678                pkg.usesLibraryFiles = null;
7679            }
7680        }
7681    }
7682
7683    private static boolean hasString(List<String> list, List<String> which) {
7684        if (list == null) {
7685            return false;
7686        }
7687        for (int i=list.size()-1; i>=0; i--) {
7688            for (int j=which.size()-1; j>=0; j--) {
7689                if (which.get(j).equals(list.get(i))) {
7690                    return true;
7691                }
7692            }
7693        }
7694        return false;
7695    }
7696
7697    private void updateAllSharedLibrariesLPw() {
7698        for (PackageParser.Package pkg : mPackages.values()) {
7699            try {
7700                updateSharedLibrariesLPw(pkg, null);
7701            } catch (PackageManagerException e) {
7702                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7703            }
7704        }
7705    }
7706
7707    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7708            PackageParser.Package changingPkg) {
7709        ArrayList<PackageParser.Package> res = null;
7710        for (PackageParser.Package pkg : mPackages.values()) {
7711            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7712                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7713                if (res == null) {
7714                    res = new ArrayList<PackageParser.Package>();
7715                }
7716                res.add(pkg);
7717                try {
7718                    updateSharedLibrariesLPw(pkg, changingPkg);
7719                } catch (PackageManagerException e) {
7720                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7721                }
7722            }
7723        }
7724        return res;
7725    }
7726
7727    /**
7728     * Derive the value of the {@code cpuAbiOverride} based on the provided
7729     * value and an optional stored value from the package settings.
7730     */
7731    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7732        String cpuAbiOverride = null;
7733
7734        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7735            cpuAbiOverride = null;
7736        } else if (abiOverride != null) {
7737            cpuAbiOverride = abiOverride;
7738        } else if (settings != null) {
7739            cpuAbiOverride = settings.cpuAbiOverrideString;
7740        }
7741
7742        return cpuAbiOverride;
7743    }
7744
7745    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7746            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7747                    throws PackageManagerException {
7748        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7749        // If the package has children and this is the first dive in the function
7750        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7751        // whether all packages (parent and children) would be successfully scanned
7752        // before the actual scan since scanning mutates internal state and we want
7753        // to atomically install the package and its children.
7754        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7755            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7756                scanFlags |= SCAN_CHECK_ONLY;
7757            }
7758        } else {
7759            scanFlags &= ~SCAN_CHECK_ONLY;
7760        }
7761
7762        final PackageParser.Package scannedPkg;
7763        try {
7764            // Scan the parent
7765            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7766            // Scan the children
7767            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7768            for (int i = 0; i < childCount; i++) {
7769                PackageParser.Package childPkg = pkg.childPackages.get(i);
7770                scanPackageLI(childPkg, policyFlags,
7771                        scanFlags, currentTime, user);
7772            }
7773        } finally {
7774            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7775        }
7776
7777        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7778            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7779        }
7780
7781        return scannedPkg;
7782    }
7783
7784    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7785            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7786        boolean success = false;
7787        try {
7788            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7789                    currentTime, user);
7790            success = true;
7791            return res;
7792        } finally {
7793            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7794                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7795                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7796                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7797                destroyAppProfilesLIF(pkg);
7798            }
7799        }
7800    }
7801
7802    /**
7803     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7804     */
7805    private static boolean apkHasCode(String fileName) {
7806        StrictJarFile jarFile = null;
7807        try {
7808            jarFile = new StrictJarFile(fileName,
7809                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7810            return jarFile.findEntry("classes.dex") != null;
7811        } catch (IOException ignore) {
7812        } finally {
7813            try {
7814                jarFile.close();
7815            } catch (IOException ignore) {}
7816        }
7817        return false;
7818    }
7819
7820    /**
7821     * Enforces code policy for the package. This ensures that if an APK has
7822     * declared hasCode="true" in its manifest that the APK actually contains
7823     * code.
7824     *
7825     * @throws PackageManagerException If bytecode could not be found when it should exist
7826     */
7827    private static void enforceCodePolicy(PackageParser.Package pkg)
7828            throws PackageManagerException {
7829        final boolean shouldHaveCode =
7830                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7831        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7832            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7833                    "Package " + pkg.baseCodePath + " code is missing");
7834        }
7835
7836        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7837            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7838                final boolean splitShouldHaveCode =
7839                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7840                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7841                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7842                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7843                }
7844            }
7845        }
7846    }
7847
7848    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7849            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7850            throws PackageManagerException {
7851        final File scanFile = new File(pkg.codePath);
7852        if (pkg.applicationInfo.getCodePath() == null ||
7853                pkg.applicationInfo.getResourcePath() == null) {
7854            // Bail out. The resource and code paths haven't been set.
7855            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7856                    "Code and resource paths haven't been set correctly");
7857        }
7858
7859        // Apply policy
7860        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7861            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7862            if (pkg.applicationInfo.isDirectBootAware()) {
7863                // we're direct boot aware; set for all components
7864                for (PackageParser.Service s : pkg.services) {
7865                    s.info.encryptionAware = s.info.directBootAware = true;
7866                }
7867                for (PackageParser.Provider p : pkg.providers) {
7868                    p.info.encryptionAware = p.info.directBootAware = true;
7869                }
7870                for (PackageParser.Activity a : pkg.activities) {
7871                    a.info.encryptionAware = a.info.directBootAware = true;
7872                }
7873                for (PackageParser.Activity r : pkg.receivers) {
7874                    r.info.encryptionAware = r.info.directBootAware = true;
7875                }
7876            }
7877        } else {
7878            // Only allow system apps to be flagged as core apps.
7879            pkg.coreApp = false;
7880            // clear flags not applicable to regular apps
7881            pkg.applicationInfo.privateFlags &=
7882                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7883            pkg.applicationInfo.privateFlags &=
7884                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7885        }
7886        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7887
7888        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7889            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7890        }
7891
7892        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7893            enforceCodePolicy(pkg);
7894        }
7895
7896        if (mCustomResolverComponentName != null &&
7897                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7898            setUpCustomResolverActivity(pkg);
7899        }
7900
7901        if (pkg.packageName.equals("android")) {
7902            synchronized (mPackages) {
7903                if (mAndroidApplication != null) {
7904                    Slog.w(TAG, "*************************************************");
7905                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7906                    Slog.w(TAG, " file=" + scanFile);
7907                    Slog.w(TAG, "*************************************************");
7908                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7909                            "Core android package being redefined.  Skipping.");
7910                }
7911
7912                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7913                    // Set up information for our fall-back user intent resolution activity.
7914                    mPlatformPackage = pkg;
7915                    pkg.mVersionCode = mSdkVersion;
7916                    mAndroidApplication = pkg.applicationInfo;
7917
7918                    if (!mResolverReplaced) {
7919                        mResolveActivity.applicationInfo = mAndroidApplication;
7920                        mResolveActivity.name = ResolverActivity.class.getName();
7921                        mResolveActivity.packageName = mAndroidApplication.packageName;
7922                        mResolveActivity.processName = "system:ui";
7923                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7924                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7925                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7926                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7927                        mResolveActivity.exported = true;
7928                        mResolveActivity.enabled = true;
7929                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7930                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7931                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7932                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7933                                | ActivityInfo.CONFIG_ORIENTATION
7934                                | ActivityInfo.CONFIG_KEYBOARD
7935                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7936                        mResolveInfo.activityInfo = mResolveActivity;
7937                        mResolveInfo.priority = 0;
7938                        mResolveInfo.preferredOrder = 0;
7939                        mResolveInfo.match = 0;
7940                        mResolveComponentName = new ComponentName(
7941                                mAndroidApplication.packageName, mResolveActivity.name);
7942                    }
7943                }
7944            }
7945        }
7946
7947        if (DEBUG_PACKAGE_SCANNING) {
7948            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7949                Log.d(TAG, "Scanning package " + pkg.packageName);
7950        }
7951
7952        synchronized (mPackages) {
7953            if (mPackages.containsKey(pkg.packageName)
7954                    || mSharedLibraries.containsKey(pkg.packageName)) {
7955                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7956                        "Application package " + pkg.packageName
7957                                + " already installed.  Skipping duplicate.");
7958            }
7959
7960            // If we're only installing presumed-existing packages, require that the
7961            // scanned APK is both already known and at the path previously established
7962            // for it.  Previously unknown packages we pick up normally, but if we have an
7963            // a priori expectation about this package's install presence, enforce it.
7964            // With a singular exception for new system packages. When an OTA contains
7965            // a new system package, we allow the codepath to change from a system location
7966            // to the user-installed location. If we don't allow this change, any newer,
7967            // user-installed version of the application will be ignored.
7968            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7969                if (mExpectingBetter.containsKey(pkg.packageName)) {
7970                    logCriticalInfo(Log.WARN,
7971                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7972                } else {
7973                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7974                    if (known != null) {
7975                        if (DEBUG_PACKAGE_SCANNING) {
7976                            Log.d(TAG, "Examining " + pkg.codePath
7977                                    + " and requiring known paths " + known.codePathString
7978                                    + " & " + known.resourcePathString);
7979                        }
7980                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7981                                || !pkg.applicationInfo.getResourcePath().equals(
7982                                known.resourcePathString)) {
7983                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7984                                    "Application package " + pkg.packageName
7985                                            + " found at " + pkg.applicationInfo.getCodePath()
7986                                            + " but expected at " + known.codePathString
7987                                            + "; ignoring.");
7988                        }
7989                    }
7990                }
7991            }
7992        }
7993
7994        // Initialize package source and resource directories
7995        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7996        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7997
7998        SharedUserSetting suid = null;
7999        PackageSetting pkgSetting = null;
8000
8001        if (!isSystemApp(pkg)) {
8002            // Only system apps can use these features.
8003            pkg.mOriginalPackages = null;
8004            pkg.mRealPackage = null;
8005            pkg.mAdoptPermissions = null;
8006        }
8007
8008        // Getting the package setting may have a side-effect, so if we
8009        // are only checking if scan would succeed, stash a copy of the
8010        // old setting to restore at the end.
8011        PackageSetting nonMutatedPs = null;
8012
8013        // writer
8014        synchronized (mPackages) {
8015            if (pkg.mSharedUserId != null) {
8016                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8017                if (suid == null) {
8018                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8019                            "Creating application package " + pkg.packageName
8020                            + " for shared user failed");
8021                }
8022                if (DEBUG_PACKAGE_SCANNING) {
8023                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8024                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8025                                + "): packages=" + suid.packages);
8026                }
8027            }
8028
8029            // Check if we are renaming from an original package name.
8030            PackageSetting origPackage = null;
8031            String realName = null;
8032            if (pkg.mOriginalPackages != null) {
8033                // This package may need to be renamed to a previously
8034                // installed name.  Let's check on that...
8035                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8036                if (pkg.mOriginalPackages.contains(renamed)) {
8037                    // This package had originally been installed as the
8038                    // original name, and we have already taken care of
8039                    // transitioning to the new one.  Just update the new
8040                    // one to continue using the old name.
8041                    realName = pkg.mRealPackage;
8042                    if (!pkg.packageName.equals(renamed)) {
8043                        // Callers into this function may have already taken
8044                        // care of renaming the package; only do it here if
8045                        // it is not already done.
8046                        pkg.setPackageName(renamed);
8047                    }
8048
8049                } else {
8050                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8051                        if ((origPackage = mSettings.peekPackageLPr(
8052                                pkg.mOriginalPackages.get(i))) != null) {
8053                            // We do have the package already installed under its
8054                            // original name...  should we use it?
8055                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8056                                // New package is not compatible with original.
8057                                origPackage = null;
8058                                continue;
8059                            } else if (origPackage.sharedUser != null) {
8060                                // Make sure uid is compatible between packages.
8061                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8062                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8063                                            + " to " + pkg.packageName + ": old uid "
8064                                            + origPackage.sharedUser.name
8065                                            + " differs from " + pkg.mSharedUserId);
8066                                    origPackage = null;
8067                                    continue;
8068                                }
8069                                // TODO: Add case when shared user id is added [b/28144775]
8070                            } else {
8071                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8072                                        + pkg.packageName + " to old name " + origPackage.name);
8073                            }
8074                            break;
8075                        }
8076                    }
8077                }
8078            }
8079
8080            if (mTransferedPackages.contains(pkg.packageName)) {
8081                Slog.w(TAG, "Package " + pkg.packageName
8082                        + " was transferred to another, but its .apk remains");
8083            }
8084
8085            // See comments in nonMutatedPs declaration
8086            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8087                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8088                if (foundPs != null) {
8089                    nonMutatedPs = new PackageSetting(foundPs);
8090                }
8091            }
8092
8093            // Just create the setting, don't add it yet. For already existing packages
8094            // the PkgSetting exists already and doesn't have to be created.
8095            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8096                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8097                    pkg.applicationInfo.primaryCpuAbi,
8098                    pkg.applicationInfo.secondaryCpuAbi,
8099                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8100                    user, false);
8101            if (pkgSetting == null) {
8102                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8103                        "Creating application package " + pkg.packageName + " failed");
8104            }
8105
8106            if (pkgSetting.origPackage != null) {
8107                // If we are first transitioning from an original package,
8108                // fix up the new package's name now.  We need to do this after
8109                // looking up the package under its new name, so getPackageLP
8110                // can take care of fiddling things correctly.
8111                pkg.setPackageName(origPackage.name);
8112
8113                // File a report about this.
8114                String msg = "New package " + pkgSetting.realName
8115                        + " renamed to replace old package " + pkgSetting.name;
8116                reportSettingsProblem(Log.WARN, msg);
8117
8118                // Make a note of it.
8119                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8120                    mTransferedPackages.add(origPackage.name);
8121                }
8122
8123                // No longer need to retain this.
8124                pkgSetting.origPackage = null;
8125            }
8126
8127            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8128                // Make a note of it.
8129                mTransferedPackages.add(pkg.packageName);
8130            }
8131
8132            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8133                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8134            }
8135
8136            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8137                // Check all shared libraries and map to their actual file path.
8138                // We only do this here for apps not on a system dir, because those
8139                // are the only ones that can fail an install due to this.  We
8140                // will take care of the system apps by updating all of their
8141                // library paths after the scan is done.
8142                updateSharedLibrariesLPw(pkg, null);
8143            }
8144
8145            if (mFoundPolicyFile) {
8146                SELinuxMMAC.assignSeinfoValue(pkg);
8147            }
8148
8149            pkg.applicationInfo.uid = pkgSetting.appId;
8150            pkg.mExtras = pkgSetting;
8151            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8152                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8153                    // We just determined the app is signed correctly, so bring
8154                    // over the latest parsed certs.
8155                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8156                } else {
8157                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8158                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8159                                "Package " + pkg.packageName + " upgrade keys do not match the "
8160                                + "previously installed version");
8161                    } else {
8162                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8163                        String msg = "System package " + pkg.packageName
8164                            + " signature changed; retaining data.";
8165                        reportSettingsProblem(Log.WARN, msg);
8166                    }
8167                }
8168            } else {
8169                try {
8170                    verifySignaturesLP(pkgSetting, pkg);
8171                    // We just determined the app is signed correctly, so bring
8172                    // over the latest parsed certs.
8173                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8174                } catch (PackageManagerException e) {
8175                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8176                        throw e;
8177                    }
8178                    // The signature has changed, but this package is in the system
8179                    // image...  let's recover!
8180                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8181                    // However...  if this package is part of a shared user, but it
8182                    // doesn't match the signature of the shared user, let's fail.
8183                    // What this means is that you can't change the signatures
8184                    // associated with an overall shared user, which doesn't seem all
8185                    // that unreasonable.
8186                    if (pkgSetting.sharedUser != null) {
8187                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8188                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8189                            throw new PackageManagerException(
8190                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8191                                            "Signature mismatch for shared user: "
8192                                            + pkgSetting.sharedUser);
8193                        }
8194                    }
8195                    // File a report about this.
8196                    String msg = "System package " + pkg.packageName
8197                        + " signature changed; retaining data.";
8198                    reportSettingsProblem(Log.WARN, msg);
8199                }
8200            }
8201            // Verify that this new package doesn't have any content providers
8202            // that conflict with existing packages.  Only do this if the
8203            // package isn't already installed, since we don't want to break
8204            // things that are installed.
8205            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8206                final int N = pkg.providers.size();
8207                int i;
8208                for (i=0; i<N; i++) {
8209                    PackageParser.Provider p = pkg.providers.get(i);
8210                    if (p.info.authority != null) {
8211                        String names[] = p.info.authority.split(";");
8212                        for (int j = 0; j < names.length; j++) {
8213                            if (mProvidersByAuthority.containsKey(names[j])) {
8214                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8215                                final String otherPackageName =
8216                                        ((other != null && other.getComponentName() != null) ?
8217                                                other.getComponentName().getPackageName() : "?");
8218                                throw new PackageManagerException(
8219                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8220                                                "Can't install because provider name " + names[j]
8221                                                + " (in package " + pkg.applicationInfo.packageName
8222                                                + ") is already used by " + otherPackageName);
8223                            }
8224                        }
8225                    }
8226                }
8227            }
8228
8229            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8230                // This package wants to adopt ownership of permissions from
8231                // another package.
8232                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8233                    final String origName = pkg.mAdoptPermissions.get(i);
8234                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8235                    if (orig != null) {
8236                        if (verifyPackageUpdateLPr(orig, pkg)) {
8237                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8238                                    + pkg.packageName);
8239                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8240                        }
8241                    }
8242                }
8243            }
8244        }
8245
8246        final String pkgName = pkg.packageName;
8247
8248        final long scanFileTime = scanFile.lastModified();
8249        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8250        pkg.applicationInfo.processName = fixProcessName(
8251                pkg.applicationInfo.packageName,
8252                pkg.applicationInfo.processName,
8253                pkg.applicationInfo.uid);
8254
8255        if (pkg != mPlatformPackage) {
8256            // Get all of our default paths setup
8257            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8258        }
8259
8260        final String path = scanFile.getPath();
8261        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8262
8263        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8264            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8265
8266            // Some system apps still use directory structure for native libraries
8267            // in which case we might end up not detecting abi solely based on apk
8268            // structure. Try to detect abi based on directory structure.
8269            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8270                    pkg.applicationInfo.primaryCpuAbi == null) {
8271                setBundledAppAbisAndRoots(pkg, pkgSetting);
8272                setNativeLibraryPaths(pkg);
8273            }
8274
8275        } else {
8276            if ((scanFlags & SCAN_MOVE) != 0) {
8277                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8278                // but we already have this packages package info in the PackageSetting. We just
8279                // use that and derive the native library path based on the new codepath.
8280                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8281                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8282            }
8283
8284            // Set native library paths again. For moves, the path will be updated based on the
8285            // ABIs we've determined above. For non-moves, the path will be updated based on the
8286            // ABIs we determined during compilation, but the path will depend on the final
8287            // package path (after the rename away from the stage path).
8288            setNativeLibraryPaths(pkg);
8289        }
8290
8291        // This is a special case for the "system" package, where the ABI is
8292        // dictated by the zygote configuration (and init.rc). We should keep track
8293        // of this ABI so that we can deal with "normal" applications that run under
8294        // the same UID correctly.
8295        if (mPlatformPackage == pkg) {
8296            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8297                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8298        }
8299
8300        // If there's a mismatch between the abi-override in the package setting
8301        // and the abiOverride specified for the install. Warn about this because we
8302        // would've already compiled the app without taking the package setting into
8303        // account.
8304        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8305            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8306                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8307                        " for package " + pkg.packageName);
8308            }
8309        }
8310
8311        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8312        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8313        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8314
8315        // Copy the derived override back to the parsed package, so that we can
8316        // update the package settings accordingly.
8317        pkg.cpuAbiOverride = cpuAbiOverride;
8318
8319        if (DEBUG_ABI_SELECTION) {
8320            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8321                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8322                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8323        }
8324
8325        // Push the derived path down into PackageSettings so we know what to
8326        // clean up at uninstall time.
8327        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8328
8329        if (DEBUG_ABI_SELECTION) {
8330            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8331                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8332                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8333        }
8334
8335        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8336            // We don't do this here during boot because we can do it all
8337            // at once after scanning all existing packages.
8338            //
8339            // We also do this *before* we perform dexopt on this package, so that
8340            // we can avoid redundant dexopts, and also to make sure we've got the
8341            // code and package path correct.
8342            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8343                    pkg, true /* boot complete */);
8344        }
8345
8346        if (mFactoryTest && pkg.requestedPermissions.contains(
8347                android.Manifest.permission.FACTORY_TEST)) {
8348            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8349        }
8350
8351        ArrayList<PackageParser.Package> clientLibPkgs = null;
8352
8353        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8354            if (nonMutatedPs != null) {
8355                synchronized (mPackages) {
8356                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8357                }
8358            }
8359            return pkg;
8360        }
8361
8362        // Only privileged apps and updated privileged apps can add child packages.
8363        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8364            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8365                throw new PackageManagerException("Only privileged apps and updated "
8366                        + "privileged apps can add child packages. Ignoring package "
8367                        + pkg.packageName);
8368            }
8369            final int childCount = pkg.childPackages.size();
8370            for (int i = 0; i < childCount; i++) {
8371                PackageParser.Package childPkg = pkg.childPackages.get(i);
8372                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8373                        childPkg.packageName)) {
8374                    throw new PackageManagerException("Cannot override a child package of "
8375                            + "another disabled system app. Ignoring package " + pkg.packageName);
8376                }
8377            }
8378        }
8379
8380        // writer
8381        synchronized (mPackages) {
8382            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8383                // Only system apps can add new shared libraries.
8384                if (pkg.libraryNames != null) {
8385                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8386                        String name = pkg.libraryNames.get(i);
8387                        boolean allowed = false;
8388                        if (pkg.isUpdatedSystemApp()) {
8389                            // New library entries can only be added through the
8390                            // system image.  This is important to get rid of a lot
8391                            // of nasty edge cases: for example if we allowed a non-
8392                            // system update of the app to add a library, then uninstalling
8393                            // the update would make the library go away, and assumptions
8394                            // we made such as through app install filtering would now
8395                            // have allowed apps on the device which aren't compatible
8396                            // with it.  Better to just have the restriction here, be
8397                            // conservative, and create many fewer cases that can negatively
8398                            // impact the user experience.
8399                            final PackageSetting sysPs = mSettings
8400                                    .getDisabledSystemPkgLPr(pkg.packageName);
8401                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8402                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8403                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8404                                        allowed = true;
8405                                        break;
8406                                    }
8407                                }
8408                            }
8409                        } else {
8410                            allowed = true;
8411                        }
8412                        if (allowed) {
8413                            if (!mSharedLibraries.containsKey(name)) {
8414                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8415                            } else if (!name.equals(pkg.packageName)) {
8416                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8417                                        + name + " already exists; skipping");
8418                            }
8419                        } else {
8420                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8421                                    + name + " that is not declared on system image; skipping");
8422                        }
8423                    }
8424                    if ((scanFlags & SCAN_BOOTING) == 0) {
8425                        // If we are not booting, we need to update any applications
8426                        // that are clients of our shared library.  If we are booting,
8427                        // this will all be done once the scan is complete.
8428                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8429                    }
8430                }
8431            }
8432        }
8433
8434        if ((scanFlags & SCAN_BOOTING) != 0) {
8435            // No apps can run during boot scan, so they don't need to be frozen
8436        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8437            // Caller asked to not kill app, so it's probably not frozen
8438        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8439            // Caller asked us to ignore frozen check for some reason; they
8440            // probably didn't know the package name
8441        } else {
8442            // We're doing major surgery on this package, so it better be frozen
8443            // right now to keep it from launching
8444            checkPackageFrozen(pkgName);
8445        }
8446
8447        // Also need to kill any apps that are dependent on the library.
8448        if (clientLibPkgs != null) {
8449            for (int i=0; i<clientLibPkgs.size(); i++) {
8450                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8451                killApplication(clientPkg.applicationInfo.packageName,
8452                        clientPkg.applicationInfo.uid, "update lib");
8453            }
8454        }
8455
8456        // Make sure we're not adding any bogus keyset info
8457        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8458        ksms.assertScannedPackageValid(pkg);
8459
8460        // writer
8461        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8462
8463        boolean createIdmapFailed = false;
8464        synchronized (mPackages) {
8465            // We don't expect installation to fail beyond this point
8466
8467            // Add the new setting to mSettings
8468            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8469            // Add the new setting to mPackages
8470            mPackages.put(pkg.applicationInfo.packageName, pkg);
8471            // Make sure we don't accidentally delete its data.
8472            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8473            while (iter.hasNext()) {
8474                PackageCleanItem item = iter.next();
8475                if (pkgName.equals(item.packageName)) {
8476                    iter.remove();
8477                }
8478            }
8479
8480            // Take care of first install / last update times.
8481            if (currentTime != 0) {
8482                if (pkgSetting.firstInstallTime == 0) {
8483                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8484                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8485                    pkgSetting.lastUpdateTime = currentTime;
8486                }
8487            } else if (pkgSetting.firstInstallTime == 0) {
8488                // We need *something*.  Take time time stamp of the file.
8489                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8490            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8491                if (scanFileTime != pkgSetting.timeStamp) {
8492                    // A package on the system image has changed; consider this
8493                    // to be an update.
8494                    pkgSetting.lastUpdateTime = scanFileTime;
8495                }
8496            }
8497
8498            // Add the package's KeySets to the global KeySetManagerService
8499            ksms.addScannedPackageLPw(pkg);
8500
8501            int N = pkg.providers.size();
8502            StringBuilder r = null;
8503            int i;
8504            for (i=0; i<N; i++) {
8505                PackageParser.Provider p = pkg.providers.get(i);
8506                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8507                        p.info.processName, pkg.applicationInfo.uid);
8508                mProviders.addProvider(p);
8509                p.syncable = p.info.isSyncable;
8510                if (p.info.authority != null) {
8511                    String names[] = p.info.authority.split(";");
8512                    p.info.authority = null;
8513                    for (int j = 0; j < names.length; j++) {
8514                        if (j == 1 && p.syncable) {
8515                            // We only want the first authority for a provider to possibly be
8516                            // syncable, so if we already added this provider using a different
8517                            // authority clear the syncable flag. We copy the provider before
8518                            // changing it because the mProviders object contains a reference
8519                            // to a provider that we don't want to change.
8520                            // Only do this for the second authority since the resulting provider
8521                            // object can be the same for all future authorities for this provider.
8522                            p = new PackageParser.Provider(p);
8523                            p.syncable = false;
8524                        }
8525                        if (!mProvidersByAuthority.containsKey(names[j])) {
8526                            mProvidersByAuthority.put(names[j], p);
8527                            if (p.info.authority == null) {
8528                                p.info.authority = names[j];
8529                            } else {
8530                                p.info.authority = p.info.authority + ";" + names[j];
8531                            }
8532                            if (DEBUG_PACKAGE_SCANNING) {
8533                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8534                                    Log.d(TAG, "Registered content provider: " + names[j]
8535                                            + ", className = " + p.info.name + ", isSyncable = "
8536                                            + p.info.isSyncable);
8537                            }
8538                        } else {
8539                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8540                            Slog.w(TAG, "Skipping provider name " + names[j] +
8541                                    " (in package " + pkg.applicationInfo.packageName +
8542                                    "): name already used by "
8543                                    + ((other != null && other.getComponentName() != null)
8544                                            ? other.getComponentName().getPackageName() : "?"));
8545                        }
8546                    }
8547                }
8548                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8549                    if (r == null) {
8550                        r = new StringBuilder(256);
8551                    } else {
8552                        r.append(' ');
8553                    }
8554                    r.append(p.info.name);
8555                }
8556            }
8557            if (r != null) {
8558                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8559            }
8560
8561            N = pkg.services.size();
8562            r = null;
8563            for (i=0; i<N; i++) {
8564                PackageParser.Service s = pkg.services.get(i);
8565                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8566                        s.info.processName, pkg.applicationInfo.uid);
8567                mServices.addService(s);
8568                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8569                    if (r == null) {
8570                        r = new StringBuilder(256);
8571                    } else {
8572                        r.append(' ');
8573                    }
8574                    r.append(s.info.name);
8575                }
8576            }
8577            if (r != null) {
8578                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8579            }
8580
8581            N = pkg.receivers.size();
8582            r = null;
8583            for (i=0; i<N; i++) {
8584                PackageParser.Activity a = pkg.receivers.get(i);
8585                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8586                        a.info.processName, pkg.applicationInfo.uid);
8587                mReceivers.addActivity(a, "receiver");
8588                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8589                    if (r == null) {
8590                        r = new StringBuilder(256);
8591                    } else {
8592                        r.append(' ');
8593                    }
8594                    r.append(a.info.name);
8595                }
8596            }
8597            if (r != null) {
8598                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8599            }
8600
8601            N = pkg.activities.size();
8602            r = null;
8603            for (i=0; i<N; i++) {
8604                PackageParser.Activity a = pkg.activities.get(i);
8605                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8606                        a.info.processName, pkg.applicationInfo.uid);
8607                mActivities.addActivity(a, "activity");
8608                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8609                    if (r == null) {
8610                        r = new StringBuilder(256);
8611                    } else {
8612                        r.append(' ');
8613                    }
8614                    r.append(a.info.name);
8615                }
8616            }
8617            if (r != null) {
8618                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8619            }
8620
8621            N = pkg.permissionGroups.size();
8622            r = null;
8623            for (i=0; i<N; i++) {
8624                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8625                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8626                if (cur == null) {
8627                    mPermissionGroups.put(pg.info.name, pg);
8628                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8629                        if (r == null) {
8630                            r = new StringBuilder(256);
8631                        } else {
8632                            r.append(' ');
8633                        }
8634                        r.append(pg.info.name);
8635                    }
8636                } else {
8637                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8638                            + pg.info.packageName + " ignored: original from "
8639                            + cur.info.packageName);
8640                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8641                        if (r == null) {
8642                            r = new StringBuilder(256);
8643                        } else {
8644                            r.append(' ');
8645                        }
8646                        r.append("DUP:");
8647                        r.append(pg.info.name);
8648                    }
8649                }
8650            }
8651            if (r != null) {
8652                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8653            }
8654
8655            N = pkg.permissions.size();
8656            r = null;
8657            for (i=0; i<N; i++) {
8658                PackageParser.Permission p = pkg.permissions.get(i);
8659
8660                // Assume by default that we did not install this permission into the system.
8661                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8662
8663                // Now that permission groups have a special meaning, we ignore permission
8664                // groups for legacy apps to prevent unexpected behavior. In particular,
8665                // permissions for one app being granted to someone just becase they happen
8666                // to be in a group defined by another app (before this had no implications).
8667                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8668                    p.group = mPermissionGroups.get(p.info.group);
8669                    // Warn for a permission in an unknown group.
8670                    if (p.info.group != null && p.group == null) {
8671                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8672                                + p.info.packageName + " in an unknown group " + p.info.group);
8673                    }
8674                }
8675
8676                ArrayMap<String, BasePermission> permissionMap =
8677                        p.tree ? mSettings.mPermissionTrees
8678                                : mSettings.mPermissions;
8679                BasePermission bp = permissionMap.get(p.info.name);
8680
8681                // Allow system apps to redefine non-system permissions
8682                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8683                    final boolean currentOwnerIsSystem = (bp.perm != null
8684                            && isSystemApp(bp.perm.owner));
8685                    if (isSystemApp(p.owner)) {
8686                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8687                            // It's a built-in permission and no owner, take ownership now
8688                            bp.packageSetting = pkgSetting;
8689                            bp.perm = p;
8690                            bp.uid = pkg.applicationInfo.uid;
8691                            bp.sourcePackage = p.info.packageName;
8692                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8693                        } else if (!currentOwnerIsSystem) {
8694                            String msg = "New decl " + p.owner + " of permission  "
8695                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8696                            reportSettingsProblem(Log.WARN, msg);
8697                            bp = null;
8698                        }
8699                    }
8700                }
8701
8702                if (bp == null) {
8703                    bp = new BasePermission(p.info.name, p.info.packageName,
8704                            BasePermission.TYPE_NORMAL);
8705                    permissionMap.put(p.info.name, bp);
8706                }
8707
8708                if (bp.perm == null) {
8709                    if (bp.sourcePackage == null
8710                            || bp.sourcePackage.equals(p.info.packageName)) {
8711                        BasePermission tree = findPermissionTreeLP(p.info.name);
8712                        if (tree == null
8713                                || tree.sourcePackage.equals(p.info.packageName)) {
8714                            bp.packageSetting = pkgSetting;
8715                            bp.perm = p;
8716                            bp.uid = pkg.applicationInfo.uid;
8717                            bp.sourcePackage = p.info.packageName;
8718                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8719                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8720                                if (r == null) {
8721                                    r = new StringBuilder(256);
8722                                } else {
8723                                    r.append(' ');
8724                                }
8725                                r.append(p.info.name);
8726                            }
8727                        } else {
8728                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8729                                    + p.info.packageName + " ignored: base tree "
8730                                    + tree.name + " is from package "
8731                                    + tree.sourcePackage);
8732                        }
8733                    } else {
8734                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8735                                + p.info.packageName + " ignored: original from "
8736                                + bp.sourcePackage);
8737                    }
8738                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8739                    if (r == null) {
8740                        r = new StringBuilder(256);
8741                    } else {
8742                        r.append(' ');
8743                    }
8744                    r.append("DUP:");
8745                    r.append(p.info.name);
8746                }
8747                if (bp.perm == p) {
8748                    bp.protectionLevel = p.info.protectionLevel;
8749                }
8750            }
8751
8752            if (r != null) {
8753                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8754            }
8755
8756            N = pkg.instrumentation.size();
8757            r = null;
8758            for (i=0; i<N; i++) {
8759                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8760                a.info.packageName = pkg.applicationInfo.packageName;
8761                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8762                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8763                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8764                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8765                a.info.dataDir = pkg.applicationInfo.dataDir;
8766                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8767                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8768
8769                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8770                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8771                mInstrumentation.put(a.getComponentName(), a);
8772                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8773                    if (r == null) {
8774                        r = new StringBuilder(256);
8775                    } else {
8776                        r.append(' ');
8777                    }
8778                    r.append(a.info.name);
8779                }
8780            }
8781            if (r != null) {
8782                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8783            }
8784
8785            if (pkg.protectedBroadcasts != null) {
8786                N = pkg.protectedBroadcasts.size();
8787                for (i=0; i<N; i++) {
8788                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8789                }
8790            }
8791
8792            pkgSetting.setTimeStamp(scanFileTime);
8793
8794            // Create idmap files for pairs of (packages, overlay packages).
8795            // Note: "android", ie framework-res.apk, is handled by native layers.
8796            if (pkg.mOverlayTarget != null) {
8797                // This is an overlay package.
8798                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8799                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8800                        mOverlays.put(pkg.mOverlayTarget,
8801                                new ArrayMap<String, PackageParser.Package>());
8802                    }
8803                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8804                    map.put(pkg.packageName, pkg);
8805                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8806                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8807                        createIdmapFailed = true;
8808                    }
8809                }
8810            } else if (mOverlays.containsKey(pkg.packageName) &&
8811                    !pkg.packageName.equals("android")) {
8812                // This is a regular package, with one or more known overlay packages.
8813                createIdmapsForPackageLI(pkg);
8814            }
8815        }
8816
8817        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8818
8819        if (createIdmapFailed) {
8820            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8821                    "scanPackageLI failed to createIdmap");
8822        }
8823        return pkg;
8824    }
8825
8826    /**
8827     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8828     * is derived purely on the basis of the contents of {@code scanFile} and
8829     * {@code cpuAbiOverride}.
8830     *
8831     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8832     */
8833    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8834                                 String cpuAbiOverride, boolean extractLibs)
8835            throws PackageManagerException {
8836        // TODO: We can probably be smarter about this stuff. For installed apps,
8837        // we can calculate this information at install time once and for all. For
8838        // system apps, we can probably assume that this information doesn't change
8839        // after the first boot scan. As things stand, we do lots of unnecessary work.
8840
8841        // Give ourselves some initial paths; we'll come back for another
8842        // pass once we've determined ABI below.
8843        setNativeLibraryPaths(pkg);
8844
8845        // We would never need to extract libs for forward-locked and external packages,
8846        // since the container service will do it for us. We shouldn't attempt to
8847        // extract libs from system app when it was not updated.
8848        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8849                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8850            extractLibs = false;
8851        }
8852
8853        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8854        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8855
8856        NativeLibraryHelper.Handle handle = null;
8857        try {
8858            handle = NativeLibraryHelper.Handle.create(pkg);
8859            // TODO(multiArch): This can be null for apps that didn't go through the
8860            // usual installation process. We can calculate it again, like we
8861            // do during install time.
8862            //
8863            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8864            // unnecessary.
8865            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8866
8867            // Null out the abis so that they can be recalculated.
8868            pkg.applicationInfo.primaryCpuAbi = null;
8869            pkg.applicationInfo.secondaryCpuAbi = null;
8870            if (isMultiArch(pkg.applicationInfo)) {
8871                // Warn if we've set an abiOverride for multi-lib packages..
8872                // By definition, we need to copy both 32 and 64 bit libraries for
8873                // such packages.
8874                if (pkg.cpuAbiOverride != null
8875                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8876                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8877                }
8878
8879                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8880                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8881                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8882                    if (extractLibs) {
8883                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8884                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8885                                useIsaSpecificSubdirs);
8886                    } else {
8887                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8888                    }
8889                }
8890
8891                maybeThrowExceptionForMultiArchCopy(
8892                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8893
8894                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8895                    if (extractLibs) {
8896                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8897                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8898                                useIsaSpecificSubdirs);
8899                    } else {
8900                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8901                    }
8902                }
8903
8904                maybeThrowExceptionForMultiArchCopy(
8905                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8906
8907                if (abi64 >= 0) {
8908                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8909                }
8910
8911                if (abi32 >= 0) {
8912                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8913                    if (abi64 >= 0) {
8914                        if (pkg.use32bitAbi) {
8915                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8916                            pkg.applicationInfo.primaryCpuAbi = abi;
8917                        } else {
8918                            pkg.applicationInfo.secondaryCpuAbi = abi;
8919                        }
8920                    } else {
8921                        pkg.applicationInfo.primaryCpuAbi = abi;
8922                    }
8923                }
8924
8925            } else {
8926                String[] abiList = (cpuAbiOverride != null) ?
8927                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8928
8929                // Enable gross and lame hacks for apps that are built with old
8930                // SDK tools. We must scan their APKs for renderscript bitcode and
8931                // not launch them if it's present. Don't bother checking on devices
8932                // that don't have 64 bit support.
8933                boolean needsRenderScriptOverride = false;
8934                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8935                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8936                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8937                    needsRenderScriptOverride = true;
8938                }
8939
8940                final int copyRet;
8941                if (extractLibs) {
8942                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8943                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8944                } else {
8945                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8946                }
8947
8948                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8949                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8950                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8951                }
8952
8953                if (copyRet >= 0) {
8954                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8955                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8956                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8957                } else if (needsRenderScriptOverride) {
8958                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8959                }
8960            }
8961        } catch (IOException ioe) {
8962            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8963        } finally {
8964            IoUtils.closeQuietly(handle);
8965        }
8966
8967        // Now that we've calculated the ABIs and determined if it's an internal app,
8968        // we will go ahead and populate the nativeLibraryPath.
8969        setNativeLibraryPaths(pkg);
8970    }
8971
8972    /**
8973     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8974     * i.e, so that all packages can be run inside a single process if required.
8975     *
8976     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8977     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8978     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8979     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8980     * updating a package that belongs to a shared user.
8981     *
8982     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8983     * adds unnecessary complexity.
8984     */
8985    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8986            PackageParser.Package scannedPackage, boolean bootComplete) {
8987        String requiredInstructionSet = null;
8988        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8989            requiredInstructionSet = VMRuntime.getInstructionSet(
8990                     scannedPackage.applicationInfo.primaryCpuAbi);
8991        }
8992
8993        PackageSetting requirer = null;
8994        for (PackageSetting ps : packagesForUser) {
8995            // If packagesForUser contains scannedPackage, we skip it. This will happen
8996            // when scannedPackage is an update of an existing package. Without this check,
8997            // we will never be able to change the ABI of any package belonging to a shared
8998            // user, even if it's compatible with other packages.
8999            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9000                if (ps.primaryCpuAbiString == null) {
9001                    continue;
9002                }
9003
9004                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9005                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9006                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9007                    // this but there's not much we can do.
9008                    String errorMessage = "Instruction set mismatch, "
9009                            + ((requirer == null) ? "[caller]" : requirer)
9010                            + " requires " + requiredInstructionSet + " whereas " + ps
9011                            + " requires " + instructionSet;
9012                    Slog.w(TAG, errorMessage);
9013                }
9014
9015                if (requiredInstructionSet == null) {
9016                    requiredInstructionSet = instructionSet;
9017                    requirer = ps;
9018                }
9019            }
9020        }
9021
9022        if (requiredInstructionSet != null) {
9023            String adjustedAbi;
9024            if (requirer != null) {
9025                // requirer != null implies that either scannedPackage was null or that scannedPackage
9026                // did not require an ABI, in which case we have to adjust scannedPackage to match
9027                // the ABI of the set (which is the same as requirer's ABI)
9028                adjustedAbi = requirer.primaryCpuAbiString;
9029                if (scannedPackage != null) {
9030                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9031                }
9032            } else {
9033                // requirer == null implies that we're updating all ABIs in the set to
9034                // match scannedPackage.
9035                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9036            }
9037
9038            for (PackageSetting ps : packagesForUser) {
9039                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9040                    if (ps.primaryCpuAbiString != null) {
9041                        continue;
9042                    }
9043
9044                    ps.primaryCpuAbiString = adjustedAbi;
9045                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9046                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9047                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9048                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9049                                + " (requirer="
9050                                + (requirer == null ? "null" : requirer.pkg.packageName)
9051                                + ", scannedPackage="
9052                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9053                                + ")");
9054                        try {
9055                            mInstaller.rmdex(ps.codePathString,
9056                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9057                        } catch (InstallerException ignored) {
9058                        }
9059                    }
9060                }
9061            }
9062        }
9063    }
9064
9065    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9066        synchronized (mPackages) {
9067            mResolverReplaced = true;
9068            // Set up information for custom user intent resolution activity.
9069            mResolveActivity.applicationInfo = pkg.applicationInfo;
9070            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9071            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9072            mResolveActivity.processName = pkg.applicationInfo.packageName;
9073            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9074            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9075                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9076            mResolveActivity.theme = 0;
9077            mResolveActivity.exported = true;
9078            mResolveActivity.enabled = true;
9079            mResolveInfo.activityInfo = mResolveActivity;
9080            mResolveInfo.priority = 0;
9081            mResolveInfo.preferredOrder = 0;
9082            mResolveInfo.match = 0;
9083            mResolveComponentName = mCustomResolverComponentName;
9084            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9085                    mResolveComponentName);
9086        }
9087    }
9088
9089    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9090        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9091
9092        // Set up information for ephemeral installer activity
9093        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9094        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9095        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9096        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9097        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9098        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9099                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9100        mEphemeralInstallerActivity.theme = 0;
9101        mEphemeralInstallerActivity.exported = true;
9102        mEphemeralInstallerActivity.enabled = true;
9103        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9104        mEphemeralInstallerInfo.priority = 0;
9105        mEphemeralInstallerInfo.preferredOrder = 0;
9106        mEphemeralInstallerInfo.match = 0;
9107
9108        if (DEBUG_EPHEMERAL) {
9109            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9110        }
9111    }
9112
9113    private static String calculateBundledApkRoot(final String codePathString) {
9114        final File codePath = new File(codePathString);
9115        final File codeRoot;
9116        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9117            codeRoot = Environment.getRootDirectory();
9118        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9119            codeRoot = Environment.getOemDirectory();
9120        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9121            codeRoot = Environment.getVendorDirectory();
9122        } else {
9123            // Unrecognized code path; take its top real segment as the apk root:
9124            // e.g. /something/app/blah.apk => /something
9125            try {
9126                File f = codePath.getCanonicalFile();
9127                File parent = f.getParentFile();    // non-null because codePath is a file
9128                File tmp;
9129                while ((tmp = parent.getParentFile()) != null) {
9130                    f = parent;
9131                    parent = tmp;
9132                }
9133                codeRoot = f;
9134                Slog.w(TAG, "Unrecognized code path "
9135                        + codePath + " - using " + codeRoot);
9136            } catch (IOException e) {
9137                // Can't canonicalize the code path -- shenanigans?
9138                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9139                return Environment.getRootDirectory().getPath();
9140            }
9141        }
9142        return codeRoot.getPath();
9143    }
9144
9145    /**
9146     * Derive and set the location of native libraries for the given package,
9147     * which varies depending on where and how the package was installed.
9148     */
9149    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9150        final ApplicationInfo info = pkg.applicationInfo;
9151        final String codePath = pkg.codePath;
9152        final File codeFile = new File(codePath);
9153        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9154        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9155
9156        info.nativeLibraryRootDir = null;
9157        info.nativeLibraryRootRequiresIsa = false;
9158        info.nativeLibraryDir = null;
9159        info.secondaryNativeLibraryDir = null;
9160
9161        if (isApkFile(codeFile)) {
9162            // Monolithic install
9163            if (bundledApp) {
9164                // If "/system/lib64/apkname" exists, assume that is the per-package
9165                // native library directory to use; otherwise use "/system/lib/apkname".
9166                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9167                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9168                        getPrimaryInstructionSet(info));
9169
9170                // This is a bundled system app so choose the path based on the ABI.
9171                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9172                // is just the default path.
9173                final String apkName = deriveCodePathName(codePath);
9174                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9175                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9176                        apkName).getAbsolutePath();
9177
9178                if (info.secondaryCpuAbi != null) {
9179                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9180                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9181                            secondaryLibDir, apkName).getAbsolutePath();
9182                }
9183            } else if (asecApp) {
9184                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9185                        .getAbsolutePath();
9186            } else {
9187                final String apkName = deriveCodePathName(codePath);
9188                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9189                        .getAbsolutePath();
9190            }
9191
9192            info.nativeLibraryRootRequiresIsa = false;
9193            info.nativeLibraryDir = info.nativeLibraryRootDir;
9194        } else {
9195            // Cluster install
9196            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9197            info.nativeLibraryRootRequiresIsa = true;
9198
9199            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9200                    getPrimaryInstructionSet(info)).getAbsolutePath();
9201
9202            if (info.secondaryCpuAbi != null) {
9203                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9204                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9205            }
9206        }
9207    }
9208
9209    /**
9210     * Calculate the abis and roots for a bundled app. These can uniquely
9211     * be determined from the contents of the system partition, i.e whether
9212     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9213     * of this information, and instead assume that the system was built
9214     * sensibly.
9215     */
9216    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9217                                           PackageSetting pkgSetting) {
9218        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9219
9220        // If "/system/lib64/apkname" exists, assume that is the per-package
9221        // native library directory to use; otherwise use "/system/lib/apkname".
9222        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9223        setBundledAppAbi(pkg, apkRoot, apkName);
9224        // pkgSetting might be null during rescan following uninstall of updates
9225        // to a bundled app, so accommodate that possibility.  The settings in
9226        // that case will be established later from the parsed package.
9227        //
9228        // If the settings aren't null, sync them up with what we've just derived.
9229        // note that apkRoot isn't stored in the package settings.
9230        if (pkgSetting != null) {
9231            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9232            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9233        }
9234    }
9235
9236    /**
9237     * Deduces the ABI of a bundled app and sets the relevant fields on the
9238     * parsed pkg object.
9239     *
9240     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9241     *        under which system libraries are installed.
9242     * @param apkName the name of the installed package.
9243     */
9244    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9245        final File codeFile = new File(pkg.codePath);
9246
9247        final boolean has64BitLibs;
9248        final boolean has32BitLibs;
9249        if (isApkFile(codeFile)) {
9250            // Monolithic install
9251            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9252            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9253        } else {
9254            // Cluster install
9255            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9256            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9257                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9258                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9259                has64BitLibs = (new File(rootDir, isa)).exists();
9260            } else {
9261                has64BitLibs = false;
9262            }
9263            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9264                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9265                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9266                has32BitLibs = (new File(rootDir, isa)).exists();
9267            } else {
9268                has32BitLibs = false;
9269            }
9270        }
9271
9272        if (has64BitLibs && !has32BitLibs) {
9273            // The package has 64 bit libs, but not 32 bit libs. Its primary
9274            // ABI should be 64 bit. We can safely assume here that the bundled
9275            // native libraries correspond to the most preferred ABI in the list.
9276
9277            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9278            pkg.applicationInfo.secondaryCpuAbi = null;
9279        } else if (has32BitLibs && !has64BitLibs) {
9280            // The package has 32 bit libs but not 64 bit libs. Its primary
9281            // ABI should be 32 bit.
9282
9283            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9284            pkg.applicationInfo.secondaryCpuAbi = null;
9285        } else if (has32BitLibs && has64BitLibs) {
9286            // The application has both 64 and 32 bit bundled libraries. We check
9287            // here that the app declares multiArch support, and warn if it doesn't.
9288            //
9289            // We will be lenient here and record both ABIs. The primary will be the
9290            // ABI that's higher on the list, i.e, a device that's configured to prefer
9291            // 64 bit apps will see a 64 bit primary ABI,
9292
9293            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9294                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9295            }
9296
9297            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9298                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9299                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9300            } else {
9301                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9302                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9303            }
9304        } else {
9305            pkg.applicationInfo.primaryCpuAbi = null;
9306            pkg.applicationInfo.secondaryCpuAbi = null;
9307        }
9308    }
9309
9310    private void killApplication(String pkgName, int appId, String reason) {
9311        // Request the ActivityManager to kill the process(only for existing packages)
9312        // so that we do not end up in a confused state while the user is still using the older
9313        // version of the application while the new one gets installed.
9314        final long token = Binder.clearCallingIdentity();
9315        try {
9316            IActivityManager am = ActivityManagerNative.getDefault();
9317            if (am != null) {
9318                try {
9319                    am.killApplicationWithAppId(pkgName, appId, reason);
9320                } catch (RemoteException e) {
9321                }
9322            }
9323        } finally {
9324            Binder.restoreCallingIdentity(token);
9325        }
9326    }
9327
9328    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9329        // Remove the parent package setting
9330        PackageSetting ps = (PackageSetting) pkg.mExtras;
9331        if (ps != null) {
9332            removePackageLI(ps, chatty);
9333        }
9334        // Remove the child package setting
9335        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9336        for (int i = 0; i < childCount; i++) {
9337            PackageParser.Package childPkg = pkg.childPackages.get(i);
9338            ps = (PackageSetting) childPkg.mExtras;
9339            if (ps != null) {
9340                removePackageLI(ps, chatty);
9341            }
9342        }
9343    }
9344
9345    void removePackageLI(PackageSetting ps, boolean chatty) {
9346        if (DEBUG_INSTALL) {
9347            if (chatty)
9348                Log.d(TAG, "Removing package " + ps.name);
9349        }
9350
9351        // writer
9352        synchronized (mPackages) {
9353            mPackages.remove(ps.name);
9354            final PackageParser.Package pkg = ps.pkg;
9355            if (pkg != null) {
9356                cleanPackageDataStructuresLILPw(pkg, chatty);
9357            }
9358        }
9359    }
9360
9361    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9362        if (DEBUG_INSTALL) {
9363            if (chatty)
9364                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9365        }
9366
9367        // writer
9368        synchronized (mPackages) {
9369            // Remove the parent package
9370            mPackages.remove(pkg.applicationInfo.packageName);
9371            cleanPackageDataStructuresLILPw(pkg, chatty);
9372
9373            // Remove the child packages
9374            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9375            for (int i = 0; i < childCount; i++) {
9376                PackageParser.Package childPkg = pkg.childPackages.get(i);
9377                mPackages.remove(childPkg.applicationInfo.packageName);
9378                cleanPackageDataStructuresLILPw(childPkg, chatty);
9379            }
9380        }
9381    }
9382
9383    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9384        int N = pkg.providers.size();
9385        StringBuilder r = null;
9386        int i;
9387        for (i=0; i<N; i++) {
9388            PackageParser.Provider p = pkg.providers.get(i);
9389            mProviders.removeProvider(p);
9390            if (p.info.authority == null) {
9391
9392                /* There was another ContentProvider with this authority when
9393                 * this app was installed so this authority is null,
9394                 * Ignore it as we don't have to unregister the provider.
9395                 */
9396                continue;
9397            }
9398            String names[] = p.info.authority.split(";");
9399            for (int j = 0; j < names.length; j++) {
9400                if (mProvidersByAuthority.get(names[j]) == p) {
9401                    mProvidersByAuthority.remove(names[j]);
9402                    if (DEBUG_REMOVE) {
9403                        if (chatty)
9404                            Log.d(TAG, "Unregistered content provider: " + names[j]
9405                                    + ", className = " + p.info.name + ", isSyncable = "
9406                                    + p.info.isSyncable);
9407                    }
9408                }
9409            }
9410            if (DEBUG_REMOVE && chatty) {
9411                if (r == null) {
9412                    r = new StringBuilder(256);
9413                } else {
9414                    r.append(' ');
9415                }
9416                r.append(p.info.name);
9417            }
9418        }
9419        if (r != null) {
9420            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9421        }
9422
9423        N = pkg.services.size();
9424        r = null;
9425        for (i=0; i<N; i++) {
9426            PackageParser.Service s = pkg.services.get(i);
9427            mServices.removeService(s);
9428            if (chatty) {
9429                if (r == null) {
9430                    r = new StringBuilder(256);
9431                } else {
9432                    r.append(' ');
9433                }
9434                r.append(s.info.name);
9435            }
9436        }
9437        if (r != null) {
9438            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9439        }
9440
9441        N = pkg.receivers.size();
9442        r = null;
9443        for (i=0; i<N; i++) {
9444            PackageParser.Activity a = pkg.receivers.get(i);
9445            mReceivers.removeActivity(a, "receiver");
9446            if (DEBUG_REMOVE && chatty) {
9447                if (r == null) {
9448                    r = new StringBuilder(256);
9449                } else {
9450                    r.append(' ');
9451                }
9452                r.append(a.info.name);
9453            }
9454        }
9455        if (r != null) {
9456            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9457        }
9458
9459        N = pkg.activities.size();
9460        r = null;
9461        for (i=0; i<N; i++) {
9462            PackageParser.Activity a = pkg.activities.get(i);
9463            mActivities.removeActivity(a, "activity");
9464            if (DEBUG_REMOVE && chatty) {
9465                if (r == null) {
9466                    r = new StringBuilder(256);
9467                } else {
9468                    r.append(' ');
9469                }
9470                r.append(a.info.name);
9471            }
9472        }
9473        if (r != null) {
9474            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9475        }
9476
9477        N = pkg.permissions.size();
9478        r = null;
9479        for (i=0; i<N; i++) {
9480            PackageParser.Permission p = pkg.permissions.get(i);
9481            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9482            if (bp == null) {
9483                bp = mSettings.mPermissionTrees.get(p.info.name);
9484            }
9485            if (bp != null && bp.perm == p) {
9486                bp.perm = null;
9487                if (DEBUG_REMOVE && chatty) {
9488                    if (r == null) {
9489                        r = new StringBuilder(256);
9490                    } else {
9491                        r.append(' ');
9492                    }
9493                    r.append(p.info.name);
9494                }
9495            }
9496            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9497                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9498                if (appOpPkgs != null) {
9499                    appOpPkgs.remove(pkg.packageName);
9500                }
9501            }
9502        }
9503        if (r != null) {
9504            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9505        }
9506
9507        N = pkg.requestedPermissions.size();
9508        r = null;
9509        for (i=0; i<N; i++) {
9510            String perm = pkg.requestedPermissions.get(i);
9511            BasePermission bp = mSettings.mPermissions.get(perm);
9512            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9513                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9514                if (appOpPkgs != null) {
9515                    appOpPkgs.remove(pkg.packageName);
9516                    if (appOpPkgs.isEmpty()) {
9517                        mAppOpPermissionPackages.remove(perm);
9518                    }
9519                }
9520            }
9521        }
9522        if (r != null) {
9523            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9524        }
9525
9526        N = pkg.instrumentation.size();
9527        r = null;
9528        for (i=0; i<N; i++) {
9529            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9530            mInstrumentation.remove(a.getComponentName());
9531            if (DEBUG_REMOVE && chatty) {
9532                if (r == null) {
9533                    r = new StringBuilder(256);
9534                } else {
9535                    r.append(' ');
9536                }
9537                r.append(a.info.name);
9538            }
9539        }
9540        if (r != null) {
9541            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9542        }
9543
9544        r = null;
9545        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9546            // Only system apps can hold shared libraries.
9547            if (pkg.libraryNames != null) {
9548                for (i=0; i<pkg.libraryNames.size(); i++) {
9549                    String name = pkg.libraryNames.get(i);
9550                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9551                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9552                        mSharedLibraries.remove(name);
9553                        if (DEBUG_REMOVE && chatty) {
9554                            if (r == null) {
9555                                r = new StringBuilder(256);
9556                            } else {
9557                                r.append(' ');
9558                            }
9559                            r.append(name);
9560                        }
9561                    }
9562                }
9563            }
9564        }
9565        if (r != null) {
9566            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9567        }
9568    }
9569
9570    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9571        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9572            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9573                return true;
9574            }
9575        }
9576        return false;
9577    }
9578
9579    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9580    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9581    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9582
9583    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9584        // Update the parent permissions
9585        updatePermissionsLPw(pkg.packageName, pkg, flags);
9586        // Update the child permissions
9587        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9588        for (int i = 0; i < childCount; i++) {
9589            PackageParser.Package childPkg = pkg.childPackages.get(i);
9590            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9591        }
9592    }
9593
9594    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9595            int flags) {
9596        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9597        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9598    }
9599
9600    private void updatePermissionsLPw(String changingPkg,
9601            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9602        // Make sure there are no dangling permission trees.
9603        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9604        while (it.hasNext()) {
9605            final BasePermission bp = it.next();
9606            if (bp.packageSetting == null) {
9607                // We may not yet have parsed the package, so just see if
9608                // we still know about its settings.
9609                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9610            }
9611            if (bp.packageSetting == null) {
9612                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9613                        + " from package " + bp.sourcePackage);
9614                it.remove();
9615            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9616                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9617                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9618                            + " from package " + bp.sourcePackage);
9619                    flags |= UPDATE_PERMISSIONS_ALL;
9620                    it.remove();
9621                }
9622            }
9623        }
9624
9625        // Make sure all dynamic permissions have been assigned to a package,
9626        // and make sure there are no dangling permissions.
9627        it = mSettings.mPermissions.values().iterator();
9628        while (it.hasNext()) {
9629            final BasePermission bp = it.next();
9630            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9631                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9632                        + bp.name + " pkg=" + bp.sourcePackage
9633                        + " info=" + bp.pendingInfo);
9634                if (bp.packageSetting == null && bp.pendingInfo != null) {
9635                    final BasePermission tree = findPermissionTreeLP(bp.name);
9636                    if (tree != null && tree.perm != null) {
9637                        bp.packageSetting = tree.packageSetting;
9638                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9639                                new PermissionInfo(bp.pendingInfo));
9640                        bp.perm.info.packageName = tree.perm.info.packageName;
9641                        bp.perm.info.name = bp.name;
9642                        bp.uid = tree.uid;
9643                    }
9644                }
9645            }
9646            if (bp.packageSetting == null) {
9647                // We may not yet have parsed the package, so just see if
9648                // we still know about its settings.
9649                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9650            }
9651            if (bp.packageSetting == null) {
9652                Slog.w(TAG, "Removing dangling permission: " + bp.name
9653                        + " from package " + bp.sourcePackage);
9654                it.remove();
9655            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9656                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9657                    Slog.i(TAG, "Removing old permission: " + bp.name
9658                            + " from package " + bp.sourcePackage);
9659                    flags |= UPDATE_PERMISSIONS_ALL;
9660                    it.remove();
9661                }
9662            }
9663        }
9664
9665        // Now update the permissions for all packages, in particular
9666        // replace the granted permissions of the system packages.
9667        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9668            for (PackageParser.Package pkg : mPackages.values()) {
9669                if (pkg != pkgInfo) {
9670                    // Only replace for packages on requested volume
9671                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9672                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9673                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9674                    grantPermissionsLPw(pkg, replace, changingPkg);
9675                }
9676            }
9677        }
9678
9679        if (pkgInfo != null) {
9680            // Only replace for packages on requested volume
9681            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9682            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9683                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9684            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9685        }
9686    }
9687
9688    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9689            String packageOfInterest) {
9690        // IMPORTANT: There are two types of permissions: install and runtime.
9691        // Install time permissions are granted when the app is installed to
9692        // all device users and users added in the future. Runtime permissions
9693        // are granted at runtime explicitly to specific users. Normal and signature
9694        // protected permissions are install time permissions. Dangerous permissions
9695        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9696        // otherwise they are runtime permissions. This function does not manage
9697        // runtime permissions except for the case an app targeting Lollipop MR1
9698        // being upgraded to target a newer SDK, in which case dangerous permissions
9699        // are transformed from install time to runtime ones.
9700
9701        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9702        if (ps == null) {
9703            return;
9704        }
9705
9706        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9707
9708        PermissionsState permissionsState = ps.getPermissionsState();
9709        PermissionsState origPermissions = permissionsState;
9710
9711        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9712
9713        boolean runtimePermissionsRevoked = false;
9714        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9715
9716        boolean changedInstallPermission = false;
9717
9718        if (replace) {
9719            ps.installPermissionsFixed = false;
9720            if (!ps.isSharedUser()) {
9721                origPermissions = new PermissionsState(permissionsState);
9722                permissionsState.reset();
9723            } else {
9724                // We need to know only about runtime permission changes since the
9725                // calling code always writes the install permissions state but
9726                // the runtime ones are written only if changed. The only cases of
9727                // changed runtime permissions here are promotion of an install to
9728                // runtime and revocation of a runtime from a shared user.
9729                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9730                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9731                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9732                    runtimePermissionsRevoked = true;
9733                }
9734            }
9735        }
9736
9737        permissionsState.setGlobalGids(mGlobalGids);
9738
9739        final int N = pkg.requestedPermissions.size();
9740        for (int i=0; i<N; i++) {
9741            final String name = pkg.requestedPermissions.get(i);
9742            final BasePermission bp = mSettings.mPermissions.get(name);
9743
9744            if (DEBUG_INSTALL) {
9745                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9746            }
9747
9748            if (bp == null || bp.packageSetting == null) {
9749                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9750                    Slog.w(TAG, "Unknown permission " + name
9751                            + " in package " + pkg.packageName);
9752                }
9753                continue;
9754            }
9755
9756            final String perm = bp.name;
9757            boolean allowedSig = false;
9758            int grant = GRANT_DENIED;
9759
9760            // Keep track of app op permissions.
9761            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9762                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9763                if (pkgs == null) {
9764                    pkgs = new ArraySet<>();
9765                    mAppOpPermissionPackages.put(bp.name, pkgs);
9766                }
9767                pkgs.add(pkg.packageName);
9768            }
9769
9770            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9771            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9772                    >= Build.VERSION_CODES.M;
9773            switch (level) {
9774                case PermissionInfo.PROTECTION_NORMAL: {
9775                    // For all apps normal permissions are install time ones.
9776                    grant = GRANT_INSTALL;
9777                } break;
9778
9779                case PermissionInfo.PROTECTION_DANGEROUS: {
9780                    // If a permission review is required for legacy apps we represent
9781                    // their permissions as always granted runtime ones since we need
9782                    // to keep the review required permission flag per user while an
9783                    // install permission's state is shared across all users.
9784                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9785                        // For legacy apps dangerous permissions are install time ones.
9786                        grant = GRANT_INSTALL;
9787                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9788                        // For legacy apps that became modern, install becomes runtime.
9789                        grant = GRANT_UPGRADE;
9790                    } else if (mPromoteSystemApps
9791                            && isSystemApp(ps)
9792                            && mExistingSystemPackages.contains(ps.name)) {
9793                        // For legacy system apps, install becomes runtime.
9794                        // We cannot check hasInstallPermission() for system apps since those
9795                        // permissions were granted implicitly and not persisted pre-M.
9796                        grant = GRANT_UPGRADE;
9797                    } else {
9798                        // For modern apps keep runtime permissions unchanged.
9799                        grant = GRANT_RUNTIME;
9800                    }
9801                } break;
9802
9803                case PermissionInfo.PROTECTION_SIGNATURE: {
9804                    // For all apps signature permissions are install time ones.
9805                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9806                    if (allowedSig) {
9807                        grant = GRANT_INSTALL;
9808                    }
9809                } break;
9810            }
9811
9812            if (DEBUG_INSTALL) {
9813                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9814            }
9815
9816            if (grant != GRANT_DENIED) {
9817                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9818                    // If this is an existing, non-system package, then
9819                    // we can't add any new permissions to it.
9820                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9821                        // Except...  if this is a permission that was added
9822                        // to the platform (note: need to only do this when
9823                        // updating the platform).
9824                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9825                            grant = GRANT_DENIED;
9826                        }
9827                    }
9828                }
9829
9830                switch (grant) {
9831                    case GRANT_INSTALL: {
9832                        // Revoke this as runtime permission to handle the case of
9833                        // a runtime permission being downgraded to an install one.
9834                        // Also in permission review mode we keep dangerous permissions
9835                        // for legacy apps
9836                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9837                            if (origPermissions.getRuntimePermissionState(
9838                                    bp.name, userId) != null) {
9839                                // Revoke the runtime permission and clear the flags.
9840                                origPermissions.revokeRuntimePermission(bp, userId);
9841                                origPermissions.updatePermissionFlags(bp, userId,
9842                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9843                                // If we revoked a permission permission, we have to write.
9844                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9845                                        changedRuntimePermissionUserIds, userId);
9846                            }
9847                        }
9848                        // Grant an install permission.
9849                        if (permissionsState.grantInstallPermission(bp) !=
9850                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9851                            changedInstallPermission = true;
9852                        }
9853                    } break;
9854
9855                    case GRANT_RUNTIME: {
9856                        // Grant previously granted runtime permissions.
9857                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9858                            PermissionState permissionState = origPermissions
9859                                    .getRuntimePermissionState(bp.name, userId);
9860                            int flags = permissionState != null
9861                                    ? permissionState.getFlags() : 0;
9862                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9863                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9864                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9865                                    // If we cannot put the permission as it was, we have to write.
9866                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9867                                            changedRuntimePermissionUserIds, userId);
9868                                }
9869                                // If the app supports runtime permissions no need for a review.
9870                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9871                                        && appSupportsRuntimePermissions
9872                                        && (flags & PackageManager
9873                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9874                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9875                                    // Since we changed the flags, we have to write.
9876                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9877                                            changedRuntimePermissionUserIds, userId);
9878                                }
9879                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9880                                    && !appSupportsRuntimePermissions) {
9881                                // For legacy apps that need a permission review, every new
9882                                // runtime permission is granted but it is pending a review.
9883                                // We also need to review only platform defined runtime
9884                                // permissions as these are the only ones the platform knows
9885                                // how to disable the API to simulate revocation as legacy
9886                                // apps don't expect to run with revoked permissions.
9887                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9888                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9889                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9890                                        // We changed the flags, hence have to write.
9891                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9892                                                changedRuntimePermissionUserIds, userId);
9893                                    }
9894                                }
9895                                if (permissionsState.grantRuntimePermission(bp, userId)
9896                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9897                                    // We changed the permission, hence have to write.
9898                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9899                                            changedRuntimePermissionUserIds, userId);
9900                                }
9901                            }
9902                            // Propagate the permission flags.
9903                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9904                        }
9905                    } break;
9906
9907                    case GRANT_UPGRADE: {
9908                        // Grant runtime permissions for a previously held install permission.
9909                        PermissionState permissionState = origPermissions
9910                                .getInstallPermissionState(bp.name);
9911                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9912
9913                        if (origPermissions.revokeInstallPermission(bp)
9914                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9915                            // We will be transferring the permission flags, so clear them.
9916                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9917                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9918                            changedInstallPermission = true;
9919                        }
9920
9921                        // If the permission is not to be promoted to runtime we ignore it and
9922                        // also its other flags as they are not applicable to install permissions.
9923                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9924                            for (int userId : currentUserIds) {
9925                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9926                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9927                                    // Transfer the permission flags.
9928                                    permissionsState.updatePermissionFlags(bp, userId,
9929                                            flags, flags);
9930                                    // If we granted the permission, we have to write.
9931                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9932                                            changedRuntimePermissionUserIds, userId);
9933                                }
9934                            }
9935                        }
9936                    } break;
9937
9938                    default: {
9939                        if (packageOfInterest == null
9940                                || packageOfInterest.equals(pkg.packageName)) {
9941                            Slog.w(TAG, "Not granting permission " + perm
9942                                    + " to package " + pkg.packageName
9943                                    + " because it was previously installed without");
9944                        }
9945                    } break;
9946                }
9947            } else {
9948                if (permissionsState.revokeInstallPermission(bp) !=
9949                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9950                    // Also drop the permission flags.
9951                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9952                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9953                    changedInstallPermission = true;
9954                    Slog.i(TAG, "Un-granting permission " + perm
9955                            + " from package " + pkg.packageName
9956                            + " (protectionLevel=" + bp.protectionLevel
9957                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9958                            + ")");
9959                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9960                    // Don't print warning for app op permissions, since it is fine for them
9961                    // not to be granted, there is a UI for the user to decide.
9962                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9963                        Slog.w(TAG, "Not granting permission " + perm
9964                                + " to package " + pkg.packageName
9965                                + " (protectionLevel=" + bp.protectionLevel
9966                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9967                                + ")");
9968                    }
9969                }
9970            }
9971        }
9972
9973        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9974                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9975            // This is the first that we have heard about this package, so the
9976            // permissions we have now selected are fixed until explicitly
9977            // changed.
9978            ps.installPermissionsFixed = true;
9979        }
9980
9981        // Persist the runtime permissions state for users with changes. If permissions
9982        // were revoked because no app in the shared user declares them we have to
9983        // write synchronously to avoid losing runtime permissions state.
9984        for (int userId : changedRuntimePermissionUserIds) {
9985            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9986        }
9987
9988        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9989    }
9990
9991    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9992        boolean allowed = false;
9993        final int NP = PackageParser.NEW_PERMISSIONS.length;
9994        for (int ip=0; ip<NP; ip++) {
9995            final PackageParser.NewPermissionInfo npi
9996                    = PackageParser.NEW_PERMISSIONS[ip];
9997            if (npi.name.equals(perm)
9998                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9999                allowed = true;
10000                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10001                        + pkg.packageName);
10002                break;
10003            }
10004        }
10005        return allowed;
10006    }
10007
10008    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10009            BasePermission bp, PermissionsState origPermissions) {
10010        boolean allowed;
10011        allowed = (compareSignatures(
10012                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10013                        == PackageManager.SIGNATURE_MATCH)
10014                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10015                        == PackageManager.SIGNATURE_MATCH);
10016        if (!allowed && (bp.protectionLevel
10017                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10018            if (isSystemApp(pkg)) {
10019                // For updated system applications, a system permission
10020                // is granted only if it had been defined by the original application.
10021                if (pkg.isUpdatedSystemApp()) {
10022                    final PackageSetting sysPs = mSettings
10023                            .getDisabledSystemPkgLPr(pkg.packageName);
10024                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10025                        // If the original was granted this permission, we take
10026                        // that grant decision as read and propagate it to the
10027                        // update.
10028                        if (sysPs.isPrivileged()) {
10029                            allowed = true;
10030                        }
10031                    } else {
10032                        // The system apk may have been updated with an older
10033                        // version of the one on the data partition, but which
10034                        // granted a new system permission that it didn't have
10035                        // before.  In this case we do want to allow the app to
10036                        // now get the new permission if the ancestral apk is
10037                        // privileged to get it.
10038                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10039                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10040                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10041                                    allowed = true;
10042                                    break;
10043                                }
10044                            }
10045                        }
10046                        // Also if a privileged parent package on the system image or any of
10047                        // its children requested a privileged permission, the updated child
10048                        // packages can also get the permission.
10049                        if (pkg.parentPackage != null) {
10050                            final PackageSetting disabledSysParentPs = mSettings
10051                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10052                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10053                                    && disabledSysParentPs.isPrivileged()) {
10054                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10055                                    allowed = true;
10056                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10057                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10058                                    for (int i = 0; i < count; i++) {
10059                                        PackageParser.Package disabledSysChildPkg =
10060                                                disabledSysParentPs.pkg.childPackages.get(i);
10061                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10062                                                perm)) {
10063                                            allowed = true;
10064                                            break;
10065                                        }
10066                                    }
10067                                }
10068                            }
10069                        }
10070                    }
10071                } else {
10072                    allowed = isPrivilegedApp(pkg);
10073                }
10074            }
10075        }
10076        if (!allowed) {
10077            if (!allowed && (bp.protectionLevel
10078                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10079                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10080                // If this was a previously normal/dangerous permission that got moved
10081                // to a system permission as part of the runtime permission redesign, then
10082                // we still want to blindly grant it to old apps.
10083                allowed = true;
10084            }
10085            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10086                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10087                // If this permission is to be granted to the system installer and
10088                // this app is an installer, then it gets the permission.
10089                allowed = true;
10090            }
10091            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10092                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10093                // If this permission is to be granted to the system verifier and
10094                // this app is a verifier, then it gets the permission.
10095                allowed = true;
10096            }
10097            if (!allowed && (bp.protectionLevel
10098                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10099                    && isSystemApp(pkg)) {
10100                // Any pre-installed system app is allowed to get this permission.
10101                allowed = true;
10102            }
10103            if (!allowed && (bp.protectionLevel
10104                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10105                // For development permissions, a development permission
10106                // is granted only if it was already granted.
10107                allowed = origPermissions.hasInstallPermission(perm);
10108            }
10109            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10110                    && pkg.packageName.equals(mSetupWizardPackage)) {
10111                // If this permission is to be granted to the system setup wizard and
10112                // this app is a setup wizard, then it gets the permission.
10113                allowed = true;
10114            }
10115        }
10116        return allowed;
10117    }
10118
10119    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10120        final int permCount = pkg.requestedPermissions.size();
10121        for (int j = 0; j < permCount; j++) {
10122            String requestedPermission = pkg.requestedPermissions.get(j);
10123            if (permission.equals(requestedPermission)) {
10124                return true;
10125            }
10126        }
10127        return false;
10128    }
10129
10130    final class ActivityIntentResolver
10131            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10132        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10133                boolean defaultOnly, int userId) {
10134            if (!sUserManager.exists(userId)) return null;
10135            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10136            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10137        }
10138
10139        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10140                int userId) {
10141            if (!sUserManager.exists(userId)) return null;
10142            mFlags = flags;
10143            return super.queryIntent(intent, resolvedType,
10144                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10145        }
10146
10147        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10148                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10149            if (!sUserManager.exists(userId)) return null;
10150            if (packageActivities == null) {
10151                return null;
10152            }
10153            mFlags = flags;
10154            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10155            final int N = packageActivities.size();
10156            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10157                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10158
10159            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10160            for (int i = 0; i < N; ++i) {
10161                intentFilters = packageActivities.get(i).intents;
10162                if (intentFilters != null && intentFilters.size() > 0) {
10163                    PackageParser.ActivityIntentInfo[] array =
10164                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10165                    intentFilters.toArray(array);
10166                    listCut.add(array);
10167                }
10168            }
10169            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10170        }
10171
10172        /**
10173         * Finds a privileged activity that matches the specified activity names.
10174         */
10175        private PackageParser.Activity findMatchingActivity(
10176                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10177            for (PackageParser.Activity sysActivity : activityList) {
10178                if (sysActivity.info.name.equals(activityInfo.name)) {
10179                    return sysActivity;
10180                }
10181                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10182                    return sysActivity;
10183                }
10184                if (sysActivity.info.targetActivity != null) {
10185                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10186                        return sysActivity;
10187                    }
10188                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10189                        return sysActivity;
10190                    }
10191                }
10192            }
10193            return null;
10194        }
10195
10196        public class IterGenerator<E> {
10197            public Iterator<E> generate(ActivityIntentInfo info) {
10198                return null;
10199            }
10200        }
10201
10202        public class ActionIterGenerator extends IterGenerator<String> {
10203            @Override
10204            public Iterator<String> generate(ActivityIntentInfo info) {
10205                return info.actionsIterator();
10206            }
10207        }
10208
10209        public class CategoriesIterGenerator extends IterGenerator<String> {
10210            @Override
10211            public Iterator<String> generate(ActivityIntentInfo info) {
10212                return info.categoriesIterator();
10213            }
10214        }
10215
10216        public class SchemesIterGenerator extends IterGenerator<String> {
10217            @Override
10218            public Iterator<String> generate(ActivityIntentInfo info) {
10219                return info.schemesIterator();
10220            }
10221        }
10222
10223        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10224            @Override
10225            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10226                return info.authoritiesIterator();
10227            }
10228        }
10229
10230        /**
10231         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10232         * MODIFIED. Do not pass in a list that should not be changed.
10233         */
10234        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10235                IterGenerator<T> generator, Iterator<T> searchIterator) {
10236            // loop through the set of actions; every one must be found in the intent filter
10237            while (searchIterator.hasNext()) {
10238                // we must have at least one filter in the list to consider a match
10239                if (intentList.size() == 0) {
10240                    break;
10241                }
10242
10243                final T searchAction = searchIterator.next();
10244
10245                // loop through the set of intent filters
10246                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10247                while (intentIter.hasNext()) {
10248                    final ActivityIntentInfo intentInfo = intentIter.next();
10249                    boolean selectionFound = false;
10250
10251                    // loop through the intent filter's selection criteria; at least one
10252                    // of them must match the searched criteria
10253                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10254                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10255                        final T intentSelection = intentSelectionIter.next();
10256                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10257                            selectionFound = true;
10258                            break;
10259                        }
10260                    }
10261
10262                    // the selection criteria wasn't found in this filter's set; this filter
10263                    // is not a potential match
10264                    if (!selectionFound) {
10265                        intentIter.remove();
10266                    }
10267                }
10268            }
10269        }
10270
10271        private boolean isProtectedAction(ActivityIntentInfo filter) {
10272            final Iterator<String> actionsIter = filter.actionsIterator();
10273            while (actionsIter != null && actionsIter.hasNext()) {
10274                final String filterAction = actionsIter.next();
10275                if (PROTECTED_ACTIONS.contains(filterAction)) {
10276                    return true;
10277                }
10278            }
10279            return false;
10280        }
10281
10282        /**
10283         * Adjusts the priority of the given intent filter according to policy.
10284         * <p>
10285         * <ul>
10286         * <li>The priority for non privileged applications is capped to '0'</li>
10287         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10288         * <li>The priority for unbundled updates to privileged applications is capped to the
10289         *      priority defined on the system partition</li>
10290         * </ul>
10291         * <p>
10292         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10293         * allowed to obtain any priority on any action.
10294         */
10295        private void adjustPriority(
10296                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10297            // nothing to do; priority is fine as-is
10298            if (intent.getPriority() <= 0) {
10299                return;
10300            }
10301
10302            final ActivityInfo activityInfo = intent.activity.info;
10303            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10304
10305            final boolean privilegedApp =
10306                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10307            if (!privilegedApp) {
10308                // non-privileged applications can never define a priority >0
10309                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10310                        + " package: " + applicationInfo.packageName
10311                        + " activity: " + intent.activity.className
10312                        + " origPrio: " + intent.getPriority());
10313                intent.setPriority(0);
10314                return;
10315            }
10316
10317            if (systemActivities == null) {
10318                // the system package is not disabled; we're parsing the system partition
10319                if (isProtectedAction(intent)) {
10320                    if (mDeferProtectedFilters) {
10321                        // We can't deal with these just yet. No component should ever obtain a
10322                        // >0 priority for a protected actions, with ONE exception -- the setup
10323                        // wizard. The setup wizard, however, cannot be known until we're able to
10324                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10325                        // until all intent filters have been processed. Chicken, meet egg.
10326                        // Let the filter temporarily have a high priority and rectify the
10327                        // priorities after all system packages have been scanned.
10328                        mProtectedFilters.add(intent);
10329                        if (DEBUG_FILTERS) {
10330                            Slog.i(TAG, "Protected action; save for later;"
10331                                    + " package: " + applicationInfo.packageName
10332                                    + " activity: " + intent.activity.className
10333                                    + " origPrio: " + intent.getPriority());
10334                        }
10335                        return;
10336                    } else {
10337                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10338                            Slog.i(TAG, "No setup wizard;"
10339                                + " All protected intents capped to priority 0");
10340                        }
10341                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10342                            if (DEBUG_FILTERS) {
10343                                Slog.i(TAG, "Found setup wizard;"
10344                                    + " allow priority " + intent.getPriority() + ";"
10345                                    + " package: " + intent.activity.info.packageName
10346                                    + " activity: " + intent.activity.className
10347                                    + " priority: " + intent.getPriority());
10348                            }
10349                            // setup wizard gets whatever it wants
10350                            return;
10351                        }
10352                        Slog.w(TAG, "Protected action; cap priority to 0;"
10353                                + " package: " + intent.activity.info.packageName
10354                                + " activity: " + intent.activity.className
10355                                + " origPrio: " + intent.getPriority());
10356                        intent.setPriority(0);
10357                        return;
10358                    }
10359                }
10360                // privileged apps on the system image get whatever priority they request
10361                return;
10362            }
10363
10364            // privileged app unbundled update ... try to find the same activity
10365            final PackageParser.Activity foundActivity =
10366                    findMatchingActivity(systemActivities, activityInfo);
10367            if (foundActivity == null) {
10368                // this is a new activity; it cannot obtain >0 priority
10369                if (DEBUG_FILTERS) {
10370                    Slog.i(TAG, "New activity; cap priority to 0;"
10371                            + " package: " + applicationInfo.packageName
10372                            + " activity: " + intent.activity.className
10373                            + " origPrio: " + intent.getPriority());
10374                }
10375                intent.setPriority(0);
10376                return;
10377            }
10378
10379            // found activity, now check for filter equivalence
10380
10381            // a shallow copy is enough; we modify the list, not its contents
10382            final List<ActivityIntentInfo> intentListCopy =
10383                    new ArrayList<>(foundActivity.intents);
10384            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10385
10386            // find matching action subsets
10387            final Iterator<String> actionsIterator = intent.actionsIterator();
10388            if (actionsIterator != null) {
10389                getIntentListSubset(
10390                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10391                if (intentListCopy.size() == 0) {
10392                    // no more intents to match; we're not equivalent
10393                    if (DEBUG_FILTERS) {
10394                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10395                                + " package: " + applicationInfo.packageName
10396                                + " activity: " + intent.activity.className
10397                                + " origPrio: " + intent.getPriority());
10398                    }
10399                    intent.setPriority(0);
10400                    return;
10401                }
10402            }
10403
10404            // find matching category subsets
10405            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10406            if (categoriesIterator != null) {
10407                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10408                        categoriesIterator);
10409                if (intentListCopy.size() == 0) {
10410                    // no more intents to match; we're not equivalent
10411                    if (DEBUG_FILTERS) {
10412                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10413                                + " package: " + applicationInfo.packageName
10414                                + " activity: " + intent.activity.className
10415                                + " origPrio: " + intent.getPriority());
10416                    }
10417                    intent.setPriority(0);
10418                    return;
10419                }
10420            }
10421
10422            // find matching schemes subsets
10423            final Iterator<String> schemesIterator = intent.schemesIterator();
10424            if (schemesIterator != null) {
10425                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10426                        schemesIterator);
10427                if (intentListCopy.size() == 0) {
10428                    // no more intents to match; we're not equivalent
10429                    if (DEBUG_FILTERS) {
10430                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10431                                + " package: " + applicationInfo.packageName
10432                                + " activity: " + intent.activity.className
10433                                + " origPrio: " + intent.getPriority());
10434                    }
10435                    intent.setPriority(0);
10436                    return;
10437                }
10438            }
10439
10440            // find matching authorities subsets
10441            final Iterator<IntentFilter.AuthorityEntry>
10442                    authoritiesIterator = intent.authoritiesIterator();
10443            if (authoritiesIterator != null) {
10444                getIntentListSubset(intentListCopy,
10445                        new AuthoritiesIterGenerator(),
10446                        authoritiesIterator);
10447                if (intentListCopy.size() == 0) {
10448                    // no more intents to match; we're not equivalent
10449                    if (DEBUG_FILTERS) {
10450                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10451                                + " package: " + applicationInfo.packageName
10452                                + " activity: " + intent.activity.className
10453                                + " origPrio: " + intent.getPriority());
10454                    }
10455                    intent.setPriority(0);
10456                    return;
10457                }
10458            }
10459
10460            // we found matching filter(s); app gets the max priority of all intents
10461            int cappedPriority = 0;
10462            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10463                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10464            }
10465            if (intent.getPriority() > cappedPriority) {
10466                if (DEBUG_FILTERS) {
10467                    Slog.i(TAG, "Found matching filter(s);"
10468                            + " cap priority to " + cappedPriority + ";"
10469                            + " package: " + applicationInfo.packageName
10470                            + " activity: " + intent.activity.className
10471                            + " origPrio: " + intent.getPriority());
10472                }
10473                intent.setPriority(cappedPriority);
10474                return;
10475            }
10476            // all this for nothing; the requested priority was <= what was on the system
10477        }
10478
10479        public final void addActivity(PackageParser.Activity a, String type) {
10480            mActivities.put(a.getComponentName(), a);
10481            if (DEBUG_SHOW_INFO)
10482                Log.v(
10483                TAG, "  " + type + " " +
10484                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10485            if (DEBUG_SHOW_INFO)
10486                Log.v(TAG, "    Class=" + a.info.name);
10487            final int NI = a.intents.size();
10488            for (int j=0; j<NI; j++) {
10489                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10490                if ("activity".equals(type)) {
10491                    final PackageSetting ps =
10492                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10493                    final List<PackageParser.Activity> systemActivities =
10494                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10495                    adjustPriority(systemActivities, intent);
10496                }
10497                if (DEBUG_SHOW_INFO) {
10498                    Log.v(TAG, "    IntentFilter:");
10499                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10500                }
10501                if (!intent.debugCheck()) {
10502                    Log.w(TAG, "==> For Activity " + a.info.name);
10503                }
10504                addFilter(intent);
10505            }
10506        }
10507
10508        public final void removeActivity(PackageParser.Activity a, String type) {
10509            mActivities.remove(a.getComponentName());
10510            if (DEBUG_SHOW_INFO) {
10511                Log.v(TAG, "  " + type + " "
10512                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10513                                : a.info.name) + ":");
10514                Log.v(TAG, "    Class=" + a.info.name);
10515            }
10516            final int NI = a.intents.size();
10517            for (int j=0; j<NI; j++) {
10518                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10519                if (DEBUG_SHOW_INFO) {
10520                    Log.v(TAG, "    IntentFilter:");
10521                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10522                }
10523                removeFilter(intent);
10524            }
10525        }
10526
10527        @Override
10528        protected boolean allowFilterResult(
10529                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10530            ActivityInfo filterAi = filter.activity.info;
10531            for (int i=dest.size()-1; i>=0; i--) {
10532                ActivityInfo destAi = dest.get(i).activityInfo;
10533                if (destAi.name == filterAi.name
10534                        && destAi.packageName == filterAi.packageName) {
10535                    return false;
10536                }
10537            }
10538            return true;
10539        }
10540
10541        @Override
10542        protected ActivityIntentInfo[] newArray(int size) {
10543            return new ActivityIntentInfo[size];
10544        }
10545
10546        @Override
10547        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10548            if (!sUserManager.exists(userId)) return true;
10549            PackageParser.Package p = filter.activity.owner;
10550            if (p != null) {
10551                PackageSetting ps = (PackageSetting)p.mExtras;
10552                if (ps != null) {
10553                    // System apps are never considered stopped for purposes of
10554                    // filtering, because there may be no way for the user to
10555                    // actually re-launch them.
10556                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10557                            && ps.getStopped(userId);
10558                }
10559            }
10560            return false;
10561        }
10562
10563        @Override
10564        protected boolean isPackageForFilter(String packageName,
10565                PackageParser.ActivityIntentInfo info) {
10566            return packageName.equals(info.activity.owner.packageName);
10567        }
10568
10569        @Override
10570        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10571                int match, int userId) {
10572            if (!sUserManager.exists(userId)) return null;
10573            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10574                return null;
10575            }
10576            final PackageParser.Activity activity = info.activity;
10577            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10578            if (ps == null) {
10579                return null;
10580            }
10581            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10582                    ps.readUserState(userId), userId);
10583            if (ai == null) {
10584                return null;
10585            }
10586            final ResolveInfo res = new ResolveInfo();
10587            res.activityInfo = ai;
10588            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10589                res.filter = info;
10590            }
10591            if (info != null) {
10592                res.handleAllWebDataURI = info.handleAllWebDataURI();
10593            }
10594            res.priority = info.getPriority();
10595            res.preferredOrder = activity.owner.mPreferredOrder;
10596            //System.out.println("Result: " + res.activityInfo.className +
10597            //                   " = " + res.priority);
10598            res.match = match;
10599            res.isDefault = info.hasDefault;
10600            res.labelRes = info.labelRes;
10601            res.nonLocalizedLabel = info.nonLocalizedLabel;
10602            if (userNeedsBadging(userId)) {
10603                res.noResourceId = true;
10604            } else {
10605                res.icon = info.icon;
10606            }
10607            res.iconResourceId = info.icon;
10608            res.system = res.activityInfo.applicationInfo.isSystemApp();
10609            return res;
10610        }
10611
10612        @Override
10613        protected void sortResults(List<ResolveInfo> results) {
10614            Collections.sort(results, mResolvePrioritySorter);
10615        }
10616
10617        @Override
10618        protected void dumpFilter(PrintWriter out, String prefix,
10619                PackageParser.ActivityIntentInfo filter) {
10620            out.print(prefix); out.print(
10621                    Integer.toHexString(System.identityHashCode(filter.activity)));
10622                    out.print(' ');
10623                    filter.activity.printComponentShortName(out);
10624                    out.print(" filter ");
10625                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10626        }
10627
10628        @Override
10629        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10630            return filter.activity;
10631        }
10632
10633        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10634            PackageParser.Activity activity = (PackageParser.Activity)label;
10635            out.print(prefix); out.print(
10636                    Integer.toHexString(System.identityHashCode(activity)));
10637                    out.print(' ');
10638                    activity.printComponentShortName(out);
10639            if (count > 1) {
10640                out.print(" ("); out.print(count); out.print(" filters)");
10641            }
10642            out.println();
10643        }
10644
10645        // Keys are String (activity class name), values are Activity.
10646        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10647                = new ArrayMap<ComponentName, PackageParser.Activity>();
10648        private int mFlags;
10649    }
10650
10651    private final class ServiceIntentResolver
10652            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10653        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10654                boolean defaultOnly, int userId) {
10655            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10656            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10657        }
10658
10659        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10660                int userId) {
10661            if (!sUserManager.exists(userId)) return null;
10662            mFlags = flags;
10663            return super.queryIntent(intent, resolvedType,
10664                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10665        }
10666
10667        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10668                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10669            if (!sUserManager.exists(userId)) return null;
10670            if (packageServices == null) {
10671                return null;
10672            }
10673            mFlags = flags;
10674            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10675            final int N = packageServices.size();
10676            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10677                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10678
10679            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10680            for (int i = 0; i < N; ++i) {
10681                intentFilters = packageServices.get(i).intents;
10682                if (intentFilters != null && intentFilters.size() > 0) {
10683                    PackageParser.ServiceIntentInfo[] array =
10684                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10685                    intentFilters.toArray(array);
10686                    listCut.add(array);
10687                }
10688            }
10689            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10690        }
10691
10692        public final void addService(PackageParser.Service s) {
10693            mServices.put(s.getComponentName(), s);
10694            if (DEBUG_SHOW_INFO) {
10695                Log.v(TAG, "  "
10696                        + (s.info.nonLocalizedLabel != null
10697                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10698                Log.v(TAG, "    Class=" + s.info.name);
10699            }
10700            final int NI = s.intents.size();
10701            int j;
10702            for (j=0; j<NI; j++) {
10703                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10704                if (DEBUG_SHOW_INFO) {
10705                    Log.v(TAG, "    IntentFilter:");
10706                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10707                }
10708                if (!intent.debugCheck()) {
10709                    Log.w(TAG, "==> For Service " + s.info.name);
10710                }
10711                addFilter(intent);
10712            }
10713        }
10714
10715        public final void removeService(PackageParser.Service s) {
10716            mServices.remove(s.getComponentName());
10717            if (DEBUG_SHOW_INFO) {
10718                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10719                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10720                Log.v(TAG, "    Class=" + s.info.name);
10721            }
10722            final int NI = s.intents.size();
10723            int j;
10724            for (j=0; j<NI; j++) {
10725                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10726                if (DEBUG_SHOW_INFO) {
10727                    Log.v(TAG, "    IntentFilter:");
10728                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10729                }
10730                removeFilter(intent);
10731            }
10732        }
10733
10734        @Override
10735        protected boolean allowFilterResult(
10736                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10737            ServiceInfo filterSi = filter.service.info;
10738            for (int i=dest.size()-1; i>=0; i--) {
10739                ServiceInfo destAi = dest.get(i).serviceInfo;
10740                if (destAi.name == filterSi.name
10741                        && destAi.packageName == filterSi.packageName) {
10742                    return false;
10743                }
10744            }
10745            return true;
10746        }
10747
10748        @Override
10749        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10750            return new PackageParser.ServiceIntentInfo[size];
10751        }
10752
10753        @Override
10754        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10755            if (!sUserManager.exists(userId)) return true;
10756            PackageParser.Package p = filter.service.owner;
10757            if (p != null) {
10758                PackageSetting ps = (PackageSetting)p.mExtras;
10759                if (ps != null) {
10760                    // System apps are never considered stopped for purposes of
10761                    // filtering, because there may be no way for the user to
10762                    // actually re-launch them.
10763                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10764                            && ps.getStopped(userId);
10765                }
10766            }
10767            return false;
10768        }
10769
10770        @Override
10771        protected boolean isPackageForFilter(String packageName,
10772                PackageParser.ServiceIntentInfo info) {
10773            return packageName.equals(info.service.owner.packageName);
10774        }
10775
10776        @Override
10777        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10778                int match, int userId) {
10779            if (!sUserManager.exists(userId)) return null;
10780            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10781            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10782                return null;
10783            }
10784            final PackageParser.Service service = info.service;
10785            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10786            if (ps == null) {
10787                return null;
10788            }
10789            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10790                    ps.readUserState(userId), userId);
10791            if (si == null) {
10792                return null;
10793            }
10794            final ResolveInfo res = new ResolveInfo();
10795            res.serviceInfo = si;
10796            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10797                res.filter = filter;
10798            }
10799            res.priority = info.getPriority();
10800            res.preferredOrder = service.owner.mPreferredOrder;
10801            res.match = match;
10802            res.isDefault = info.hasDefault;
10803            res.labelRes = info.labelRes;
10804            res.nonLocalizedLabel = info.nonLocalizedLabel;
10805            res.icon = info.icon;
10806            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10807            return res;
10808        }
10809
10810        @Override
10811        protected void sortResults(List<ResolveInfo> results) {
10812            Collections.sort(results, mResolvePrioritySorter);
10813        }
10814
10815        @Override
10816        protected void dumpFilter(PrintWriter out, String prefix,
10817                PackageParser.ServiceIntentInfo filter) {
10818            out.print(prefix); out.print(
10819                    Integer.toHexString(System.identityHashCode(filter.service)));
10820                    out.print(' ');
10821                    filter.service.printComponentShortName(out);
10822                    out.print(" filter ");
10823                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10824        }
10825
10826        @Override
10827        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10828            return filter.service;
10829        }
10830
10831        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10832            PackageParser.Service service = (PackageParser.Service)label;
10833            out.print(prefix); out.print(
10834                    Integer.toHexString(System.identityHashCode(service)));
10835                    out.print(' ');
10836                    service.printComponentShortName(out);
10837            if (count > 1) {
10838                out.print(" ("); out.print(count); out.print(" filters)");
10839            }
10840            out.println();
10841        }
10842
10843//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10844//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10845//            final List<ResolveInfo> retList = Lists.newArrayList();
10846//            while (i.hasNext()) {
10847//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10848//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10849//                    retList.add(resolveInfo);
10850//                }
10851//            }
10852//            return retList;
10853//        }
10854
10855        // Keys are String (activity class name), values are Activity.
10856        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10857                = new ArrayMap<ComponentName, PackageParser.Service>();
10858        private int mFlags;
10859    };
10860
10861    private final class ProviderIntentResolver
10862            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10863        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10864                boolean defaultOnly, int userId) {
10865            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10866            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10867        }
10868
10869        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10870                int userId) {
10871            if (!sUserManager.exists(userId))
10872                return null;
10873            mFlags = flags;
10874            return super.queryIntent(intent, resolvedType,
10875                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10876        }
10877
10878        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10879                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10880            if (!sUserManager.exists(userId))
10881                return null;
10882            if (packageProviders == null) {
10883                return null;
10884            }
10885            mFlags = flags;
10886            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10887            final int N = packageProviders.size();
10888            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10889                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10890
10891            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10892            for (int i = 0; i < N; ++i) {
10893                intentFilters = packageProviders.get(i).intents;
10894                if (intentFilters != null && intentFilters.size() > 0) {
10895                    PackageParser.ProviderIntentInfo[] array =
10896                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10897                    intentFilters.toArray(array);
10898                    listCut.add(array);
10899                }
10900            }
10901            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10902        }
10903
10904        public final void addProvider(PackageParser.Provider p) {
10905            if (mProviders.containsKey(p.getComponentName())) {
10906                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10907                return;
10908            }
10909
10910            mProviders.put(p.getComponentName(), p);
10911            if (DEBUG_SHOW_INFO) {
10912                Log.v(TAG, "  "
10913                        + (p.info.nonLocalizedLabel != null
10914                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10915                Log.v(TAG, "    Class=" + p.info.name);
10916            }
10917            final int NI = p.intents.size();
10918            int j;
10919            for (j = 0; j < NI; j++) {
10920                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10921                if (DEBUG_SHOW_INFO) {
10922                    Log.v(TAG, "    IntentFilter:");
10923                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10924                }
10925                if (!intent.debugCheck()) {
10926                    Log.w(TAG, "==> For Provider " + p.info.name);
10927                }
10928                addFilter(intent);
10929            }
10930        }
10931
10932        public final void removeProvider(PackageParser.Provider p) {
10933            mProviders.remove(p.getComponentName());
10934            if (DEBUG_SHOW_INFO) {
10935                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10936                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10937                Log.v(TAG, "    Class=" + p.info.name);
10938            }
10939            final int NI = p.intents.size();
10940            int j;
10941            for (j = 0; j < NI; j++) {
10942                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10943                if (DEBUG_SHOW_INFO) {
10944                    Log.v(TAG, "    IntentFilter:");
10945                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10946                }
10947                removeFilter(intent);
10948            }
10949        }
10950
10951        @Override
10952        protected boolean allowFilterResult(
10953                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10954            ProviderInfo filterPi = filter.provider.info;
10955            for (int i = dest.size() - 1; i >= 0; i--) {
10956                ProviderInfo destPi = dest.get(i).providerInfo;
10957                if (destPi.name == filterPi.name
10958                        && destPi.packageName == filterPi.packageName) {
10959                    return false;
10960                }
10961            }
10962            return true;
10963        }
10964
10965        @Override
10966        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10967            return new PackageParser.ProviderIntentInfo[size];
10968        }
10969
10970        @Override
10971        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10972            if (!sUserManager.exists(userId))
10973                return true;
10974            PackageParser.Package p = filter.provider.owner;
10975            if (p != null) {
10976                PackageSetting ps = (PackageSetting) p.mExtras;
10977                if (ps != null) {
10978                    // System apps are never considered stopped for purposes of
10979                    // filtering, because there may be no way for the user to
10980                    // actually re-launch them.
10981                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10982                            && ps.getStopped(userId);
10983                }
10984            }
10985            return false;
10986        }
10987
10988        @Override
10989        protected boolean isPackageForFilter(String packageName,
10990                PackageParser.ProviderIntentInfo info) {
10991            return packageName.equals(info.provider.owner.packageName);
10992        }
10993
10994        @Override
10995        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10996                int match, int userId) {
10997            if (!sUserManager.exists(userId))
10998                return null;
10999            final PackageParser.ProviderIntentInfo info = filter;
11000            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11001                return null;
11002            }
11003            final PackageParser.Provider provider = info.provider;
11004            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11005            if (ps == null) {
11006                return null;
11007            }
11008            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11009                    ps.readUserState(userId), userId);
11010            if (pi == null) {
11011                return null;
11012            }
11013            final ResolveInfo res = new ResolveInfo();
11014            res.providerInfo = pi;
11015            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11016                res.filter = filter;
11017            }
11018            res.priority = info.getPriority();
11019            res.preferredOrder = provider.owner.mPreferredOrder;
11020            res.match = match;
11021            res.isDefault = info.hasDefault;
11022            res.labelRes = info.labelRes;
11023            res.nonLocalizedLabel = info.nonLocalizedLabel;
11024            res.icon = info.icon;
11025            res.system = res.providerInfo.applicationInfo.isSystemApp();
11026            return res;
11027        }
11028
11029        @Override
11030        protected void sortResults(List<ResolveInfo> results) {
11031            Collections.sort(results, mResolvePrioritySorter);
11032        }
11033
11034        @Override
11035        protected void dumpFilter(PrintWriter out, String prefix,
11036                PackageParser.ProviderIntentInfo filter) {
11037            out.print(prefix);
11038            out.print(
11039                    Integer.toHexString(System.identityHashCode(filter.provider)));
11040            out.print(' ');
11041            filter.provider.printComponentShortName(out);
11042            out.print(" filter ");
11043            out.println(Integer.toHexString(System.identityHashCode(filter)));
11044        }
11045
11046        @Override
11047        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11048            return filter.provider;
11049        }
11050
11051        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11052            PackageParser.Provider provider = (PackageParser.Provider)label;
11053            out.print(prefix); out.print(
11054                    Integer.toHexString(System.identityHashCode(provider)));
11055                    out.print(' ');
11056                    provider.printComponentShortName(out);
11057            if (count > 1) {
11058                out.print(" ("); out.print(count); out.print(" filters)");
11059            }
11060            out.println();
11061        }
11062
11063        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11064                = new ArrayMap<ComponentName, PackageParser.Provider>();
11065        private int mFlags;
11066    }
11067
11068    private static final class EphemeralIntentResolver
11069            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11070        @Override
11071        protected EphemeralResolveIntentInfo[] newArray(int size) {
11072            return new EphemeralResolveIntentInfo[size];
11073        }
11074
11075        @Override
11076        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11077            return true;
11078        }
11079
11080        @Override
11081        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11082                int userId) {
11083            if (!sUserManager.exists(userId)) {
11084                return null;
11085            }
11086            return info.getEphemeralResolveInfo();
11087        }
11088    }
11089
11090    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11091            new Comparator<ResolveInfo>() {
11092        public int compare(ResolveInfo r1, ResolveInfo r2) {
11093            int v1 = r1.priority;
11094            int v2 = r2.priority;
11095            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11096            if (v1 != v2) {
11097                return (v1 > v2) ? -1 : 1;
11098            }
11099            v1 = r1.preferredOrder;
11100            v2 = r2.preferredOrder;
11101            if (v1 != v2) {
11102                return (v1 > v2) ? -1 : 1;
11103            }
11104            if (r1.isDefault != r2.isDefault) {
11105                return r1.isDefault ? -1 : 1;
11106            }
11107            v1 = r1.match;
11108            v2 = r2.match;
11109            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11110            if (v1 != v2) {
11111                return (v1 > v2) ? -1 : 1;
11112            }
11113            if (r1.system != r2.system) {
11114                return r1.system ? -1 : 1;
11115            }
11116            if (r1.activityInfo != null) {
11117                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11118            }
11119            if (r1.serviceInfo != null) {
11120                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11121            }
11122            if (r1.providerInfo != null) {
11123                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11124            }
11125            return 0;
11126        }
11127    };
11128
11129    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11130            new Comparator<ProviderInfo>() {
11131        public int compare(ProviderInfo p1, ProviderInfo p2) {
11132            final int v1 = p1.initOrder;
11133            final int v2 = p2.initOrder;
11134            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11135        }
11136    };
11137
11138    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11139            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11140            final int[] userIds) {
11141        mHandler.post(new Runnable() {
11142            @Override
11143            public void run() {
11144                try {
11145                    final IActivityManager am = ActivityManagerNative.getDefault();
11146                    if (am == null) return;
11147                    final int[] resolvedUserIds;
11148                    if (userIds == null) {
11149                        resolvedUserIds = am.getRunningUserIds();
11150                    } else {
11151                        resolvedUserIds = userIds;
11152                    }
11153                    for (int id : resolvedUserIds) {
11154                        final Intent intent = new Intent(action,
11155                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11156                        if (extras != null) {
11157                            intent.putExtras(extras);
11158                        }
11159                        if (targetPkg != null) {
11160                            intent.setPackage(targetPkg);
11161                        }
11162                        // Modify the UID when posting to other users
11163                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11164                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11165                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11166                            intent.putExtra(Intent.EXTRA_UID, uid);
11167                        }
11168                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11169                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11170                        if (DEBUG_BROADCASTS) {
11171                            RuntimeException here = new RuntimeException("here");
11172                            here.fillInStackTrace();
11173                            Slog.d(TAG, "Sending to user " + id + ": "
11174                                    + intent.toShortString(false, true, false, false)
11175                                    + " " + intent.getExtras(), here);
11176                        }
11177                        am.broadcastIntent(null, intent, null, finishedReceiver,
11178                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11179                                null, finishedReceiver != null, false, id);
11180                    }
11181                } catch (RemoteException ex) {
11182                }
11183            }
11184        });
11185    }
11186
11187    /**
11188     * Check if the external storage media is available. This is true if there
11189     * is a mounted external storage medium or if the external storage is
11190     * emulated.
11191     */
11192    private boolean isExternalMediaAvailable() {
11193        return mMediaMounted || Environment.isExternalStorageEmulated();
11194    }
11195
11196    @Override
11197    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11198        // writer
11199        synchronized (mPackages) {
11200            if (!isExternalMediaAvailable()) {
11201                // If the external storage is no longer mounted at this point,
11202                // the caller may not have been able to delete all of this
11203                // packages files and can not delete any more.  Bail.
11204                return null;
11205            }
11206            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11207            if (lastPackage != null) {
11208                pkgs.remove(lastPackage);
11209            }
11210            if (pkgs.size() > 0) {
11211                return pkgs.get(0);
11212            }
11213        }
11214        return null;
11215    }
11216
11217    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11218        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11219                userId, andCode ? 1 : 0, packageName);
11220        if (mSystemReady) {
11221            msg.sendToTarget();
11222        } else {
11223            if (mPostSystemReadyMessages == null) {
11224                mPostSystemReadyMessages = new ArrayList<>();
11225            }
11226            mPostSystemReadyMessages.add(msg);
11227        }
11228    }
11229
11230    void startCleaningPackages() {
11231        // reader
11232        if (!isExternalMediaAvailable()) {
11233            return;
11234        }
11235        synchronized (mPackages) {
11236            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11237                return;
11238            }
11239        }
11240        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11241        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11242        IActivityManager am = ActivityManagerNative.getDefault();
11243        if (am != null) {
11244            try {
11245                am.startService(null, intent, null, mContext.getOpPackageName(),
11246                        UserHandle.USER_SYSTEM);
11247            } catch (RemoteException e) {
11248            }
11249        }
11250    }
11251
11252    @Override
11253    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11254            int installFlags, String installerPackageName, int userId) {
11255        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11256
11257        final int callingUid = Binder.getCallingUid();
11258        enforceCrossUserPermission(callingUid, userId,
11259                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11260
11261        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11262            try {
11263                if (observer != null) {
11264                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11265                }
11266            } catch (RemoteException re) {
11267            }
11268            return;
11269        }
11270
11271        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11272            installFlags |= PackageManager.INSTALL_FROM_ADB;
11273
11274        } else {
11275            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11276            // about installerPackageName.
11277
11278            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11279            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11280        }
11281
11282        UserHandle user;
11283        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11284            user = UserHandle.ALL;
11285        } else {
11286            user = new UserHandle(userId);
11287        }
11288
11289        // Only system components can circumvent runtime permissions when installing.
11290        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11291                && mContext.checkCallingOrSelfPermission(Manifest.permission
11292                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11293            throw new SecurityException("You need the "
11294                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11295                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11296        }
11297
11298        final File originFile = new File(originPath);
11299        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11300
11301        final Message msg = mHandler.obtainMessage(INIT_COPY);
11302        final VerificationInfo verificationInfo = new VerificationInfo(
11303                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11304        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11305                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11306                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11307                null /*certificates*/);
11308        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11309        msg.obj = params;
11310
11311        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11312                System.identityHashCode(msg.obj));
11313        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11314                System.identityHashCode(msg.obj));
11315
11316        mHandler.sendMessage(msg);
11317    }
11318
11319    void installStage(String packageName, File stagedDir, String stagedCid,
11320            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11321            String installerPackageName, int installerUid, UserHandle user,
11322            Certificate[][] certificates) {
11323        if (DEBUG_EPHEMERAL) {
11324            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11325                Slog.d(TAG, "Ephemeral install of " + packageName);
11326            }
11327        }
11328        final VerificationInfo verificationInfo = new VerificationInfo(
11329                sessionParams.originatingUri, sessionParams.referrerUri,
11330                sessionParams.originatingUid, installerUid);
11331
11332        final OriginInfo origin;
11333        if (stagedDir != null) {
11334            origin = OriginInfo.fromStagedFile(stagedDir);
11335        } else {
11336            origin = OriginInfo.fromStagedContainer(stagedCid);
11337        }
11338
11339        final Message msg = mHandler.obtainMessage(INIT_COPY);
11340        final InstallParams params = new InstallParams(origin, null, observer,
11341                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11342                verificationInfo, user, sessionParams.abiOverride,
11343                sessionParams.grantedRuntimePermissions, certificates);
11344        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11345        msg.obj = params;
11346
11347        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11348                System.identityHashCode(msg.obj));
11349        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11350                System.identityHashCode(msg.obj));
11351
11352        mHandler.sendMessage(msg);
11353    }
11354
11355    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11356            int userId) {
11357        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11358        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11359    }
11360
11361    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11362            int appId, int userId) {
11363        Bundle extras = new Bundle(1);
11364        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11365
11366        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11367                packageName, extras, 0, null, null, new int[] {userId});
11368        try {
11369            IActivityManager am = ActivityManagerNative.getDefault();
11370            if (isSystem && am.isUserRunning(userId, 0)) {
11371                // The just-installed/enabled app is bundled on the system, so presumed
11372                // to be able to run automatically without needing an explicit launch.
11373                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11374                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11375                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11376                        .setPackage(packageName);
11377                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11378                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11379            }
11380        } catch (RemoteException e) {
11381            // shouldn't happen
11382            Slog.w(TAG, "Unable to bootstrap installed package", e);
11383        }
11384    }
11385
11386    @Override
11387    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11388            int userId) {
11389        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11390        PackageSetting pkgSetting;
11391        final int uid = Binder.getCallingUid();
11392        enforceCrossUserPermission(uid, userId,
11393                true /* requireFullPermission */, true /* checkShell */,
11394                "setApplicationHiddenSetting for user " + userId);
11395
11396        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11397            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11398            return false;
11399        }
11400
11401        long callingId = Binder.clearCallingIdentity();
11402        try {
11403            boolean sendAdded = false;
11404            boolean sendRemoved = false;
11405            // writer
11406            synchronized (mPackages) {
11407                pkgSetting = mSettings.mPackages.get(packageName);
11408                if (pkgSetting == null) {
11409                    return false;
11410                }
11411                if (pkgSetting.getHidden(userId) != hidden) {
11412                    pkgSetting.setHidden(hidden, userId);
11413                    mSettings.writePackageRestrictionsLPr(userId);
11414                    if (hidden) {
11415                        sendRemoved = true;
11416                    } else {
11417                        sendAdded = true;
11418                    }
11419                }
11420            }
11421            if (sendAdded) {
11422                sendPackageAddedForUser(packageName, pkgSetting, userId);
11423                return true;
11424            }
11425            if (sendRemoved) {
11426                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11427                        "hiding pkg");
11428                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11429                return true;
11430            }
11431        } finally {
11432            Binder.restoreCallingIdentity(callingId);
11433        }
11434        return false;
11435    }
11436
11437    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11438            int userId) {
11439        final PackageRemovedInfo info = new PackageRemovedInfo();
11440        info.removedPackage = packageName;
11441        info.removedUsers = new int[] {userId};
11442        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11443        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11444    }
11445
11446    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11447        if (pkgList.length > 0) {
11448            Bundle extras = new Bundle(1);
11449            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11450
11451            sendPackageBroadcast(
11452                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11453                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11454                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11455                    new int[] {userId});
11456        }
11457    }
11458
11459    /**
11460     * Returns true if application is not found or there was an error. Otherwise it returns
11461     * the hidden state of the package for the given user.
11462     */
11463    @Override
11464    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11465        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11466        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11467                true /* requireFullPermission */, false /* checkShell */,
11468                "getApplicationHidden for user " + userId);
11469        PackageSetting pkgSetting;
11470        long callingId = Binder.clearCallingIdentity();
11471        try {
11472            // writer
11473            synchronized (mPackages) {
11474                pkgSetting = mSettings.mPackages.get(packageName);
11475                if (pkgSetting == null) {
11476                    return true;
11477                }
11478                return pkgSetting.getHidden(userId);
11479            }
11480        } finally {
11481            Binder.restoreCallingIdentity(callingId);
11482        }
11483    }
11484
11485    /**
11486     * @hide
11487     */
11488    @Override
11489    public int installExistingPackageAsUser(String packageName, int userId) {
11490        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11491                null);
11492        PackageSetting pkgSetting;
11493        final int uid = Binder.getCallingUid();
11494        enforceCrossUserPermission(uid, userId,
11495                true /* requireFullPermission */, true /* checkShell */,
11496                "installExistingPackage for user " + userId);
11497        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11498            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11499        }
11500
11501        long callingId = Binder.clearCallingIdentity();
11502        try {
11503            boolean installed = false;
11504
11505            // writer
11506            synchronized (mPackages) {
11507                pkgSetting = mSettings.mPackages.get(packageName);
11508                if (pkgSetting == null) {
11509                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11510                }
11511                if (!pkgSetting.getInstalled(userId)) {
11512                    pkgSetting.setInstalled(true, userId);
11513                    pkgSetting.setHidden(false, userId);
11514                    mSettings.writePackageRestrictionsLPr(userId);
11515                    installed = true;
11516                }
11517            }
11518
11519            if (installed) {
11520                if (pkgSetting.pkg != null) {
11521                    synchronized (mInstallLock) {
11522                        // We don't need to freeze for a brand new install
11523                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11524                    }
11525                }
11526                sendPackageAddedForUser(packageName, pkgSetting, userId);
11527            }
11528        } finally {
11529            Binder.restoreCallingIdentity(callingId);
11530        }
11531
11532        return PackageManager.INSTALL_SUCCEEDED;
11533    }
11534
11535    boolean isUserRestricted(int userId, String restrictionKey) {
11536        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11537        if (restrictions.getBoolean(restrictionKey, false)) {
11538            Log.w(TAG, "User is restricted: " + restrictionKey);
11539            return true;
11540        }
11541        return false;
11542    }
11543
11544    @Override
11545    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11546            int userId) {
11547        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11548        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11549                true /* requireFullPermission */, true /* checkShell */,
11550                "setPackagesSuspended for user " + userId);
11551
11552        if (ArrayUtils.isEmpty(packageNames)) {
11553            return packageNames;
11554        }
11555
11556        // List of package names for whom the suspended state has changed.
11557        List<String> changedPackages = new ArrayList<>(packageNames.length);
11558        // List of package names for whom the suspended state is not set as requested in this
11559        // method.
11560        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11561        long callingId = Binder.clearCallingIdentity();
11562        try {
11563            for (int i = 0; i < packageNames.length; i++) {
11564                String packageName = packageNames[i];
11565                boolean changed = false;
11566                final int appId;
11567                synchronized (mPackages) {
11568                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11569                    if (pkgSetting == null) {
11570                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11571                                + "\". Skipping suspending/un-suspending.");
11572                        unactionedPackages.add(packageName);
11573                        continue;
11574                    }
11575                    appId = pkgSetting.appId;
11576                    if (pkgSetting.getSuspended(userId) != suspended) {
11577                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11578                            unactionedPackages.add(packageName);
11579                            continue;
11580                        }
11581                        pkgSetting.setSuspended(suspended, userId);
11582                        mSettings.writePackageRestrictionsLPr(userId);
11583                        changed = true;
11584                        changedPackages.add(packageName);
11585                    }
11586                }
11587
11588                if (changed && suspended) {
11589                    killApplication(packageName, UserHandle.getUid(userId, appId),
11590                            "suspending package");
11591                }
11592            }
11593        } finally {
11594            Binder.restoreCallingIdentity(callingId);
11595        }
11596
11597        if (!changedPackages.isEmpty()) {
11598            sendPackagesSuspendedForUser(changedPackages.toArray(
11599                    new String[changedPackages.size()]), userId, suspended);
11600        }
11601
11602        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11603    }
11604
11605    @Override
11606    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11607        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11608                true /* requireFullPermission */, false /* checkShell */,
11609                "isPackageSuspendedForUser for user " + userId);
11610        synchronized (mPackages) {
11611            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11612            if (pkgSetting == null) {
11613                throw new IllegalArgumentException("Unknown target package: " + packageName);
11614            }
11615            return pkgSetting.getSuspended(userId);
11616        }
11617    }
11618
11619    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11620        if (isPackageDeviceAdmin(packageName, userId)) {
11621            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11622                    + "\": has an active device admin");
11623            return false;
11624        }
11625
11626        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11627        if (packageName.equals(activeLauncherPackageName)) {
11628            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11629                    + "\": contains the active launcher");
11630            return false;
11631        }
11632
11633        if (packageName.equals(mRequiredInstallerPackage)) {
11634            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11635                    + "\": required for package installation");
11636            return false;
11637        }
11638
11639        if (packageName.equals(mRequiredVerifierPackage)) {
11640            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11641                    + "\": required for package verification");
11642            return false;
11643        }
11644
11645        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11646            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11647                    + "\": is the default dialer");
11648            return false;
11649        }
11650
11651        return true;
11652    }
11653
11654    private String getActiveLauncherPackageName(int userId) {
11655        Intent intent = new Intent(Intent.ACTION_MAIN);
11656        intent.addCategory(Intent.CATEGORY_HOME);
11657        ResolveInfo resolveInfo = resolveIntent(
11658                intent,
11659                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11660                PackageManager.MATCH_DEFAULT_ONLY,
11661                userId);
11662
11663        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11664    }
11665
11666    private String getDefaultDialerPackageName(int userId) {
11667        synchronized (mPackages) {
11668            return mSettings.getDefaultDialerPackageNameLPw(userId);
11669        }
11670    }
11671
11672    @Override
11673    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11674        mContext.enforceCallingOrSelfPermission(
11675                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11676                "Only package verification agents can verify applications");
11677
11678        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11679        final PackageVerificationResponse response = new PackageVerificationResponse(
11680                verificationCode, Binder.getCallingUid());
11681        msg.arg1 = id;
11682        msg.obj = response;
11683        mHandler.sendMessage(msg);
11684    }
11685
11686    @Override
11687    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11688            long millisecondsToDelay) {
11689        mContext.enforceCallingOrSelfPermission(
11690                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11691                "Only package verification agents can extend verification timeouts");
11692
11693        final PackageVerificationState state = mPendingVerification.get(id);
11694        final PackageVerificationResponse response = new PackageVerificationResponse(
11695                verificationCodeAtTimeout, Binder.getCallingUid());
11696
11697        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11698            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11699        }
11700        if (millisecondsToDelay < 0) {
11701            millisecondsToDelay = 0;
11702        }
11703        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11704                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11705            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11706        }
11707
11708        if ((state != null) && !state.timeoutExtended()) {
11709            state.extendTimeout();
11710
11711            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11712            msg.arg1 = id;
11713            msg.obj = response;
11714            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11715        }
11716    }
11717
11718    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11719            int verificationCode, UserHandle user) {
11720        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11721        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11722        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11723        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11724        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11725
11726        mContext.sendBroadcastAsUser(intent, user,
11727                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11728    }
11729
11730    private ComponentName matchComponentForVerifier(String packageName,
11731            List<ResolveInfo> receivers) {
11732        ActivityInfo targetReceiver = null;
11733
11734        final int NR = receivers.size();
11735        for (int i = 0; i < NR; i++) {
11736            final ResolveInfo info = receivers.get(i);
11737            if (info.activityInfo == null) {
11738                continue;
11739            }
11740
11741            if (packageName.equals(info.activityInfo.packageName)) {
11742                targetReceiver = info.activityInfo;
11743                break;
11744            }
11745        }
11746
11747        if (targetReceiver == null) {
11748            return null;
11749        }
11750
11751        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11752    }
11753
11754    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11755            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11756        if (pkgInfo.verifiers.length == 0) {
11757            return null;
11758        }
11759
11760        final int N = pkgInfo.verifiers.length;
11761        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11762        for (int i = 0; i < N; i++) {
11763            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11764
11765            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11766                    receivers);
11767            if (comp == null) {
11768                continue;
11769            }
11770
11771            final int verifierUid = getUidForVerifier(verifierInfo);
11772            if (verifierUid == -1) {
11773                continue;
11774            }
11775
11776            if (DEBUG_VERIFY) {
11777                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11778                        + " with the correct signature");
11779            }
11780            sufficientVerifiers.add(comp);
11781            verificationState.addSufficientVerifier(verifierUid);
11782        }
11783
11784        return sufficientVerifiers;
11785    }
11786
11787    private int getUidForVerifier(VerifierInfo verifierInfo) {
11788        synchronized (mPackages) {
11789            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11790            if (pkg == null) {
11791                return -1;
11792            } else if (pkg.mSignatures.length != 1) {
11793                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11794                        + " has more than one signature; ignoring");
11795                return -1;
11796            }
11797
11798            /*
11799             * If the public key of the package's signature does not match
11800             * our expected public key, then this is a different package and
11801             * we should skip.
11802             */
11803
11804            final byte[] expectedPublicKey;
11805            try {
11806                final Signature verifierSig = pkg.mSignatures[0];
11807                final PublicKey publicKey = verifierSig.getPublicKey();
11808                expectedPublicKey = publicKey.getEncoded();
11809            } catch (CertificateException e) {
11810                return -1;
11811            }
11812
11813            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11814
11815            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11816                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11817                        + " does not have the expected public key; ignoring");
11818                return -1;
11819            }
11820
11821            return pkg.applicationInfo.uid;
11822        }
11823    }
11824
11825    @Override
11826    public void finishPackageInstall(int token, boolean didLaunch) {
11827        enforceSystemOrRoot("Only the system is allowed to finish installs");
11828
11829        if (DEBUG_INSTALL) {
11830            Slog.v(TAG, "BM finishing package install for " + token);
11831        }
11832        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11833
11834        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11835        mHandler.sendMessage(msg);
11836    }
11837
11838    /**
11839     * Get the verification agent timeout.
11840     *
11841     * @return verification timeout in milliseconds
11842     */
11843    private long getVerificationTimeout() {
11844        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11845                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11846                DEFAULT_VERIFICATION_TIMEOUT);
11847    }
11848
11849    /**
11850     * Get the default verification agent response code.
11851     *
11852     * @return default verification response code
11853     */
11854    private int getDefaultVerificationResponse() {
11855        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11856                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11857                DEFAULT_VERIFICATION_RESPONSE);
11858    }
11859
11860    /**
11861     * Check whether or not package verification has been enabled.
11862     *
11863     * @return true if verification should be performed
11864     */
11865    private boolean isVerificationEnabled(int userId, int installFlags) {
11866        if (!DEFAULT_VERIFY_ENABLE) {
11867            return false;
11868        }
11869        // Ephemeral apps don't get the full verification treatment
11870        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11871            if (DEBUG_EPHEMERAL) {
11872                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11873            }
11874            return false;
11875        }
11876
11877        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11878
11879        // Check if installing from ADB
11880        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11881            // Do not run verification in a test harness environment
11882            if (ActivityManager.isRunningInTestHarness()) {
11883                return false;
11884            }
11885            if (ensureVerifyAppsEnabled) {
11886                return true;
11887            }
11888            // Check if the developer does not want package verification for ADB installs
11889            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11890                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11891                return false;
11892            }
11893        }
11894
11895        if (ensureVerifyAppsEnabled) {
11896            return true;
11897        }
11898
11899        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11900                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11901    }
11902
11903    @Override
11904    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11905            throws RemoteException {
11906        mContext.enforceCallingOrSelfPermission(
11907                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11908                "Only intentfilter verification agents can verify applications");
11909
11910        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11911        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11912                Binder.getCallingUid(), verificationCode, failedDomains);
11913        msg.arg1 = id;
11914        msg.obj = response;
11915        mHandler.sendMessage(msg);
11916    }
11917
11918    @Override
11919    public int getIntentVerificationStatus(String packageName, int userId) {
11920        synchronized (mPackages) {
11921            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11922        }
11923    }
11924
11925    @Override
11926    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11927        mContext.enforceCallingOrSelfPermission(
11928                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11929
11930        boolean result = false;
11931        synchronized (mPackages) {
11932            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11933        }
11934        if (result) {
11935            scheduleWritePackageRestrictionsLocked(userId);
11936        }
11937        return result;
11938    }
11939
11940    @Override
11941    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11942            String packageName) {
11943        synchronized (mPackages) {
11944            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11945        }
11946    }
11947
11948    @Override
11949    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11950        if (TextUtils.isEmpty(packageName)) {
11951            return ParceledListSlice.emptyList();
11952        }
11953        synchronized (mPackages) {
11954            PackageParser.Package pkg = mPackages.get(packageName);
11955            if (pkg == null || pkg.activities == null) {
11956                return ParceledListSlice.emptyList();
11957            }
11958            final int count = pkg.activities.size();
11959            ArrayList<IntentFilter> result = new ArrayList<>();
11960            for (int n=0; n<count; n++) {
11961                PackageParser.Activity activity = pkg.activities.get(n);
11962                if (activity.intents != null && activity.intents.size() > 0) {
11963                    result.addAll(activity.intents);
11964                }
11965            }
11966            return new ParceledListSlice<>(result);
11967        }
11968    }
11969
11970    @Override
11971    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11972        mContext.enforceCallingOrSelfPermission(
11973                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11974
11975        synchronized (mPackages) {
11976            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11977            if (packageName != null) {
11978                result |= updateIntentVerificationStatus(packageName,
11979                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11980                        userId);
11981                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11982                        packageName, userId);
11983            }
11984            return result;
11985        }
11986    }
11987
11988    @Override
11989    public String getDefaultBrowserPackageName(int userId) {
11990        synchronized (mPackages) {
11991            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11992        }
11993    }
11994
11995    /**
11996     * Get the "allow unknown sources" setting.
11997     *
11998     * @return the current "allow unknown sources" setting
11999     */
12000    private int getUnknownSourcesSettings() {
12001        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12002                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12003                -1);
12004    }
12005
12006    @Override
12007    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12008        final int uid = Binder.getCallingUid();
12009        // writer
12010        synchronized (mPackages) {
12011            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12012            if (targetPackageSetting == null) {
12013                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12014            }
12015
12016            PackageSetting installerPackageSetting;
12017            if (installerPackageName != null) {
12018                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12019                if (installerPackageSetting == null) {
12020                    throw new IllegalArgumentException("Unknown installer package: "
12021                            + installerPackageName);
12022                }
12023            } else {
12024                installerPackageSetting = null;
12025            }
12026
12027            Signature[] callerSignature;
12028            Object obj = mSettings.getUserIdLPr(uid);
12029            if (obj != null) {
12030                if (obj instanceof SharedUserSetting) {
12031                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12032                } else if (obj instanceof PackageSetting) {
12033                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12034                } else {
12035                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12036                }
12037            } else {
12038                throw new SecurityException("Unknown calling UID: " + uid);
12039            }
12040
12041            // Verify: can't set installerPackageName to a package that is
12042            // not signed with the same cert as the caller.
12043            if (installerPackageSetting != null) {
12044                if (compareSignatures(callerSignature,
12045                        installerPackageSetting.signatures.mSignatures)
12046                        != PackageManager.SIGNATURE_MATCH) {
12047                    throw new SecurityException(
12048                            "Caller does not have same cert as new installer package "
12049                            + installerPackageName);
12050                }
12051            }
12052
12053            // Verify: if target already has an installer package, it must
12054            // be signed with the same cert as the caller.
12055            if (targetPackageSetting.installerPackageName != null) {
12056                PackageSetting setting = mSettings.mPackages.get(
12057                        targetPackageSetting.installerPackageName);
12058                // If the currently set package isn't valid, then it's always
12059                // okay to change it.
12060                if (setting != null) {
12061                    if (compareSignatures(callerSignature,
12062                            setting.signatures.mSignatures)
12063                            != PackageManager.SIGNATURE_MATCH) {
12064                        throw new SecurityException(
12065                                "Caller does not have same cert as old installer package "
12066                                + targetPackageSetting.installerPackageName);
12067                    }
12068                }
12069            }
12070
12071            // Okay!
12072            targetPackageSetting.installerPackageName = installerPackageName;
12073            if (installerPackageName != null) {
12074                mSettings.mInstallerPackages.add(installerPackageName);
12075            }
12076            scheduleWriteSettingsLocked();
12077        }
12078    }
12079
12080    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12081        // Queue up an async operation since the package installation may take a little while.
12082        mHandler.post(new Runnable() {
12083            public void run() {
12084                mHandler.removeCallbacks(this);
12085                 // Result object to be returned
12086                PackageInstalledInfo res = new PackageInstalledInfo();
12087                res.setReturnCode(currentStatus);
12088                res.uid = -1;
12089                res.pkg = null;
12090                res.removedInfo = null;
12091                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12092                    args.doPreInstall(res.returnCode);
12093                    synchronized (mInstallLock) {
12094                        installPackageTracedLI(args, res);
12095                    }
12096                    args.doPostInstall(res.returnCode, res.uid);
12097                }
12098
12099                // A restore should be performed at this point if (a) the install
12100                // succeeded, (b) the operation is not an update, and (c) the new
12101                // package has not opted out of backup participation.
12102                final boolean update = res.removedInfo != null
12103                        && res.removedInfo.removedPackage != null;
12104                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12105                boolean doRestore = !update
12106                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12107
12108                // Set up the post-install work request bookkeeping.  This will be used
12109                // and cleaned up by the post-install event handling regardless of whether
12110                // there's a restore pass performed.  Token values are >= 1.
12111                int token;
12112                if (mNextInstallToken < 0) mNextInstallToken = 1;
12113                token = mNextInstallToken++;
12114
12115                PostInstallData data = new PostInstallData(args, res);
12116                mRunningInstalls.put(token, data);
12117                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12118
12119                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12120                    // Pass responsibility to the Backup Manager.  It will perform a
12121                    // restore if appropriate, then pass responsibility back to the
12122                    // Package Manager to run the post-install observer callbacks
12123                    // and broadcasts.
12124                    IBackupManager bm = IBackupManager.Stub.asInterface(
12125                            ServiceManager.getService(Context.BACKUP_SERVICE));
12126                    if (bm != null) {
12127                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12128                                + " to BM for possible restore");
12129                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12130                        try {
12131                            // TODO: http://b/22388012
12132                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12133                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12134                            } else {
12135                                doRestore = false;
12136                            }
12137                        } catch (RemoteException e) {
12138                            // can't happen; the backup manager is local
12139                        } catch (Exception e) {
12140                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12141                            doRestore = false;
12142                        }
12143                    } else {
12144                        Slog.e(TAG, "Backup Manager not found!");
12145                        doRestore = false;
12146                    }
12147                }
12148
12149                if (!doRestore) {
12150                    // No restore possible, or the Backup Manager was mysteriously not
12151                    // available -- just fire the post-install work request directly.
12152                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12153
12154                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12155
12156                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12157                    mHandler.sendMessage(msg);
12158                }
12159            }
12160        });
12161    }
12162
12163    /**
12164     * Callback from PackageSettings whenever an app is first transitioned out of the
12165     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12166     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12167     * here whether the app is the target of an ongoing install, and only send the
12168     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12169     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12170     * handling.
12171     */
12172    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12173        // Serialize this with the rest of the install-process message chain.  In the
12174        // restore-at-install case, this Runnable will necessarily run before the
12175        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12176        // are coherent.  In the non-restore case, the app has already completed install
12177        // and been launched through some other means, so it is not in a problematic
12178        // state for observers to see the FIRST_LAUNCH signal.
12179        mHandler.post(new Runnable() {
12180            @Override
12181            public void run() {
12182                for (int i = 0; i < mRunningInstalls.size(); i++) {
12183                    final PostInstallData data = mRunningInstalls.valueAt(i);
12184                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12185                        // right package; but is it for the right user?
12186                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12187                            if (userId == data.res.newUsers[uIndex]) {
12188                                if (DEBUG_BACKUP) {
12189                                    Slog.i(TAG, "Package " + pkgName
12190                                            + " being restored so deferring FIRST_LAUNCH");
12191                                }
12192                                return;
12193                            }
12194                        }
12195                    }
12196                }
12197                // didn't find it, so not being restored
12198                if (DEBUG_BACKUP) {
12199                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12200                }
12201                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12202            }
12203        });
12204    }
12205
12206    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12207        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12208                installerPkg, null, userIds);
12209    }
12210
12211    private abstract class HandlerParams {
12212        private static final int MAX_RETRIES = 4;
12213
12214        /**
12215         * Number of times startCopy() has been attempted and had a non-fatal
12216         * error.
12217         */
12218        private int mRetries = 0;
12219
12220        /** User handle for the user requesting the information or installation. */
12221        private final UserHandle mUser;
12222        String traceMethod;
12223        int traceCookie;
12224
12225        HandlerParams(UserHandle user) {
12226            mUser = user;
12227        }
12228
12229        UserHandle getUser() {
12230            return mUser;
12231        }
12232
12233        HandlerParams setTraceMethod(String traceMethod) {
12234            this.traceMethod = traceMethod;
12235            return this;
12236        }
12237
12238        HandlerParams setTraceCookie(int traceCookie) {
12239            this.traceCookie = traceCookie;
12240            return this;
12241        }
12242
12243        final boolean startCopy() {
12244            boolean res;
12245            try {
12246                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12247
12248                if (++mRetries > MAX_RETRIES) {
12249                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12250                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12251                    handleServiceError();
12252                    return false;
12253                } else {
12254                    handleStartCopy();
12255                    res = true;
12256                }
12257            } catch (RemoteException e) {
12258                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12259                mHandler.sendEmptyMessage(MCS_RECONNECT);
12260                res = false;
12261            }
12262            handleReturnCode();
12263            return res;
12264        }
12265
12266        final void serviceError() {
12267            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12268            handleServiceError();
12269            handleReturnCode();
12270        }
12271
12272        abstract void handleStartCopy() throws RemoteException;
12273        abstract void handleServiceError();
12274        abstract void handleReturnCode();
12275    }
12276
12277    class MeasureParams extends HandlerParams {
12278        private final PackageStats mStats;
12279        private boolean mSuccess;
12280
12281        private final IPackageStatsObserver mObserver;
12282
12283        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12284            super(new UserHandle(stats.userHandle));
12285            mObserver = observer;
12286            mStats = stats;
12287        }
12288
12289        @Override
12290        public String toString() {
12291            return "MeasureParams{"
12292                + Integer.toHexString(System.identityHashCode(this))
12293                + " " + mStats.packageName + "}";
12294        }
12295
12296        @Override
12297        void handleStartCopy() throws RemoteException {
12298            synchronized (mInstallLock) {
12299                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12300            }
12301
12302            if (mSuccess) {
12303                final boolean mounted;
12304                if (Environment.isExternalStorageEmulated()) {
12305                    mounted = true;
12306                } else {
12307                    final String status = Environment.getExternalStorageState();
12308                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12309                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12310                }
12311
12312                if (mounted) {
12313                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12314
12315                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12316                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12317
12318                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12319                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12320
12321                    // Always subtract cache size, since it's a subdirectory
12322                    mStats.externalDataSize -= mStats.externalCacheSize;
12323
12324                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12325                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12326
12327                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12328                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12329                }
12330            }
12331        }
12332
12333        @Override
12334        void handleReturnCode() {
12335            if (mObserver != null) {
12336                try {
12337                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12338                } catch (RemoteException e) {
12339                    Slog.i(TAG, "Observer no longer exists.");
12340                }
12341            }
12342        }
12343
12344        @Override
12345        void handleServiceError() {
12346            Slog.e(TAG, "Could not measure application " + mStats.packageName
12347                            + " external storage");
12348        }
12349    }
12350
12351    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12352            throws RemoteException {
12353        long result = 0;
12354        for (File path : paths) {
12355            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12356        }
12357        return result;
12358    }
12359
12360    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12361        for (File path : paths) {
12362            try {
12363                mcs.clearDirectory(path.getAbsolutePath());
12364            } catch (RemoteException e) {
12365            }
12366        }
12367    }
12368
12369    static class OriginInfo {
12370        /**
12371         * Location where install is coming from, before it has been
12372         * copied/renamed into place. This could be a single monolithic APK
12373         * file, or a cluster directory. This location may be untrusted.
12374         */
12375        final File file;
12376        final String cid;
12377
12378        /**
12379         * Flag indicating that {@link #file} or {@link #cid} has already been
12380         * staged, meaning downstream users don't need to defensively copy the
12381         * contents.
12382         */
12383        final boolean staged;
12384
12385        /**
12386         * Flag indicating that {@link #file} or {@link #cid} is an already
12387         * installed app that is being moved.
12388         */
12389        final boolean existing;
12390
12391        final String resolvedPath;
12392        final File resolvedFile;
12393
12394        static OriginInfo fromNothing() {
12395            return new OriginInfo(null, null, false, false);
12396        }
12397
12398        static OriginInfo fromUntrustedFile(File file) {
12399            return new OriginInfo(file, null, false, false);
12400        }
12401
12402        static OriginInfo fromExistingFile(File file) {
12403            return new OriginInfo(file, null, false, true);
12404        }
12405
12406        static OriginInfo fromStagedFile(File file) {
12407            return new OriginInfo(file, null, true, false);
12408        }
12409
12410        static OriginInfo fromStagedContainer(String cid) {
12411            return new OriginInfo(null, cid, true, false);
12412        }
12413
12414        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12415            this.file = file;
12416            this.cid = cid;
12417            this.staged = staged;
12418            this.existing = existing;
12419
12420            if (cid != null) {
12421                resolvedPath = PackageHelper.getSdDir(cid);
12422                resolvedFile = new File(resolvedPath);
12423            } else if (file != null) {
12424                resolvedPath = file.getAbsolutePath();
12425                resolvedFile = file;
12426            } else {
12427                resolvedPath = null;
12428                resolvedFile = null;
12429            }
12430        }
12431    }
12432
12433    static class MoveInfo {
12434        final int moveId;
12435        final String fromUuid;
12436        final String toUuid;
12437        final String packageName;
12438        final String dataAppName;
12439        final int appId;
12440        final String seinfo;
12441        final int targetSdkVersion;
12442
12443        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12444                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12445            this.moveId = moveId;
12446            this.fromUuid = fromUuid;
12447            this.toUuid = toUuid;
12448            this.packageName = packageName;
12449            this.dataAppName = dataAppName;
12450            this.appId = appId;
12451            this.seinfo = seinfo;
12452            this.targetSdkVersion = targetSdkVersion;
12453        }
12454    }
12455
12456    static class VerificationInfo {
12457        /** A constant used to indicate that a uid value is not present. */
12458        public static final int NO_UID = -1;
12459
12460        /** URI referencing where the package was downloaded from. */
12461        final Uri originatingUri;
12462
12463        /** HTTP referrer URI associated with the originatingURI. */
12464        final Uri referrer;
12465
12466        /** UID of the application that the install request originated from. */
12467        final int originatingUid;
12468
12469        /** UID of application requesting the install */
12470        final int installerUid;
12471
12472        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12473            this.originatingUri = originatingUri;
12474            this.referrer = referrer;
12475            this.originatingUid = originatingUid;
12476            this.installerUid = installerUid;
12477        }
12478    }
12479
12480    class InstallParams extends HandlerParams {
12481        final OriginInfo origin;
12482        final MoveInfo move;
12483        final IPackageInstallObserver2 observer;
12484        int installFlags;
12485        final String installerPackageName;
12486        final String volumeUuid;
12487        private InstallArgs mArgs;
12488        private int mRet;
12489        final String packageAbiOverride;
12490        final String[] grantedRuntimePermissions;
12491        final VerificationInfo verificationInfo;
12492        final Certificate[][] certificates;
12493
12494        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12495                int installFlags, String installerPackageName, String volumeUuid,
12496                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12497                String[] grantedPermissions, Certificate[][] certificates) {
12498            super(user);
12499            this.origin = origin;
12500            this.move = move;
12501            this.observer = observer;
12502            this.installFlags = installFlags;
12503            this.installerPackageName = installerPackageName;
12504            this.volumeUuid = volumeUuid;
12505            this.verificationInfo = verificationInfo;
12506            this.packageAbiOverride = packageAbiOverride;
12507            this.grantedRuntimePermissions = grantedPermissions;
12508            this.certificates = certificates;
12509        }
12510
12511        @Override
12512        public String toString() {
12513            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12514                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12515        }
12516
12517        private int installLocationPolicy(PackageInfoLite pkgLite) {
12518            String packageName = pkgLite.packageName;
12519            int installLocation = pkgLite.installLocation;
12520            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12521            // reader
12522            synchronized (mPackages) {
12523                // Currently installed package which the new package is attempting to replace or
12524                // null if no such package is installed.
12525                PackageParser.Package installedPkg = mPackages.get(packageName);
12526                // Package which currently owns the data which the new package will own if installed.
12527                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12528                // will be null whereas dataOwnerPkg will contain information about the package
12529                // which was uninstalled while keeping its data.
12530                PackageParser.Package dataOwnerPkg = installedPkg;
12531                if (dataOwnerPkg  == null) {
12532                    PackageSetting ps = mSettings.mPackages.get(packageName);
12533                    if (ps != null) {
12534                        dataOwnerPkg = ps.pkg;
12535                    }
12536                }
12537
12538                if (dataOwnerPkg != null) {
12539                    // If installed, the package will get access to data left on the device by its
12540                    // predecessor. As a security measure, this is permited only if this is not a
12541                    // version downgrade or if the predecessor package is marked as debuggable and
12542                    // a downgrade is explicitly requested.
12543                    //
12544                    // On debuggable platform builds, downgrades are permitted even for
12545                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12546                    // not offer security guarantees and thus it's OK to disable some security
12547                    // mechanisms to make debugging/testing easier on those builds. However, even on
12548                    // debuggable builds downgrades of packages are permitted only if requested via
12549                    // installFlags. This is because we aim to keep the behavior of debuggable
12550                    // platform builds as close as possible to the behavior of non-debuggable
12551                    // platform builds.
12552                    final boolean downgradeRequested =
12553                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12554                    final boolean packageDebuggable =
12555                                (dataOwnerPkg.applicationInfo.flags
12556                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12557                    final boolean downgradePermitted =
12558                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12559                    if (!downgradePermitted) {
12560                        try {
12561                            checkDowngrade(dataOwnerPkg, pkgLite);
12562                        } catch (PackageManagerException e) {
12563                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12564                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12565                        }
12566                    }
12567                }
12568
12569                if (installedPkg != null) {
12570                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12571                        // Check for updated system application.
12572                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12573                            if (onSd) {
12574                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12575                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12576                            }
12577                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12578                        } else {
12579                            if (onSd) {
12580                                // Install flag overrides everything.
12581                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12582                            }
12583                            // If current upgrade specifies particular preference
12584                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12585                                // Application explicitly specified internal.
12586                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12587                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12588                                // App explictly prefers external. Let policy decide
12589                            } else {
12590                                // Prefer previous location
12591                                if (isExternal(installedPkg)) {
12592                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12593                                }
12594                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12595                            }
12596                        }
12597                    } else {
12598                        // Invalid install. Return error code
12599                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12600                    }
12601                }
12602            }
12603            // All the special cases have been taken care of.
12604            // Return result based on recommended install location.
12605            if (onSd) {
12606                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12607            }
12608            return pkgLite.recommendedInstallLocation;
12609        }
12610
12611        /*
12612         * Invoke remote method to get package information and install
12613         * location values. Override install location based on default
12614         * policy if needed and then create install arguments based
12615         * on the install location.
12616         */
12617        public void handleStartCopy() throws RemoteException {
12618            int ret = PackageManager.INSTALL_SUCCEEDED;
12619
12620            // If we're already staged, we've firmly committed to an install location
12621            if (origin.staged) {
12622                if (origin.file != null) {
12623                    installFlags |= PackageManager.INSTALL_INTERNAL;
12624                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12625                } else if (origin.cid != null) {
12626                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12627                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12628                } else {
12629                    throw new IllegalStateException("Invalid stage location");
12630                }
12631            }
12632
12633            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12634            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12635            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12636            PackageInfoLite pkgLite = null;
12637
12638            if (onInt && onSd) {
12639                // Check if both bits are set.
12640                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12641                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12642            } else if (onSd && ephemeral) {
12643                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12644                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12645            } else {
12646                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12647                        packageAbiOverride);
12648
12649                if (DEBUG_EPHEMERAL && ephemeral) {
12650                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12651                }
12652
12653                /*
12654                 * If we have too little free space, try to free cache
12655                 * before giving up.
12656                 */
12657                if (!origin.staged && pkgLite.recommendedInstallLocation
12658                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12659                    // TODO: focus freeing disk space on the target device
12660                    final StorageManager storage = StorageManager.from(mContext);
12661                    final long lowThreshold = storage.getStorageLowBytes(
12662                            Environment.getDataDirectory());
12663
12664                    final long sizeBytes = mContainerService.calculateInstalledSize(
12665                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12666
12667                    try {
12668                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12669                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12670                                installFlags, packageAbiOverride);
12671                    } catch (InstallerException e) {
12672                        Slog.w(TAG, "Failed to free cache", e);
12673                    }
12674
12675                    /*
12676                     * The cache free must have deleted the file we
12677                     * downloaded to install.
12678                     *
12679                     * TODO: fix the "freeCache" call to not delete
12680                     *       the file we care about.
12681                     */
12682                    if (pkgLite.recommendedInstallLocation
12683                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12684                        pkgLite.recommendedInstallLocation
12685                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12686                    }
12687                }
12688            }
12689
12690            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12691                int loc = pkgLite.recommendedInstallLocation;
12692                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12693                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12694                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12695                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12696                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12697                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12698                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12699                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12700                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12701                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12702                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12703                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12704                } else {
12705                    // Override with defaults if needed.
12706                    loc = installLocationPolicy(pkgLite);
12707                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12708                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12709                    } else if (!onSd && !onInt) {
12710                        // Override install location with flags
12711                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12712                            // Set the flag to install on external media.
12713                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12714                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12715                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12716                            if (DEBUG_EPHEMERAL) {
12717                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12718                            }
12719                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12720                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12721                                    |PackageManager.INSTALL_INTERNAL);
12722                        } else {
12723                            // Make sure the flag for installing on external
12724                            // media is unset
12725                            installFlags |= PackageManager.INSTALL_INTERNAL;
12726                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12727                        }
12728                    }
12729                }
12730            }
12731
12732            final InstallArgs args = createInstallArgs(this);
12733            mArgs = args;
12734
12735            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12736                // TODO: http://b/22976637
12737                // Apps installed for "all" users use the device owner to verify the app
12738                UserHandle verifierUser = getUser();
12739                if (verifierUser == UserHandle.ALL) {
12740                    verifierUser = UserHandle.SYSTEM;
12741                }
12742
12743                /*
12744                 * Determine if we have any installed package verifiers. If we
12745                 * do, then we'll defer to them to verify the packages.
12746                 */
12747                final int requiredUid = mRequiredVerifierPackage == null ? -1
12748                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12749                                verifierUser.getIdentifier());
12750                if (!origin.existing && requiredUid != -1
12751                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12752                    final Intent verification = new Intent(
12753                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12754                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12755                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12756                            PACKAGE_MIME_TYPE);
12757                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12758
12759                    // Query all live verifiers based on current user state
12760                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12761                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12762
12763                    if (DEBUG_VERIFY) {
12764                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12765                                + verification.toString() + " with " + pkgLite.verifiers.length
12766                                + " optional verifiers");
12767                    }
12768
12769                    final int verificationId = mPendingVerificationToken++;
12770
12771                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12772
12773                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12774                            installerPackageName);
12775
12776                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12777                            installFlags);
12778
12779                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12780                            pkgLite.packageName);
12781
12782                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12783                            pkgLite.versionCode);
12784
12785                    if (verificationInfo != null) {
12786                        if (verificationInfo.originatingUri != null) {
12787                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12788                                    verificationInfo.originatingUri);
12789                        }
12790                        if (verificationInfo.referrer != null) {
12791                            verification.putExtra(Intent.EXTRA_REFERRER,
12792                                    verificationInfo.referrer);
12793                        }
12794                        if (verificationInfo.originatingUid >= 0) {
12795                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12796                                    verificationInfo.originatingUid);
12797                        }
12798                        if (verificationInfo.installerUid >= 0) {
12799                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12800                                    verificationInfo.installerUid);
12801                        }
12802                    }
12803
12804                    final PackageVerificationState verificationState = new PackageVerificationState(
12805                            requiredUid, args);
12806
12807                    mPendingVerification.append(verificationId, verificationState);
12808
12809                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12810                            receivers, verificationState);
12811
12812                    /*
12813                     * If any sufficient verifiers were listed in the package
12814                     * manifest, attempt to ask them.
12815                     */
12816                    if (sufficientVerifiers != null) {
12817                        final int N = sufficientVerifiers.size();
12818                        if (N == 0) {
12819                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12820                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12821                        } else {
12822                            for (int i = 0; i < N; i++) {
12823                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12824
12825                                final Intent sufficientIntent = new Intent(verification);
12826                                sufficientIntent.setComponent(verifierComponent);
12827                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12828                            }
12829                        }
12830                    }
12831
12832                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12833                            mRequiredVerifierPackage, receivers);
12834                    if (ret == PackageManager.INSTALL_SUCCEEDED
12835                            && mRequiredVerifierPackage != null) {
12836                        Trace.asyncTraceBegin(
12837                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12838                        /*
12839                         * Send the intent to the required verification agent,
12840                         * but only start the verification timeout after the
12841                         * target BroadcastReceivers have run.
12842                         */
12843                        verification.setComponent(requiredVerifierComponent);
12844                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12845                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12846                                new BroadcastReceiver() {
12847                                    @Override
12848                                    public void onReceive(Context context, Intent intent) {
12849                                        final Message msg = mHandler
12850                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12851                                        msg.arg1 = verificationId;
12852                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12853                                    }
12854                                }, null, 0, null, null);
12855
12856                        /*
12857                         * We don't want the copy to proceed until verification
12858                         * succeeds, so null out this field.
12859                         */
12860                        mArgs = null;
12861                    }
12862                } else {
12863                    /*
12864                     * No package verification is enabled, so immediately start
12865                     * the remote call to initiate copy using temporary file.
12866                     */
12867                    ret = args.copyApk(mContainerService, true);
12868                }
12869            }
12870
12871            mRet = ret;
12872        }
12873
12874        @Override
12875        void handleReturnCode() {
12876            // If mArgs is null, then MCS couldn't be reached. When it
12877            // reconnects, it will try again to install. At that point, this
12878            // will succeed.
12879            if (mArgs != null) {
12880                processPendingInstall(mArgs, mRet);
12881            }
12882        }
12883
12884        @Override
12885        void handleServiceError() {
12886            mArgs = createInstallArgs(this);
12887            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12888        }
12889
12890        public boolean isForwardLocked() {
12891            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12892        }
12893    }
12894
12895    /**
12896     * Used during creation of InstallArgs
12897     *
12898     * @param installFlags package installation flags
12899     * @return true if should be installed on external storage
12900     */
12901    private static boolean installOnExternalAsec(int installFlags) {
12902        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12903            return false;
12904        }
12905        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12906            return true;
12907        }
12908        return false;
12909    }
12910
12911    /**
12912     * Used during creation of InstallArgs
12913     *
12914     * @param installFlags package installation flags
12915     * @return true if should be installed as forward locked
12916     */
12917    private static boolean installForwardLocked(int installFlags) {
12918        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12919    }
12920
12921    private InstallArgs createInstallArgs(InstallParams params) {
12922        if (params.move != null) {
12923            return new MoveInstallArgs(params);
12924        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12925            return new AsecInstallArgs(params);
12926        } else {
12927            return new FileInstallArgs(params);
12928        }
12929    }
12930
12931    /**
12932     * Create args that describe an existing installed package. Typically used
12933     * when cleaning up old installs, or used as a move source.
12934     */
12935    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12936            String resourcePath, String[] instructionSets) {
12937        final boolean isInAsec;
12938        if (installOnExternalAsec(installFlags)) {
12939            /* Apps on SD card are always in ASEC containers. */
12940            isInAsec = true;
12941        } else if (installForwardLocked(installFlags)
12942                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12943            /*
12944             * Forward-locked apps are only in ASEC containers if they're the
12945             * new style
12946             */
12947            isInAsec = true;
12948        } else {
12949            isInAsec = false;
12950        }
12951
12952        if (isInAsec) {
12953            return new AsecInstallArgs(codePath, instructionSets,
12954                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12955        } else {
12956            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12957        }
12958    }
12959
12960    static abstract class InstallArgs {
12961        /** @see InstallParams#origin */
12962        final OriginInfo origin;
12963        /** @see InstallParams#move */
12964        final MoveInfo move;
12965
12966        final IPackageInstallObserver2 observer;
12967        // Always refers to PackageManager flags only
12968        final int installFlags;
12969        final String installerPackageName;
12970        final String volumeUuid;
12971        final UserHandle user;
12972        final String abiOverride;
12973        final String[] installGrantPermissions;
12974        /** If non-null, drop an async trace when the install completes */
12975        final String traceMethod;
12976        final int traceCookie;
12977        final Certificate[][] certificates;
12978
12979        // The list of instruction sets supported by this app. This is currently
12980        // only used during the rmdex() phase to clean up resources. We can get rid of this
12981        // if we move dex files under the common app path.
12982        /* nullable */ String[] instructionSets;
12983
12984        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12985                int installFlags, String installerPackageName, String volumeUuid,
12986                UserHandle user, String[] instructionSets,
12987                String abiOverride, String[] installGrantPermissions,
12988                String traceMethod, int traceCookie, Certificate[][] certificates) {
12989            this.origin = origin;
12990            this.move = move;
12991            this.installFlags = installFlags;
12992            this.observer = observer;
12993            this.installerPackageName = installerPackageName;
12994            this.volumeUuid = volumeUuid;
12995            this.user = user;
12996            this.instructionSets = instructionSets;
12997            this.abiOverride = abiOverride;
12998            this.installGrantPermissions = installGrantPermissions;
12999            this.traceMethod = traceMethod;
13000            this.traceCookie = traceCookie;
13001            this.certificates = certificates;
13002        }
13003
13004        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13005        abstract int doPreInstall(int status);
13006
13007        /**
13008         * Rename package into final resting place. All paths on the given
13009         * scanned package should be updated to reflect the rename.
13010         */
13011        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13012        abstract int doPostInstall(int status, int uid);
13013
13014        /** @see PackageSettingBase#codePathString */
13015        abstract String getCodePath();
13016        /** @see PackageSettingBase#resourcePathString */
13017        abstract String getResourcePath();
13018
13019        // Need installer lock especially for dex file removal.
13020        abstract void cleanUpResourcesLI();
13021        abstract boolean doPostDeleteLI(boolean delete);
13022
13023        /**
13024         * Called before the source arguments are copied. This is used mostly
13025         * for MoveParams when it needs to read the source file to put it in the
13026         * destination.
13027         */
13028        int doPreCopy() {
13029            return PackageManager.INSTALL_SUCCEEDED;
13030        }
13031
13032        /**
13033         * Called after the source arguments are copied. This is used mostly for
13034         * MoveParams when it needs to read the source file to put it in the
13035         * destination.
13036         */
13037        int doPostCopy(int uid) {
13038            return PackageManager.INSTALL_SUCCEEDED;
13039        }
13040
13041        protected boolean isFwdLocked() {
13042            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13043        }
13044
13045        protected boolean isExternalAsec() {
13046            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13047        }
13048
13049        protected boolean isEphemeral() {
13050            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13051        }
13052
13053        UserHandle getUser() {
13054            return user;
13055        }
13056    }
13057
13058    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13059        if (!allCodePaths.isEmpty()) {
13060            if (instructionSets == null) {
13061                throw new IllegalStateException("instructionSet == null");
13062            }
13063            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13064            for (String codePath : allCodePaths) {
13065                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13066                    try {
13067                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13068                    } catch (InstallerException ignored) {
13069                    }
13070                }
13071            }
13072        }
13073    }
13074
13075    /**
13076     * Logic to handle installation of non-ASEC applications, including copying
13077     * and renaming logic.
13078     */
13079    class FileInstallArgs extends InstallArgs {
13080        private File codeFile;
13081        private File resourceFile;
13082
13083        // Example topology:
13084        // /data/app/com.example/base.apk
13085        // /data/app/com.example/split_foo.apk
13086        // /data/app/com.example/lib/arm/libfoo.so
13087        // /data/app/com.example/lib/arm64/libfoo.so
13088        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13089
13090        /** New install */
13091        FileInstallArgs(InstallParams params) {
13092            super(params.origin, params.move, params.observer, params.installFlags,
13093                    params.installerPackageName, params.volumeUuid,
13094                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13095                    params.grantedRuntimePermissions,
13096                    params.traceMethod, params.traceCookie, params.certificates);
13097            if (isFwdLocked()) {
13098                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13099            }
13100        }
13101
13102        /** Existing install */
13103        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13104            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13105                    null, null, null, 0, null /*certificates*/);
13106            this.codeFile = (codePath != null) ? new File(codePath) : null;
13107            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13108        }
13109
13110        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13111            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13112            try {
13113                return doCopyApk(imcs, temp);
13114            } finally {
13115                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13116            }
13117        }
13118
13119        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13120            if (origin.staged) {
13121                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13122                codeFile = origin.file;
13123                resourceFile = origin.file;
13124                return PackageManager.INSTALL_SUCCEEDED;
13125            }
13126
13127            try {
13128                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13129                final File tempDir =
13130                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13131                codeFile = tempDir;
13132                resourceFile = tempDir;
13133            } catch (IOException e) {
13134                Slog.w(TAG, "Failed to create copy file: " + e);
13135                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13136            }
13137
13138            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13139                @Override
13140                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13141                    if (!FileUtils.isValidExtFilename(name)) {
13142                        throw new IllegalArgumentException("Invalid filename: " + name);
13143                    }
13144                    try {
13145                        final File file = new File(codeFile, name);
13146                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13147                                O_RDWR | O_CREAT, 0644);
13148                        Os.chmod(file.getAbsolutePath(), 0644);
13149                        return new ParcelFileDescriptor(fd);
13150                    } catch (ErrnoException e) {
13151                        throw new RemoteException("Failed to open: " + e.getMessage());
13152                    }
13153                }
13154            };
13155
13156            int ret = PackageManager.INSTALL_SUCCEEDED;
13157            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13158            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13159                Slog.e(TAG, "Failed to copy package");
13160                return ret;
13161            }
13162
13163            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13164            NativeLibraryHelper.Handle handle = null;
13165            try {
13166                handle = NativeLibraryHelper.Handle.create(codeFile);
13167                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13168                        abiOverride);
13169            } catch (IOException e) {
13170                Slog.e(TAG, "Copying native libraries failed", e);
13171                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13172            } finally {
13173                IoUtils.closeQuietly(handle);
13174            }
13175
13176            return ret;
13177        }
13178
13179        int doPreInstall(int status) {
13180            if (status != PackageManager.INSTALL_SUCCEEDED) {
13181                cleanUp();
13182            }
13183            return status;
13184        }
13185
13186        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13187            if (status != PackageManager.INSTALL_SUCCEEDED) {
13188                cleanUp();
13189                return false;
13190            }
13191
13192            final File targetDir = codeFile.getParentFile();
13193            final File beforeCodeFile = codeFile;
13194            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13195
13196            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13197            try {
13198                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13199            } catch (ErrnoException e) {
13200                Slog.w(TAG, "Failed to rename", e);
13201                return false;
13202            }
13203
13204            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13205                Slog.w(TAG, "Failed to restorecon");
13206                return false;
13207            }
13208
13209            // Reflect the rename internally
13210            codeFile = afterCodeFile;
13211            resourceFile = afterCodeFile;
13212
13213            // Reflect the rename in scanned details
13214            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13215            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13216                    afterCodeFile, pkg.baseCodePath));
13217            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13218                    afterCodeFile, pkg.splitCodePaths));
13219
13220            // Reflect the rename in app info
13221            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13222            pkg.setApplicationInfoCodePath(pkg.codePath);
13223            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13224            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13225            pkg.setApplicationInfoResourcePath(pkg.codePath);
13226            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13227            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13228
13229            return true;
13230        }
13231
13232        int doPostInstall(int status, int uid) {
13233            if (status != PackageManager.INSTALL_SUCCEEDED) {
13234                cleanUp();
13235            }
13236            return status;
13237        }
13238
13239        @Override
13240        String getCodePath() {
13241            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13242        }
13243
13244        @Override
13245        String getResourcePath() {
13246            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13247        }
13248
13249        private boolean cleanUp() {
13250            if (codeFile == null || !codeFile.exists()) {
13251                return false;
13252            }
13253
13254            removeCodePathLI(codeFile);
13255
13256            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13257                resourceFile.delete();
13258            }
13259
13260            return true;
13261        }
13262
13263        void cleanUpResourcesLI() {
13264            // Try enumerating all code paths before deleting
13265            List<String> allCodePaths = Collections.EMPTY_LIST;
13266            if (codeFile != null && codeFile.exists()) {
13267                try {
13268                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13269                    allCodePaths = pkg.getAllCodePaths();
13270                } catch (PackageParserException e) {
13271                    // Ignored; we tried our best
13272                }
13273            }
13274
13275            cleanUp();
13276            removeDexFiles(allCodePaths, instructionSets);
13277        }
13278
13279        boolean doPostDeleteLI(boolean delete) {
13280            // XXX err, shouldn't we respect the delete flag?
13281            cleanUpResourcesLI();
13282            return true;
13283        }
13284    }
13285
13286    private boolean isAsecExternal(String cid) {
13287        final String asecPath = PackageHelper.getSdFilesystem(cid);
13288        return !asecPath.startsWith(mAsecInternalPath);
13289    }
13290
13291    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13292            PackageManagerException {
13293        if (copyRet < 0) {
13294            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13295                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13296                throw new PackageManagerException(copyRet, message);
13297            }
13298        }
13299    }
13300
13301    /**
13302     * Extract the MountService "container ID" from the full code path of an
13303     * .apk.
13304     */
13305    static String cidFromCodePath(String fullCodePath) {
13306        int eidx = fullCodePath.lastIndexOf("/");
13307        String subStr1 = fullCodePath.substring(0, eidx);
13308        int sidx = subStr1.lastIndexOf("/");
13309        return subStr1.substring(sidx+1, eidx);
13310    }
13311
13312    /**
13313     * Logic to handle installation of ASEC applications, including copying and
13314     * renaming logic.
13315     */
13316    class AsecInstallArgs extends InstallArgs {
13317        static final String RES_FILE_NAME = "pkg.apk";
13318        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13319
13320        String cid;
13321        String packagePath;
13322        String resourcePath;
13323
13324        /** New install */
13325        AsecInstallArgs(InstallParams params) {
13326            super(params.origin, params.move, params.observer, params.installFlags,
13327                    params.installerPackageName, params.volumeUuid,
13328                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13329                    params.grantedRuntimePermissions,
13330                    params.traceMethod, params.traceCookie, params.certificates);
13331        }
13332
13333        /** Existing install */
13334        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13335                        boolean isExternal, boolean isForwardLocked) {
13336            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13337              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13338                    instructionSets, null, null, null, 0, null /*certificates*/);
13339            // Hackily pretend we're still looking at a full code path
13340            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13341                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13342            }
13343
13344            // Extract cid from fullCodePath
13345            int eidx = fullCodePath.lastIndexOf("/");
13346            String subStr1 = fullCodePath.substring(0, eidx);
13347            int sidx = subStr1.lastIndexOf("/");
13348            cid = subStr1.substring(sidx+1, eidx);
13349            setMountPath(subStr1);
13350        }
13351
13352        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13353            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13354              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13355                    instructionSets, null, null, null, 0, null /*certificates*/);
13356            this.cid = cid;
13357            setMountPath(PackageHelper.getSdDir(cid));
13358        }
13359
13360        void createCopyFile() {
13361            cid = mInstallerService.allocateExternalStageCidLegacy();
13362        }
13363
13364        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13365            if (origin.staged && origin.cid != null) {
13366                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13367                cid = origin.cid;
13368                setMountPath(PackageHelper.getSdDir(cid));
13369                return PackageManager.INSTALL_SUCCEEDED;
13370            }
13371
13372            if (temp) {
13373                createCopyFile();
13374            } else {
13375                /*
13376                 * Pre-emptively destroy the container since it's destroyed if
13377                 * copying fails due to it existing anyway.
13378                 */
13379                PackageHelper.destroySdDir(cid);
13380            }
13381
13382            final String newMountPath = imcs.copyPackageToContainer(
13383                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13384                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13385
13386            if (newMountPath != null) {
13387                setMountPath(newMountPath);
13388                return PackageManager.INSTALL_SUCCEEDED;
13389            } else {
13390                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13391            }
13392        }
13393
13394        @Override
13395        String getCodePath() {
13396            return packagePath;
13397        }
13398
13399        @Override
13400        String getResourcePath() {
13401            return resourcePath;
13402        }
13403
13404        int doPreInstall(int status) {
13405            if (status != PackageManager.INSTALL_SUCCEEDED) {
13406                // Destroy container
13407                PackageHelper.destroySdDir(cid);
13408            } else {
13409                boolean mounted = PackageHelper.isContainerMounted(cid);
13410                if (!mounted) {
13411                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13412                            Process.SYSTEM_UID);
13413                    if (newMountPath != null) {
13414                        setMountPath(newMountPath);
13415                    } else {
13416                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13417                    }
13418                }
13419            }
13420            return status;
13421        }
13422
13423        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13424            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13425            String newMountPath = null;
13426            if (PackageHelper.isContainerMounted(cid)) {
13427                // Unmount the container
13428                if (!PackageHelper.unMountSdDir(cid)) {
13429                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13430                    return false;
13431                }
13432            }
13433            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13434                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13435                        " which might be stale. Will try to clean up.");
13436                // Clean up the stale container and proceed to recreate.
13437                if (!PackageHelper.destroySdDir(newCacheId)) {
13438                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13439                    return false;
13440                }
13441                // Successfully cleaned up stale container. Try to rename again.
13442                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13443                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13444                            + " inspite of cleaning it up.");
13445                    return false;
13446                }
13447            }
13448            if (!PackageHelper.isContainerMounted(newCacheId)) {
13449                Slog.w(TAG, "Mounting container " + newCacheId);
13450                newMountPath = PackageHelper.mountSdDir(newCacheId,
13451                        getEncryptKey(), Process.SYSTEM_UID);
13452            } else {
13453                newMountPath = PackageHelper.getSdDir(newCacheId);
13454            }
13455            if (newMountPath == null) {
13456                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13457                return false;
13458            }
13459            Log.i(TAG, "Succesfully renamed " + cid +
13460                    " to " + newCacheId +
13461                    " at new path: " + newMountPath);
13462            cid = newCacheId;
13463
13464            final File beforeCodeFile = new File(packagePath);
13465            setMountPath(newMountPath);
13466            final File afterCodeFile = new File(packagePath);
13467
13468            // Reflect the rename in scanned details
13469            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13470            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13471                    afterCodeFile, pkg.baseCodePath));
13472            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13473                    afterCodeFile, pkg.splitCodePaths));
13474
13475            // Reflect the rename in app info
13476            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13477            pkg.setApplicationInfoCodePath(pkg.codePath);
13478            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13479            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13480            pkg.setApplicationInfoResourcePath(pkg.codePath);
13481            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13482            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13483
13484            return true;
13485        }
13486
13487        private void setMountPath(String mountPath) {
13488            final File mountFile = new File(mountPath);
13489
13490            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13491            if (monolithicFile.exists()) {
13492                packagePath = monolithicFile.getAbsolutePath();
13493                if (isFwdLocked()) {
13494                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13495                } else {
13496                    resourcePath = packagePath;
13497                }
13498            } else {
13499                packagePath = mountFile.getAbsolutePath();
13500                resourcePath = packagePath;
13501            }
13502        }
13503
13504        int doPostInstall(int status, int uid) {
13505            if (status != PackageManager.INSTALL_SUCCEEDED) {
13506                cleanUp();
13507            } else {
13508                final int groupOwner;
13509                final String protectedFile;
13510                if (isFwdLocked()) {
13511                    groupOwner = UserHandle.getSharedAppGid(uid);
13512                    protectedFile = RES_FILE_NAME;
13513                } else {
13514                    groupOwner = -1;
13515                    protectedFile = null;
13516                }
13517
13518                if (uid < Process.FIRST_APPLICATION_UID
13519                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13520                    Slog.e(TAG, "Failed to finalize " + cid);
13521                    PackageHelper.destroySdDir(cid);
13522                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13523                }
13524
13525                boolean mounted = PackageHelper.isContainerMounted(cid);
13526                if (!mounted) {
13527                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13528                }
13529            }
13530            return status;
13531        }
13532
13533        private void cleanUp() {
13534            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13535
13536            // Destroy secure container
13537            PackageHelper.destroySdDir(cid);
13538        }
13539
13540        private List<String> getAllCodePaths() {
13541            final File codeFile = new File(getCodePath());
13542            if (codeFile != null && codeFile.exists()) {
13543                try {
13544                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13545                    return pkg.getAllCodePaths();
13546                } catch (PackageParserException e) {
13547                    // Ignored; we tried our best
13548                }
13549            }
13550            return Collections.EMPTY_LIST;
13551        }
13552
13553        void cleanUpResourcesLI() {
13554            // Enumerate all code paths before deleting
13555            cleanUpResourcesLI(getAllCodePaths());
13556        }
13557
13558        private void cleanUpResourcesLI(List<String> allCodePaths) {
13559            cleanUp();
13560            removeDexFiles(allCodePaths, instructionSets);
13561        }
13562
13563        String getPackageName() {
13564            return getAsecPackageName(cid);
13565        }
13566
13567        boolean doPostDeleteLI(boolean delete) {
13568            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13569            final List<String> allCodePaths = getAllCodePaths();
13570            boolean mounted = PackageHelper.isContainerMounted(cid);
13571            if (mounted) {
13572                // Unmount first
13573                if (PackageHelper.unMountSdDir(cid)) {
13574                    mounted = false;
13575                }
13576            }
13577            if (!mounted && delete) {
13578                cleanUpResourcesLI(allCodePaths);
13579            }
13580            return !mounted;
13581        }
13582
13583        @Override
13584        int doPreCopy() {
13585            if (isFwdLocked()) {
13586                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13587                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13588                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13589                }
13590            }
13591
13592            return PackageManager.INSTALL_SUCCEEDED;
13593        }
13594
13595        @Override
13596        int doPostCopy(int uid) {
13597            if (isFwdLocked()) {
13598                if (uid < Process.FIRST_APPLICATION_UID
13599                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13600                                RES_FILE_NAME)) {
13601                    Slog.e(TAG, "Failed to finalize " + cid);
13602                    PackageHelper.destroySdDir(cid);
13603                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13604                }
13605            }
13606
13607            return PackageManager.INSTALL_SUCCEEDED;
13608        }
13609    }
13610
13611    /**
13612     * Logic to handle movement of existing installed applications.
13613     */
13614    class MoveInstallArgs extends InstallArgs {
13615        private File codeFile;
13616        private File resourceFile;
13617
13618        /** New install */
13619        MoveInstallArgs(InstallParams params) {
13620            super(params.origin, params.move, params.observer, params.installFlags,
13621                    params.installerPackageName, params.volumeUuid,
13622                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13623                    params.grantedRuntimePermissions,
13624                    params.traceMethod, params.traceCookie, params.certificates);
13625        }
13626
13627        int copyApk(IMediaContainerService imcs, boolean temp) {
13628            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13629                    + move.fromUuid + " to " + move.toUuid);
13630            synchronized (mInstaller) {
13631                try {
13632                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13633                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13634                } catch (InstallerException e) {
13635                    Slog.w(TAG, "Failed to move app", e);
13636                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13637                }
13638            }
13639
13640            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13641            resourceFile = codeFile;
13642            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13643
13644            return PackageManager.INSTALL_SUCCEEDED;
13645        }
13646
13647        int doPreInstall(int status) {
13648            if (status != PackageManager.INSTALL_SUCCEEDED) {
13649                cleanUp(move.toUuid);
13650            }
13651            return status;
13652        }
13653
13654        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13655            if (status != PackageManager.INSTALL_SUCCEEDED) {
13656                cleanUp(move.toUuid);
13657                return false;
13658            }
13659
13660            // Reflect the move in app info
13661            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13662            pkg.setApplicationInfoCodePath(pkg.codePath);
13663            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13664            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13665            pkg.setApplicationInfoResourcePath(pkg.codePath);
13666            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13667            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13668
13669            return true;
13670        }
13671
13672        int doPostInstall(int status, int uid) {
13673            if (status == PackageManager.INSTALL_SUCCEEDED) {
13674                cleanUp(move.fromUuid);
13675            } else {
13676                cleanUp(move.toUuid);
13677            }
13678            return status;
13679        }
13680
13681        @Override
13682        String getCodePath() {
13683            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13684        }
13685
13686        @Override
13687        String getResourcePath() {
13688            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13689        }
13690
13691        private boolean cleanUp(String volumeUuid) {
13692            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13693                    move.dataAppName);
13694            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13695            final int[] userIds = sUserManager.getUserIds();
13696            synchronized (mInstallLock) {
13697                // Clean up both app data and code
13698                // All package moves are frozen until finished
13699                for (int userId : userIds) {
13700                    try {
13701                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13702                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13703                    } catch (InstallerException e) {
13704                        Slog.w(TAG, String.valueOf(e));
13705                    }
13706                }
13707                removeCodePathLI(codeFile);
13708            }
13709            return true;
13710        }
13711
13712        void cleanUpResourcesLI() {
13713            throw new UnsupportedOperationException();
13714        }
13715
13716        boolean doPostDeleteLI(boolean delete) {
13717            throw new UnsupportedOperationException();
13718        }
13719    }
13720
13721    static String getAsecPackageName(String packageCid) {
13722        int idx = packageCid.lastIndexOf("-");
13723        if (idx == -1) {
13724            return packageCid;
13725        }
13726        return packageCid.substring(0, idx);
13727    }
13728
13729    // Utility method used to create code paths based on package name and available index.
13730    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13731        String idxStr = "";
13732        int idx = 1;
13733        // Fall back to default value of idx=1 if prefix is not
13734        // part of oldCodePath
13735        if (oldCodePath != null) {
13736            String subStr = oldCodePath;
13737            // Drop the suffix right away
13738            if (suffix != null && subStr.endsWith(suffix)) {
13739                subStr = subStr.substring(0, subStr.length() - suffix.length());
13740            }
13741            // If oldCodePath already contains prefix find out the
13742            // ending index to either increment or decrement.
13743            int sidx = subStr.lastIndexOf(prefix);
13744            if (sidx != -1) {
13745                subStr = subStr.substring(sidx + prefix.length());
13746                if (subStr != null) {
13747                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13748                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13749                    }
13750                    try {
13751                        idx = Integer.parseInt(subStr);
13752                        if (idx <= 1) {
13753                            idx++;
13754                        } else {
13755                            idx--;
13756                        }
13757                    } catch(NumberFormatException e) {
13758                    }
13759                }
13760            }
13761        }
13762        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13763        return prefix + idxStr;
13764    }
13765
13766    private File getNextCodePath(File targetDir, String packageName) {
13767        int suffix = 1;
13768        File result;
13769        do {
13770            result = new File(targetDir, packageName + "-" + suffix);
13771            suffix++;
13772        } while (result.exists());
13773        return result;
13774    }
13775
13776    // Utility method that returns the relative package path with respect
13777    // to the installation directory. Like say for /data/data/com.test-1.apk
13778    // string com.test-1 is returned.
13779    static String deriveCodePathName(String codePath) {
13780        if (codePath == null) {
13781            return null;
13782        }
13783        final File codeFile = new File(codePath);
13784        final String name = codeFile.getName();
13785        if (codeFile.isDirectory()) {
13786            return name;
13787        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13788            final int lastDot = name.lastIndexOf('.');
13789            return name.substring(0, lastDot);
13790        } else {
13791            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13792            return null;
13793        }
13794    }
13795
13796    static class PackageInstalledInfo {
13797        String name;
13798        int uid;
13799        // The set of users that originally had this package installed.
13800        int[] origUsers;
13801        // The set of users that now have this package installed.
13802        int[] newUsers;
13803        PackageParser.Package pkg;
13804        int returnCode;
13805        String returnMsg;
13806        PackageRemovedInfo removedInfo;
13807        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13808
13809        public void setError(int code, String msg) {
13810            setReturnCode(code);
13811            setReturnMessage(msg);
13812            Slog.w(TAG, msg);
13813        }
13814
13815        public void setError(String msg, PackageParserException e) {
13816            setReturnCode(e.error);
13817            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13818            Slog.w(TAG, msg, e);
13819        }
13820
13821        public void setError(String msg, PackageManagerException e) {
13822            returnCode = e.error;
13823            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13824            Slog.w(TAG, msg, e);
13825        }
13826
13827        public void setReturnCode(int returnCode) {
13828            this.returnCode = returnCode;
13829            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13830            for (int i = 0; i < childCount; i++) {
13831                addedChildPackages.valueAt(i).returnCode = returnCode;
13832            }
13833        }
13834
13835        private void setReturnMessage(String returnMsg) {
13836            this.returnMsg = returnMsg;
13837            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13838            for (int i = 0; i < childCount; i++) {
13839                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13840            }
13841        }
13842
13843        // In some error cases we want to convey more info back to the observer
13844        String origPackage;
13845        String origPermission;
13846    }
13847
13848    /*
13849     * Install a non-existing package.
13850     */
13851    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13852            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13853            PackageInstalledInfo res) {
13854        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13855
13856        // Remember this for later, in case we need to rollback this install
13857        String pkgName = pkg.packageName;
13858
13859        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13860
13861        synchronized(mPackages) {
13862            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13863                // A package with the same name is already installed, though
13864                // it has been renamed to an older name.  The package we
13865                // are trying to install should be installed as an update to
13866                // the existing one, but that has not been requested, so bail.
13867                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13868                        + " without first uninstalling package running as "
13869                        + mSettings.mRenamedPackages.get(pkgName));
13870                return;
13871            }
13872            if (mPackages.containsKey(pkgName)) {
13873                // Don't allow installation over an existing package with the same name.
13874                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13875                        + " without first uninstalling.");
13876                return;
13877            }
13878        }
13879
13880        try {
13881            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13882                    System.currentTimeMillis(), user);
13883
13884            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13885
13886            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13887                prepareAppDataAfterInstallLIF(newPackage);
13888
13889            } else {
13890                // Remove package from internal structures, but keep around any
13891                // data that might have already existed
13892                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13893                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13894            }
13895        } catch (PackageManagerException e) {
13896            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13897        }
13898
13899        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13900    }
13901
13902    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13903        // Can't rotate keys during boot or if sharedUser.
13904        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13905                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13906            return false;
13907        }
13908        // app is using upgradeKeySets; make sure all are valid
13909        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13910        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13911        for (int i = 0; i < upgradeKeySets.length; i++) {
13912            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13913                Slog.wtf(TAG, "Package "
13914                         + (oldPs.name != null ? oldPs.name : "<null>")
13915                         + " contains upgrade-key-set reference to unknown key-set: "
13916                         + upgradeKeySets[i]
13917                         + " reverting to signatures check.");
13918                return false;
13919            }
13920        }
13921        return true;
13922    }
13923
13924    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13925        // Upgrade keysets are being used.  Determine if new package has a superset of the
13926        // required keys.
13927        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13928        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13929        for (int i = 0; i < upgradeKeySets.length; i++) {
13930            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13931            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13932                return true;
13933            }
13934        }
13935        return false;
13936    }
13937
13938    private static void updateDigest(MessageDigest digest, File file) throws IOException {
13939        try (DigestInputStream digestStream =
13940                new DigestInputStream(new FileInputStream(file), digest)) {
13941            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
13942        }
13943    }
13944
13945    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13946            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13947        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13948
13949        final PackageParser.Package oldPackage;
13950        final String pkgName = pkg.packageName;
13951        final int[] allUsers;
13952        final int[] installedUsers;
13953
13954        synchronized(mPackages) {
13955            oldPackage = mPackages.get(pkgName);
13956            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13957
13958            // don't allow upgrade to target a release SDK from a pre-release SDK
13959            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13960                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13961            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13962                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13963            if (oldTargetsPreRelease
13964                    && !newTargetsPreRelease
13965                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13966                Slog.w(TAG, "Can't install package targeting released sdk");
13967                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13968                return;
13969            }
13970
13971            // don't allow an upgrade from full to ephemeral
13972            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13973            if (isEphemeral && !oldIsEphemeral) {
13974                // can't downgrade from full to ephemeral
13975                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13976                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13977                return;
13978            }
13979
13980            // verify signatures are valid
13981            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13982            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13983                if (!checkUpgradeKeySetLP(ps, pkg)) {
13984                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13985                            "New package not signed by keys specified by upgrade-keysets: "
13986                                    + pkgName);
13987                    return;
13988                }
13989            } else {
13990                // default to original signature matching
13991                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13992                        != PackageManager.SIGNATURE_MATCH) {
13993                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13994                            "New package has a different signature: " + pkgName);
13995                    return;
13996                }
13997            }
13998
13999            // don't allow a system upgrade unless the upgrade hash matches
14000            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14001                byte[] digestBytes = null;
14002                try {
14003                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14004                    updateDigest(digest, new File(pkg.baseCodePath));
14005                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14006                        for (String path : pkg.splitCodePaths) {
14007                            updateDigest(digest, new File(path));
14008                        }
14009                    }
14010                    digestBytes = digest.digest();
14011                } catch (NoSuchAlgorithmException | IOException e) {
14012                    res.setError(INSTALL_FAILED_INVALID_APK,
14013                            "Could not compute hash: " + pkgName);
14014                    return;
14015                }
14016                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14017                    res.setError(INSTALL_FAILED_INVALID_APK,
14018                            "New package fails restrict-update check: " + pkgName);
14019                    return;
14020                }
14021                // retain upgrade restriction
14022                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14023            }
14024
14025            // Check for shared user id changes
14026            String invalidPackageName =
14027                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14028            if (invalidPackageName != null) {
14029                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14030                        "Package " + invalidPackageName + " tried to change user "
14031                                + oldPackage.mSharedUserId);
14032                return;
14033            }
14034
14035            // In case of rollback, remember per-user/profile install state
14036            allUsers = sUserManager.getUserIds();
14037            installedUsers = ps.queryInstalledUsers(allUsers, true);
14038        }
14039
14040        // Update what is removed
14041        res.removedInfo = new PackageRemovedInfo();
14042        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14043        res.removedInfo.removedPackage = oldPackage.packageName;
14044        res.removedInfo.isUpdate = true;
14045        res.removedInfo.origUsers = installedUsers;
14046        final int childCount = (oldPackage.childPackages != null)
14047                ? oldPackage.childPackages.size() : 0;
14048        for (int i = 0; i < childCount; i++) {
14049            boolean childPackageUpdated = false;
14050            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14051            if (res.addedChildPackages != null) {
14052                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14053                if (childRes != null) {
14054                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14055                    childRes.removedInfo.removedPackage = childPkg.packageName;
14056                    childRes.removedInfo.isUpdate = true;
14057                    childPackageUpdated = true;
14058                }
14059            }
14060            if (!childPackageUpdated) {
14061                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14062                childRemovedRes.removedPackage = childPkg.packageName;
14063                childRemovedRes.isUpdate = false;
14064                childRemovedRes.dataRemoved = true;
14065                synchronized (mPackages) {
14066                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14067                    if (childPs != null) {
14068                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14069                    }
14070                }
14071                if (res.removedInfo.removedChildPackages == null) {
14072                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14073                }
14074                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14075            }
14076        }
14077
14078        boolean sysPkg = (isSystemApp(oldPackage));
14079        if (sysPkg) {
14080            // Set the system/privileged flags as needed
14081            final boolean privileged =
14082                    (oldPackage.applicationInfo.privateFlags
14083                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14084            final int systemPolicyFlags = policyFlags
14085                    | PackageParser.PARSE_IS_SYSTEM
14086                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14087
14088            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14089                    user, allUsers, installerPackageName, res);
14090        } else {
14091            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14092                    user, allUsers, installerPackageName, res);
14093        }
14094    }
14095
14096    public List<String> getPreviousCodePaths(String packageName) {
14097        final PackageSetting ps = mSettings.mPackages.get(packageName);
14098        final List<String> result = new ArrayList<String>();
14099        if (ps != null && ps.oldCodePaths != null) {
14100            result.addAll(ps.oldCodePaths);
14101        }
14102        return result;
14103    }
14104
14105    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14106            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14107            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14108        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14109                + deletedPackage);
14110
14111        String pkgName = deletedPackage.packageName;
14112        boolean deletedPkg = true;
14113        boolean addedPkg = false;
14114        boolean updatedSettings = false;
14115        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14116        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14117                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14118
14119        final long origUpdateTime = (pkg.mExtras != null)
14120                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14121
14122        // First delete the existing package while retaining the data directory
14123        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14124                res.removedInfo, true, pkg)) {
14125            // If the existing package wasn't successfully deleted
14126            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14127            deletedPkg = false;
14128        } else {
14129            // Successfully deleted the old package; proceed with replace.
14130
14131            // If deleted package lived in a container, give users a chance to
14132            // relinquish resources before killing.
14133            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14134                if (DEBUG_INSTALL) {
14135                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14136                }
14137                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14138                final ArrayList<String> pkgList = new ArrayList<String>(1);
14139                pkgList.add(deletedPackage.applicationInfo.packageName);
14140                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14141            }
14142
14143            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14144                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14145            clearAppProfilesLIF(pkg);
14146
14147            try {
14148                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14149                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14150                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14151
14152                // Update the in-memory copy of the previous code paths.
14153                PackageSetting ps = mSettings.mPackages.get(pkgName);
14154                if (!killApp) {
14155                    if (ps.oldCodePaths == null) {
14156                        ps.oldCodePaths = new ArraySet<>();
14157                    }
14158                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14159                    if (deletedPackage.splitCodePaths != null) {
14160                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14161                    }
14162                } else {
14163                    ps.oldCodePaths = null;
14164                }
14165                if (ps.childPackageNames != null) {
14166                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14167                        final String childPkgName = ps.childPackageNames.get(i);
14168                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14169                        childPs.oldCodePaths = ps.oldCodePaths;
14170                    }
14171                }
14172                prepareAppDataAfterInstallLIF(newPackage);
14173                addedPkg = true;
14174            } catch (PackageManagerException e) {
14175                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14176            }
14177        }
14178
14179        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14180            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14181
14182            // Revert all internal state mutations and added folders for the failed install
14183            if (addedPkg) {
14184                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14185                        res.removedInfo, true, null);
14186            }
14187
14188            // Restore the old package
14189            if (deletedPkg) {
14190                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14191                File restoreFile = new File(deletedPackage.codePath);
14192                // Parse old package
14193                boolean oldExternal = isExternal(deletedPackage);
14194                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14195                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14196                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14197                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14198                try {
14199                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14200                            null);
14201                } catch (PackageManagerException e) {
14202                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14203                            + e.getMessage());
14204                    return;
14205                }
14206
14207                synchronized (mPackages) {
14208                    // Ensure the installer package name up to date
14209                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14210
14211                    // Update permissions for restored package
14212                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14213
14214                    mSettings.writeLPr();
14215                }
14216
14217                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14218            }
14219        } else {
14220            synchronized (mPackages) {
14221                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14222                if (ps != null) {
14223                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14224                    if (res.removedInfo.removedChildPackages != null) {
14225                        final int childCount = res.removedInfo.removedChildPackages.size();
14226                        // Iterate in reverse as we may modify the collection
14227                        for (int i = childCount - 1; i >= 0; i--) {
14228                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14229                            if (res.addedChildPackages.containsKey(childPackageName)) {
14230                                res.removedInfo.removedChildPackages.removeAt(i);
14231                            } else {
14232                                PackageRemovedInfo childInfo = res.removedInfo
14233                                        .removedChildPackages.valueAt(i);
14234                                childInfo.removedForAllUsers = mPackages.get(
14235                                        childInfo.removedPackage) == null;
14236                            }
14237                        }
14238                    }
14239                }
14240            }
14241        }
14242    }
14243
14244    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14245            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14246            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14247        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14248                + ", old=" + deletedPackage);
14249
14250        final boolean disabledSystem;
14251
14252        // Remove existing system package
14253        removePackageLI(deletedPackage, true);
14254
14255        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14256        if (!disabledSystem) {
14257            // We didn't need to disable the .apk as a current system package,
14258            // which means we are replacing another update that is already
14259            // installed.  We need to make sure to delete the older one's .apk.
14260            res.removedInfo.args = createInstallArgsForExisting(0,
14261                    deletedPackage.applicationInfo.getCodePath(),
14262                    deletedPackage.applicationInfo.getResourcePath(),
14263                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14264        } else {
14265            res.removedInfo.args = null;
14266        }
14267
14268        // Successfully disabled the old package. Now proceed with re-installation
14269        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14270                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14271        clearAppProfilesLIF(pkg);
14272
14273        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14274        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14275                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14276
14277        PackageParser.Package newPackage = null;
14278        try {
14279            // Add the package to the internal data structures
14280            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14281
14282            // Set the update and install times
14283            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14284            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14285                    System.currentTimeMillis());
14286
14287            // Update the package dynamic state if succeeded
14288            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14289                // Now that the install succeeded make sure we remove data
14290                // directories for any child package the update removed.
14291                final int deletedChildCount = (deletedPackage.childPackages != null)
14292                        ? deletedPackage.childPackages.size() : 0;
14293                final int newChildCount = (newPackage.childPackages != null)
14294                        ? newPackage.childPackages.size() : 0;
14295                for (int i = 0; i < deletedChildCount; i++) {
14296                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14297                    boolean childPackageDeleted = true;
14298                    for (int j = 0; j < newChildCount; j++) {
14299                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14300                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14301                            childPackageDeleted = false;
14302                            break;
14303                        }
14304                    }
14305                    if (childPackageDeleted) {
14306                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14307                                deletedChildPkg.packageName);
14308                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14309                            PackageRemovedInfo removedChildRes = res.removedInfo
14310                                    .removedChildPackages.get(deletedChildPkg.packageName);
14311                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14312                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14313                        }
14314                    }
14315                }
14316
14317                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14318                prepareAppDataAfterInstallLIF(newPackage);
14319            }
14320        } catch (PackageManagerException e) {
14321            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14322            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14323        }
14324
14325        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14326            // Re installation failed. Restore old information
14327            // Remove new pkg information
14328            if (newPackage != null) {
14329                removeInstalledPackageLI(newPackage, true);
14330            }
14331            // Add back the old system package
14332            try {
14333                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14334            } catch (PackageManagerException e) {
14335                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14336            }
14337
14338            synchronized (mPackages) {
14339                if (disabledSystem) {
14340                    enableSystemPackageLPw(deletedPackage);
14341                }
14342
14343                // Ensure the installer package name up to date
14344                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14345
14346                // Update permissions for restored package
14347                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14348
14349                mSettings.writeLPr();
14350            }
14351
14352            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14353                    + " after failed upgrade");
14354        }
14355    }
14356
14357    /**
14358     * Checks whether the parent or any of the child packages have a change shared
14359     * user. For a package to be a valid update the shred users of the parent and
14360     * the children should match. We may later support changing child shared users.
14361     * @param oldPkg The updated package.
14362     * @param newPkg The update package.
14363     * @return The shared user that change between the versions.
14364     */
14365    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14366            PackageParser.Package newPkg) {
14367        // Check parent shared user
14368        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14369            return newPkg.packageName;
14370        }
14371        // Check child shared users
14372        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14373        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14374        for (int i = 0; i < newChildCount; i++) {
14375            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14376            // If this child was present, did it have the same shared user?
14377            for (int j = 0; j < oldChildCount; j++) {
14378                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14379                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14380                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14381                    return newChildPkg.packageName;
14382                }
14383            }
14384        }
14385        return null;
14386    }
14387
14388    private void removeNativeBinariesLI(PackageSetting ps) {
14389        // Remove the lib path for the parent package
14390        if (ps != null) {
14391            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14392            // Remove the lib path for the child packages
14393            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14394            for (int i = 0; i < childCount; i++) {
14395                PackageSetting childPs = null;
14396                synchronized (mPackages) {
14397                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14398                }
14399                if (childPs != null) {
14400                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14401                            .legacyNativeLibraryPathString);
14402                }
14403            }
14404        }
14405    }
14406
14407    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14408        // Enable the parent package
14409        mSettings.enableSystemPackageLPw(pkg.packageName);
14410        // Enable the child packages
14411        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14412        for (int i = 0; i < childCount; i++) {
14413            PackageParser.Package childPkg = pkg.childPackages.get(i);
14414            mSettings.enableSystemPackageLPw(childPkg.packageName);
14415        }
14416    }
14417
14418    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14419            PackageParser.Package newPkg) {
14420        // Disable the parent package (parent always replaced)
14421        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14422        // Disable the child packages
14423        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14424        for (int i = 0; i < childCount; i++) {
14425            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14426            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14427            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14428        }
14429        return disabled;
14430    }
14431
14432    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14433            String installerPackageName) {
14434        // Enable the parent package
14435        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14436        // Enable the child packages
14437        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14438        for (int i = 0; i < childCount; i++) {
14439            PackageParser.Package childPkg = pkg.childPackages.get(i);
14440            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14441        }
14442    }
14443
14444    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14445        // Collect all used permissions in the UID
14446        ArraySet<String> usedPermissions = new ArraySet<>();
14447        final int packageCount = su.packages.size();
14448        for (int i = 0; i < packageCount; i++) {
14449            PackageSetting ps = su.packages.valueAt(i);
14450            if (ps.pkg == null) {
14451                continue;
14452            }
14453            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14454            for (int j = 0; j < requestedPermCount; j++) {
14455                String permission = ps.pkg.requestedPermissions.get(j);
14456                BasePermission bp = mSettings.mPermissions.get(permission);
14457                if (bp != null) {
14458                    usedPermissions.add(permission);
14459                }
14460            }
14461        }
14462
14463        PermissionsState permissionsState = su.getPermissionsState();
14464        // Prune install permissions
14465        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14466        final int installPermCount = installPermStates.size();
14467        for (int i = installPermCount - 1; i >= 0;  i--) {
14468            PermissionState permissionState = installPermStates.get(i);
14469            if (!usedPermissions.contains(permissionState.getName())) {
14470                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14471                if (bp != null) {
14472                    permissionsState.revokeInstallPermission(bp);
14473                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14474                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14475                }
14476            }
14477        }
14478
14479        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14480
14481        // Prune runtime permissions
14482        for (int userId : allUserIds) {
14483            List<PermissionState> runtimePermStates = permissionsState
14484                    .getRuntimePermissionStates(userId);
14485            final int runtimePermCount = runtimePermStates.size();
14486            for (int i = runtimePermCount - 1; i >= 0; i--) {
14487                PermissionState permissionState = runtimePermStates.get(i);
14488                if (!usedPermissions.contains(permissionState.getName())) {
14489                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14490                    if (bp != null) {
14491                        permissionsState.revokeRuntimePermission(bp, userId);
14492                        permissionsState.updatePermissionFlags(bp, userId,
14493                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14494                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14495                                runtimePermissionChangedUserIds, userId);
14496                    }
14497                }
14498            }
14499        }
14500
14501        return runtimePermissionChangedUserIds;
14502    }
14503
14504    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14505            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14506        // Update the parent package setting
14507        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14508                res, user);
14509        // Update the child packages setting
14510        final int childCount = (newPackage.childPackages != null)
14511                ? newPackage.childPackages.size() : 0;
14512        for (int i = 0; i < childCount; i++) {
14513            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14514            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14515            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14516                    childRes.origUsers, childRes, user);
14517        }
14518    }
14519
14520    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14521            String installerPackageName, int[] allUsers, int[] installedForUsers,
14522            PackageInstalledInfo res, UserHandle user) {
14523        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14524
14525        String pkgName = newPackage.packageName;
14526        synchronized (mPackages) {
14527            //write settings. the installStatus will be incomplete at this stage.
14528            //note that the new package setting would have already been
14529            //added to mPackages. It hasn't been persisted yet.
14530            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14531            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14532            mSettings.writeLPr();
14533            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14534        }
14535
14536        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14537        synchronized (mPackages) {
14538            updatePermissionsLPw(newPackage.packageName, newPackage,
14539                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14540                            ? UPDATE_PERMISSIONS_ALL : 0));
14541            // For system-bundled packages, we assume that installing an upgraded version
14542            // of the package implies that the user actually wants to run that new code,
14543            // so we enable the package.
14544            PackageSetting ps = mSettings.mPackages.get(pkgName);
14545            final int userId = user.getIdentifier();
14546            if (ps != null) {
14547                if (isSystemApp(newPackage)) {
14548                    if (DEBUG_INSTALL) {
14549                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14550                    }
14551                    // Enable system package for requested users
14552                    if (res.origUsers != null) {
14553                        for (int origUserId : res.origUsers) {
14554                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14555                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14556                                        origUserId, installerPackageName);
14557                            }
14558                        }
14559                    }
14560                    // Also convey the prior install/uninstall state
14561                    if (allUsers != null && installedForUsers != null) {
14562                        for (int currentUserId : allUsers) {
14563                            final boolean installed = ArrayUtils.contains(
14564                                    installedForUsers, currentUserId);
14565                            if (DEBUG_INSTALL) {
14566                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14567                            }
14568                            ps.setInstalled(installed, currentUserId);
14569                        }
14570                        // these install state changes will be persisted in the
14571                        // upcoming call to mSettings.writeLPr().
14572                    }
14573                }
14574                // It's implied that when a user requests installation, they want the app to be
14575                // installed and enabled.
14576                if (userId != UserHandle.USER_ALL) {
14577                    ps.setInstalled(true, userId);
14578                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14579                }
14580            }
14581            res.name = pkgName;
14582            res.uid = newPackage.applicationInfo.uid;
14583            res.pkg = newPackage;
14584            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14585            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14586            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14587            //to update install status
14588            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14589            mSettings.writeLPr();
14590            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14591        }
14592
14593        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14594    }
14595
14596    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14597        try {
14598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14599            installPackageLI(args, res);
14600        } finally {
14601            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14602        }
14603    }
14604
14605    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14606        final int installFlags = args.installFlags;
14607        final String installerPackageName = args.installerPackageName;
14608        final String volumeUuid = args.volumeUuid;
14609        final File tmpPackageFile = new File(args.getCodePath());
14610        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14611        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14612                || (args.volumeUuid != null));
14613        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14614        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14615        boolean replace = false;
14616        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14617        if (args.move != null) {
14618            // moving a complete application; perform an initial scan on the new install location
14619            scanFlags |= SCAN_INITIAL;
14620        }
14621        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14622            scanFlags |= SCAN_DONT_KILL_APP;
14623        }
14624
14625        // Result object to be returned
14626        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14627
14628        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14629
14630        // Sanity check
14631        if (ephemeral && (forwardLocked || onExternal)) {
14632            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14633                    + " external=" + onExternal);
14634            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14635            return;
14636        }
14637
14638        // Retrieve PackageSettings and parse package
14639        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14640                | PackageParser.PARSE_ENFORCE_CODE
14641                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14642                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14643                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14644                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14645        PackageParser pp = new PackageParser();
14646        pp.setSeparateProcesses(mSeparateProcesses);
14647        pp.setDisplayMetrics(mMetrics);
14648
14649        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14650        final PackageParser.Package pkg;
14651        try {
14652            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14653        } catch (PackageParserException e) {
14654            res.setError("Failed parse during installPackageLI", e);
14655            return;
14656        } finally {
14657            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14658        }
14659
14660        // If we are installing a clustered package add results for the children
14661        if (pkg.childPackages != null) {
14662            synchronized (mPackages) {
14663                final int childCount = pkg.childPackages.size();
14664                for (int i = 0; i < childCount; i++) {
14665                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14666                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14667                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14668                    childRes.pkg = childPkg;
14669                    childRes.name = childPkg.packageName;
14670                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14671                    if (childPs != null) {
14672                        childRes.origUsers = childPs.queryInstalledUsers(
14673                                sUserManager.getUserIds(), true);
14674                    }
14675                    if ((mPackages.containsKey(childPkg.packageName))) {
14676                        childRes.removedInfo = new PackageRemovedInfo();
14677                        childRes.removedInfo.removedPackage = childPkg.packageName;
14678                    }
14679                    if (res.addedChildPackages == null) {
14680                        res.addedChildPackages = new ArrayMap<>();
14681                    }
14682                    res.addedChildPackages.put(childPkg.packageName, childRes);
14683                }
14684            }
14685        }
14686
14687        // If package doesn't declare API override, mark that we have an install
14688        // time CPU ABI override.
14689        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14690            pkg.cpuAbiOverride = args.abiOverride;
14691        }
14692
14693        String pkgName = res.name = pkg.packageName;
14694        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14695            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14696                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14697                return;
14698            }
14699        }
14700
14701        try {
14702            // either use what we've been given or parse directly from the APK
14703            if (args.certificates != null) {
14704                try {
14705                    PackageParser.populateCertificates(pkg, args.certificates);
14706                } catch (PackageParserException e) {
14707                    // there was something wrong with the certificates we were given;
14708                    // try to pull them from the APK
14709                    PackageParser.collectCertificates(pkg, parseFlags);
14710                }
14711            } else {
14712                PackageParser.collectCertificates(pkg, parseFlags);
14713            }
14714        } catch (PackageParserException e) {
14715            res.setError("Failed collect during installPackageLI", e);
14716            return;
14717        }
14718
14719        // Get rid of all references to package scan path via parser.
14720        pp = null;
14721        String oldCodePath = null;
14722        boolean systemApp = false;
14723        synchronized (mPackages) {
14724            // Check if installing already existing package
14725            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14726                String oldName = mSettings.mRenamedPackages.get(pkgName);
14727                if (pkg.mOriginalPackages != null
14728                        && pkg.mOriginalPackages.contains(oldName)
14729                        && mPackages.containsKey(oldName)) {
14730                    // This package is derived from an original package,
14731                    // and this device has been updating from that original
14732                    // name.  We must continue using the original name, so
14733                    // rename the new package here.
14734                    pkg.setPackageName(oldName);
14735                    pkgName = pkg.packageName;
14736                    replace = true;
14737                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14738                            + oldName + " pkgName=" + pkgName);
14739                } else if (mPackages.containsKey(pkgName)) {
14740                    // This package, under its official name, already exists
14741                    // on the device; we should replace it.
14742                    replace = true;
14743                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14744                }
14745
14746                // Child packages are installed through the parent package
14747                if (pkg.parentPackage != null) {
14748                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14749                            "Package " + pkg.packageName + " is child of package "
14750                                    + pkg.parentPackage.parentPackage + ". Child packages "
14751                                    + "can be updated only through the parent package.");
14752                    return;
14753                }
14754
14755                if (replace) {
14756                    // Prevent apps opting out from runtime permissions
14757                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14758                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14759                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14760                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14761                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14762                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14763                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14764                                        + " doesn't support runtime permissions but the old"
14765                                        + " target SDK " + oldTargetSdk + " does.");
14766                        return;
14767                    }
14768
14769                    // Prevent installing of child packages
14770                    if (oldPackage.parentPackage != null) {
14771                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14772                                "Package " + pkg.packageName + " is child of package "
14773                                        + oldPackage.parentPackage + ". Child packages "
14774                                        + "can be updated only through the parent package.");
14775                        return;
14776                    }
14777                }
14778            }
14779
14780            PackageSetting ps = mSettings.mPackages.get(pkgName);
14781            if (ps != null) {
14782                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14783
14784                // Quick sanity check that we're signed correctly if updating;
14785                // we'll check this again later when scanning, but we want to
14786                // bail early here before tripping over redefined permissions.
14787                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14788                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14789                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14790                                + pkg.packageName + " upgrade keys do not match the "
14791                                + "previously installed version");
14792                        return;
14793                    }
14794                } else {
14795                    try {
14796                        verifySignaturesLP(ps, pkg);
14797                    } catch (PackageManagerException e) {
14798                        res.setError(e.error, e.getMessage());
14799                        return;
14800                    }
14801                }
14802
14803                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14804                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14805                    systemApp = (ps.pkg.applicationInfo.flags &
14806                            ApplicationInfo.FLAG_SYSTEM) != 0;
14807                }
14808                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14809            }
14810
14811            // Check whether the newly-scanned package wants to define an already-defined perm
14812            int N = pkg.permissions.size();
14813            for (int i = N-1; i >= 0; i--) {
14814                PackageParser.Permission perm = pkg.permissions.get(i);
14815                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14816                if (bp != null) {
14817                    // If the defining package is signed with our cert, it's okay.  This
14818                    // also includes the "updating the same package" case, of course.
14819                    // "updating same package" could also involve key-rotation.
14820                    final boolean sigsOk;
14821                    if (bp.sourcePackage.equals(pkg.packageName)
14822                            && (bp.packageSetting instanceof PackageSetting)
14823                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14824                                    scanFlags))) {
14825                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14826                    } else {
14827                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14828                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14829                    }
14830                    if (!sigsOk) {
14831                        // If the owning package is the system itself, we log but allow
14832                        // install to proceed; we fail the install on all other permission
14833                        // redefinitions.
14834                        if (!bp.sourcePackage.equals("android")) {
14835                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14836                                    + pkg.packageName + " attempting to redeclare permission "
14837                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14838                            res.origPermission = perm.info.name;
14839                            res.origPackage = bp.sourcePackage;
14840                            return;
14841                        } else {
14842                            Slog.w(TAG, "Package " + pkg.packageName
14843                                    + " attempting to redeclare system permission "
14844                                    + perm.info.name + "; ignoring new declaration");
14845                            pkg.permissions.remove(i);
14846                        }
14847                    }
14848                }
14849            }
14850        }
14851
14852        if (systemApp) {
14853            if (onExternal) {
14854                // Abort update; system app can't be replaced with app on sdcard
14855                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14856                        "Cannot install updates to system apps on sdcard");
14857                return;
14858            } else if (ephemeral) {
14859                // Abort update; system app can't be replaced with an ephemeral app
14860                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14861                        "Cannot update a system app with an ephemeral app");
14862                return;
14863            }
14864        }
14865
14866        if (args.move != null) {
14867            // We did an in-place move, so dex is ready to roll
14868            scanFlags |= SCAN_NO_DEX;
14869            scanFlags |= SCAN_MOVE;
14870
14871            synchronized (mPackages) {
14872                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14873                if (ps == null) {
14874                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14875                            "Missing settings for moved package " + pkgName);
14876                }
14877
14878                // We moved the entire application as-is, so bring over the
14879                // previously derived ABI information.
14880                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14881                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14882            }
14883
14884        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14885            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14886            scanFlags |= SCAN_NO_DEX;
14887
14888            try {
14889                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14890                    args.abiOverride : pkg.cpuAbiOverride);
14891                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14892                        true /* extract libs */);
14893            } catch (PackageManagerException pme) {
14894                Slog.e(TAG, "Error deriving application ABI", pme);
14895                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14896                return;
14897            }
14898
14899            // Shared libraries for the package need to be updated.
14900            synchronized (mPackages) {
14901                try {
14902                    updateSharedLibrariesLPw(pkg, null);
14903                } catch (PackageManagerException e) {
14904                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14905                }
14906            }
14907            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14908            // Do not run PackageDexOptimizer through the local performDexOpt
14909            // method because `pkg` is not in `mPackages` yet.
14910            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14911                    null /* instructionSets */, false /* checkProfiles */,
14912                    getCompilerFilterForReason(REASON_INSTALL));
14913            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14914            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14915                String msg = "Extracting package failed for " + pkgName;
14916                res.setError(INSTALL_FAILED_DEXOPT, msg);
14917                return;
14918            }
14919
14920            // Notify BackgroundDexOptService that the package has been changed.
14921            // If this is an update of a package which used to fail to compile,
14922            // BDOS will remove it from its blacklist.
14923            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14924        }
14925
14926        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14927            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14928            return;
14929        }
14930
14931        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14932
14933        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14934                "installPackageLI")) {
14935            if (replace) {
14936                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14937                        installerPackageName, res);
14938            } else {
14939                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14940                        args.user, installerPackageName, volumeUuid, res);
14941            }
14942        }
14943        synchronized (mPackages) {
14944            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14945            if (ps != null) {
14946                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14947            }
14948
14949            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14950            for (int i = 0; i < childCount; i++) {
14951                PackageParser.Package childPkg = pkg.childPackages.get(i);
14952                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14953                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14954                if (childPs != null) {
14955                    childRes.newUsers = childPs.queryInstalledUsers(
14956                            sUserManager.getUserIds(), true);
14957                }
14958            }
14959        }
14960    }
14961
14962    private void startIntentFilterVerifications(int userId, boolean replacing,
14963            PackageParser.Package pkg) {
14964        if (mIntentFilterVerifierComponent == null) {
14965            Slog.w(TAG, "No IntentFilter verification will not be done as "
14966                    + "there is no IntentFilterVerifier available!");
14967            return;
14968        }
14969
14970        final int verifierUid = getPackageUid(
14971                mIntentFilterVerifierComponent.getPackageName(),
14972                MATCH_DEBUG_TRIAGED_MISSING,
14973                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14974
14975        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14976        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14977        mHandler.sendMessage(msg);
14978
14979        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14980        for (int i = 0; i < childCount; i++) {
14981            PackageParser.Package childPkg = pkg.childPackages.get(i);
14982            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14983            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14984            mHandler.sendMessage(msg);
14985        }
14986    }
14987
14988    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14989            PackageParser.Package pkg) {
14990        int size = pkg.activities.size();
14991        if (size == 0) {
14992            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14993                    "No activity, so no need to verify any IntentFilter!");
14994            return;
14995        }
14996
14997        final boolean hasDomainURLs = hasDomainURLs(pkg);
14998        if (!hasDomainURLs) {
14999            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15000                    "No domain URLs, so no need to verify any IntentFilter!");
15001            return;
15002        }
15003
15004        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15005                + " if any IntentFilter from the " + size
15006                + " Activities needs verification ...");
15007
15008        int count = 0;
15009        final String packageName = pkg.packageName;
15010
15011        synchronized (mPackages) {
15012            // If this is a new install and we see that we've already run verification for this
15013            // package, we have nothing to do: it means the state was restored from backup.
15014            if (!replacing) {
15015                IntentFilterVerificationInfo ivi =
15016                        mSettings.getIntentFilterVerificationLPr(packageName);
15017                if (ivi != null) {
15018                    if (DEBUG_DOMAIN_VERIFICATION) {
15019                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15020                                + ivi.getStatusString());
15021                    }
15022                    return;
15023                }
15024            }
15025
15026            // If any filters need to be verified, then all need to be.
15027            boolean needToVerify = false;
15028            for (PackageParser.Activity a : pkg.activities) {
15029                for (ActivityIntentInfo filter : a.intents) {
15030                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15031                        if (DEBUG_DOMAIN_VERIFICATION) {
15032                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15033                        }
15034                        needToVerify = true;
15035                        break;
15036                    }
15037                }
15038            }
15039
15040            if (needToVerify) {
15041                final int verificationId = mIntentFilterVerificationToken++;
15042                for (PackageParser.Activity a : pkg.activities) {
15043                    for (ActivityIntentInfo filter : a.intents) {
15044                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15045                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15046                                    "Verification needed for IntentFilter:" + filter.toString());
15047                            mIntentFilterVerifier.addOneIntentFilterVerification(
15048                                    verifierUid, userId, verificationId, filter, packageName);
15049                            count++;
15050                        }
15051                    }
15052                }
15053            }
15054        }
15055
15056        if (count > 0) {
15057            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15058                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15059                    +  " for userId:" + userId);
15060            mIntentFilterVerifier.startVerifications(userId);
15061        } else {
15062            if (DEBUG_DOMAIN_VERIFICATION) {
15063                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15064            }
15065        }
15066    }
15067
15068    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15069        final ComponentName cn  = filter.activity.getComponentName();
15070        final String packageName = cn.getPackageName();
15071
15072        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15073                packageName);
15074        if (ivi == null) {
15075            return true;
15076        }
15077        int status = ivi.getStatus();
15078        switch (status) {
15079            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15080            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15081                return true;
15082
15083            default:
15084                // Nothing to do
15085                return false;
15086        }
15087    }
15088
15089    private static boolean isMultiArch(ApplicationInfo info) {
15090        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15091    }
15092
15093    private static boolean isExternal(PackageParser.Package pkg) {
15094        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15095    }
15096
15097    private static boolean isExternal(PackageSetting ps) {
15098        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15099    }
15100
15101    private static boolean isEphemeral(PackageParser.Package pkg) {
15102        return pkg.applicationInfo.isEphemeralApp();
15103    }
15104
15105    private static boolean isEphemeral(PackageSetting ps) {
15106        return ps.pkg != null && isEphemeral(ps.pkg);
15107    }
15108
15109    private static boolean isSystemApp(PackageParser.Package pkg) {
15110        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15111    }
15112
15113    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15114        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15115    }
15116
15117    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15118        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15119    }
15120
15121    private static boolean isSystemApp(PackageSetting ps) {
15122        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15123    }
15124
15125    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15126        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15127    }
15128
15129    private int packageFlagsToInstallFlags(PackageSetting ps) {
15130        int installFlags = 0;
15131        if (isEphemeral(ps)) {
15132            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15133        }
15134        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15135            // This existing package was an external ASEC install when we have
15136            // the external flag without a UUID
15137            installFlags |= PackageManager.INSTALL_EXTERNAL;
15138        }
15139        if (ps.isForwardLocked()) {
15140            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15141        }
15142        return installFlags;
15143    }
15144
15145    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15146        if (isExternal(pkg)) {
15147            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15148                return StorageManager.UUID_PRIMARY_PHYSICAL;
15149            } else {
15150                return pkg.volumeUuid;
15151            }
15152        } else {
15153            return StorageManager.UUID_PRIVATE_INTERNAL;
15154        }
15155    }
15156
15157    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15158        if (isExternal(pkg)) {
15159            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15160                return mSettings.getExternalVersion();
15161            } else {
15162                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15163            }
15164        } else {
15165            return mSettings.getInternalVersion();
15166        }
15167    }
15168
15169    private void deleteTempPackageFiles() {
15170        final FilenameFilter filter = new FilenameFilter() {
15171            public boolean accept(File dir, String name) {
15172                return name.startsWith("vmdl") && name.endsWith(".tmp");
15173            }
15174        };
15175        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15176            file.delete();
15177        }
15178    }
15179
15180    @Override
15181    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15182            int flags) {
15183        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15184                flags);
15185    }
15186
15187    @Override
15188    public void deletePackage(final String packageName,
15189            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15190        mContext.enforceCallingOrSelfPermission(
15191                android.Manifest.permission.DELETE_PACKAGES, null);
15192        Preconditions.checkNotNull(packageName);
15193        Preconditions.checkNotNull(observer);
15194        final int uid = Binder.getCallingUid();
15195        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15196        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15197        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15198            mContext.enforceCallingOrSelfPermission(
15199                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15200                    "deletePackage for user " + userId);
15201        }
15202
15203        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15204            try {
15205                observer.onPackageDeleted(packageName,
15206                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15207            } catch (RemoteException re) {
15208            }
15209            return;
15210        }
15211
15212        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15213            try {
15214                observer.onPackageDeleted(packageName,
15215                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15216            } catch (RemoteException re) {
15217            }
15218            return;
15219        }
15220
15221        if (DEBUG_REMOVE) {
15222            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15223                    + " deleteAllUsers: " + deleteAllUsers );
15224        }
15225        // Queue up an async operation since the package deletion may take a little while.
15226        mHandler.post(new Runnable() {
15227            public void run() {
15228                mHandler.removeCallbacks(this);
15229                int returnCode;
15230                if (!deleteAllUsers) {
15231                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15232                } else {
15233                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15234                    // If nobody is blocking uninstall, proceed with delete for all users
15235                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15236                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15237                    } else {
15238                        // Otherwise uninstall individually for users with blockUninstalls=false
15239                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15240                        for (int userId : users) {
15241                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15242                                returnCode = deletePackageX(packageName, userId, userFlags);
15243                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15244                                    Slog.w(TAG, "Package delete failed for user " + userId
15245                                            + ", returnCode " + returnCode);
15246                                }
15247                            }
15248                        }
15249                        // The app has only been marked uninstalled for certain users.
15250                        // We still need to report that delete was blocked
15251                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15252                    }
15253                }
15254                try {
15255                    observer.onPackageDeleted(packageName, returnCode, null);
15256                } catch (RemoteException e) {
15257                    Log.i(TAG, "Observer no longer exists.");
15258                } //end catch
15259            } //end run
15260        });
15261    }
15262
15263    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15264        int[] result = EMPTY_INT_ARRAY;
15265        for (int userId : userIds) {
15266            if (getBlockUninstallForUser(packageName, userId)) {
15267                result = ArrayUtils.appendInt(result, userId);
15268            }
15269        }
15270        return result;
15271    }
15272
15273    @Override
15274    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15275        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15276    }
15277
15278    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15279        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15280                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15281        try {
15282            if (dpm != null) {
15283                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15284                        /* callingUserOnly =*/ false);
15285                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15286                        : deviceOwnerComponentName.getPackageName();
15287                // Does the package contains the device owner?
15288                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15289                // this check is probably not needed, since DO should be registered as a device
15290                // admin on some user too. (Original bug for this: b/17657954)
15291                if (packageName.equals(deviceOwnerPackageName)) {
15292                    return true;
15293                }
15294                // Does it contain a device admin for any user?
15295                int[] users;
15296                if (userId == UserHandle.USER_ALL) {
15297                    users = sUserManager.getUserIds();
15298                } else {
15299                    users = new int[]{userId};
15300                }
15301                for (int i = 0; i < users.length; ++i) {
15302                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15303                        return true;
15304                    }
15305                }
15306            }
15307        } catch (RemoteException e) {
15308        }
15309        return false;
15310    }
15311
15312    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15313        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15314    }
15315
15316    /**
15317     *  This method is an internal method that could be get invoked either
15318     *  to delete an installed package or to clean up a failed installation.
15319     *  After deleting an installed package, a broadcast is sent to notify any
15320     *  listeners that the package has been removed. For cleaning up a failed
15321     *  installation, the broadcast is not necessary since the package's
15322     *  installation wouldn't have sent the initial broadcast either
15323     *  The key steps in deleting a package are
15324     *  deleting the package information in internal structures like mPackages,
15325     *  deleting the packages base directories through installd
15326     *  updating mSettings to reflect current status
15327     *  persisting settings for later use
15328     *  sending a broadcast if necessary
15329     */
15330    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15331        final PackageRemovedInfo info = new PackageRemovedInfo();
15332        final boolean res;
15333
15334        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15335                ? UserHandle.ALL : new UserHandle(userId);
15336
15337        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15338            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15339            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15340        }
15341
15342        PackageSetting uninstalledPs = null;
15343
15344        // for the uninstall-updates case and restricted profiles, remember the per-
15345        // user handle installed state
15346        int[] allUsers;
15347        synchronized (mPackages) {
15348            uninstalledPs = mSettings.mPackages.get(packageName);
15349            if (uninstalledPs == null) {
15350                Slog.w(TAG, "Not removing non-existent package " + packageName);
15351                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15352            }
15353            allUsers = sUserManager.getUserIds();
15354            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15355        }
15356
15357        synchronized (mInstallLock) {
15358            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15359            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15360                    "deletePackageX")) {
15361                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15362                        deleteFlags | REMOVE_CHATTY, info, true, null);
15363            }
15364            synchronized (mPackages) {
15365                if (res) {
15366                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15367                }
15368            }
15369        }
15370
15371        if (res) {
15372            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15373            info.sendPackageRemovedBroadcasts(killApp);
15374            info.sendSystemPackageUpdatedBroadcasts();
15375            info.sendSystemPackageAppearedBroadcasts();
15376        }
15377        // Force a gc here.
15378        Runtime.getRuntime().gc();
15379        // Delete the resources here after sending the broadcast to let
15380        // other processes clean up before deleting resources.
15381        if (info.args != null) {
15382            synchronized (mInstallLock) {
15383                info.args.doPostDeleteLI(true);
15384            }
15385        }
15386
15387        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15388    }
15389
15390    class PackageRemovedInfo {
15391        String removedPackage;
15392        int uid = -1;
15393        int removedAppId = -1;
15394        int[] origUsers;
15395        int[] removedUsers = null;
15396        boolean isRemovedPackageSystemUpdate = false;
15397        boolean isUpdate;
15398        boolean dataRemoved;
15399        boolean removedForAllUsers;
15400        // Clean up resources deleted packages.
15401        InstallArgs args = null;
15402        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15403        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15404
15405        void sendPackageRemovedBroadcasts(boolean killApp) {
15406            sendPackageRemovedBroadcastInternal(killApp);
15407            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15408            for (int i = 0; i < childCount; i++) {
15409                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15410                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15411            }
15412        }
15413
15414        void sendSystemPackageUpdatedBroadcasts() {
15415            if (isRemovedPackageSystemUpdate) {
15416                sendSystemPackageUpdatedBroadcastsInternal();
15417                final int childCount = (removedChildPackages != null)
15418                        ? removedChildPackages.size() : 0;
15419                for (int i = 0; i < childCount; i++) {
15420                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15421                    if (childInfo.isRemovedPackageSystemUpdate) {
15422                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15423                    }
15424                }
15425            }
15426        }
15427
15428        void sendSystemPackageAppearedBroadcasts() {
15429            final int packageCount = (appearedChildPackages != null)
15430                    ? appearedChildPackages.size() : 0;
15431            for (int i = 0; i < packageCount; i++) {
15432                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15433                for (int userId : installedInfo.newUsers) {
15434                    sendPackageAddedForUser(installedInfo.name, true,
15435                            UserHandle.getAppId(installedInfo.uid), userId);
15436                }
15437            }
15438        }
15439
15440        private void sendSystemPackageUpdatedBroadcastsInternal() {
15441            Bundle extras = new Bundle(2);
15442            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15443            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15444            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15445                    extras, 0, null, null, null);
15446            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15447                    extras, 0, null, null, null);
15448            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15449                    null, 0, removedPackage, null, null);
15450        }
15451
15452        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15453            Bundle extras = new Bundle(2);
15454            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15455            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15456            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15457            if (isUpdate || isRemovedPackageSystemUpdate) {
15458                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15459            }
15460            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15461            if (removedPackage != null) {
15462                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15463                        extras, 0, null, null, removedUsers);
15464                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15465                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15466                            removedPackage, extras, 0, null, null, removedUsers);
15467                }
15468            }
15469            if (removedAppId >= 0) {
15470                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15471                        removedUsers);
15472            }
15473        }
15474    }
15475
15476    /*
15477     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15478     * flag is not set, the data directory is removed as well.
15479     * make sure this flag is set for partially installed apps. If not its meaningless to
15480     * delete a partially installed application.
15481     */
15482    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15483            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15484        String packageName = ps.name;
15485        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15486        // Retrieve object to delete permissions for shared user later on
15487        final PackageParser.Package deletedPkg;
15488        final PackageSetting deletedPs;
15489        // reader
15490        synchronized (mPackages) {
15491            deletedPkg = mPackages.get(packageName);
15492            deletedPs = mSettings.mPackages.get(packageName);
15493            if (outInfo != null) {
15494                outInfo.removedPackage = packageName;
15495                outInfo.removedUsers = deletedPs != null
15496                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15497                        : null;
15498            }
15499        }
15500
15501        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15502
15503        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15504            final PackageParser.Package resolvedPkg;
15505            if (deletedPkg != null) {
15506                resolvedPkg = deletedPkg;
15507            } else {
15508                // We don't have a parsed package when it lives on an ejected
15509                // adopted storage device, so fake something together
15510                resolvedPkg = new PackageParser.Package(ps.name);
15511                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15512            }
15513            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15514                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15515            destroyAppProfilesLIF(resolvedPkg);
15516            if (outInfo != null) {
15517                outInfo.dataRemoved = true;
15518            }
15519            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15520        }
15521
15522        // writer
15523        synchronized (mPackages) {
15524            if (deletedPs != null) {
15525                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15526                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15527                    clearDefaultBrowserIfNeeded(packageName);
15528                    if (outInfo != null) {
15529                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15530                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15531                    }
15532                    updatePermissionsLPw(deletedPs.name, null, 0);
15533                    if (deletedPs.sharedUser != null) {
15534                        // Remove permissions associated with package. Since runtime
15535                        // permissions are per user we have to kill the removed package
15536                        // or packages running under the shared user of the removed
15537                        // package if revoking the permissions requested only by the removed
15538                        // package is successful and this causes a change in gids.
15539                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15540                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15541                                    userId);
15542                            if (userIdToKill == UserHandle.USER_ALL
15543                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15544                                // If gids changed for this user, kill all affected packages.
15545                                mHandler.post(new Runnable() {
15546                                    @Override
15547                                    public void run() {
15548                                        // This has to happen with no lock held.
15549                                        killApplication(deletedPs.name, deletedPs.appId,
15550                                                KILL_APP_REASON_GIDS_CHANGED);
15551                                    }
15552                                });
15553                                break;
15554                            }
15555                        }
15556                    }
15557                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15558                }
15559                // make sure to preserve per-user disabled state if this removal was just
15560                // a downgrade of a system app to the factory package
15561                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15562                    if (DEBUG_REMOVE) {
15563                        Slog.d(TAG, "Propagating install state across downgrade");
15564                    }
15565                    for (int userId : allUserHandles) {
15566                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15567                        if (DEBUG_REMOVE) {
15568                            Slog.d(TAG, "    user " + userId + " => " + installed);
15569                        }
15570                        ps.setInstalled(installed, userId);
15571                    }
15572                }
15573            }
15574            // can downgrade to reader
15575            if (writeSettings) {
15576                // Save settings now
15577                mSettings.writeLPr();
15578            }
15579        }
15580        if (outInfo != null) {
15581            // A user ID was deleted here. Go through all users and remove it
15582            // from KeyStore.
15583            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15584        }
15585    }
15586
15587    static boolean locationIsPrivileged(File path) {
15588        try {
15589            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15590                    .getCanonicalPath();
15591            return path.getCanonicalPath().startsWith(privilegedAppDir);
15592        } catch (IOException e) {
15593            Slog.e(TAG, "Unable to access code path " + path);
15594        }
15595        return false;
15596    }
15597
15598    /*
15599     * Tries to delete system package.
15600     */
15601    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15602            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15603            boolean writeSettings) {
15604        if (deletedPs.parentPackageName != null) {
15605            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15606            return false;
15607        }
15608
15609        final boolean applyUserRestrictions
15610                = (allUserHandles != null) && (outInfo.origUsers != null);
15611        final PackageSetting disabledPs;
15612        // Confirm if the system package has been updated
15613        // An updated system app can be deleted. This will also have to restore
15614        // the system pkg from system partition
15615        // reader
15616        synchronized (mPackages) {
15617            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15618        }
15619
15620        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15621                + " disabledPs=" + disabledPs);
15622
15623        if (disabledPs == null) {
15624            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15625            return false;
15626        } else if (DEBUG_REMOVE) {
15627            Slog.d(TAG, "Deleting system pkg from data partition");
15628        }
15629
15630        if (DEBUG_REMOVE) {
15631            if (applyUserRestrictions) {
15632                Slog.d(TAG, "Remembering install states:");
15633                for (int userId : allUserHandles) {
15634                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15635                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15636                }
15637            }
15638        }
15639
15640        // Delete the updated package
15641        outInfo.isRemovedPackageSystemUpdate = true;
15642        if (outInfo.removedChildPackages != null) {
15643            final int childCount = (deletedPs.childPackageNames != null)
15644                    ? deletedPs.childPackageNames.size() : 0;
15645            for (int i = 0; i < childCount; i++) {
15646                String childPackageName = deletedPs.childPackageNames.get(i);
15647                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15648                        .contains(childPackageName)) {
15649                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15650                            childPackageName);
15651                    if (childInfo != null) {
15652                        childInfo.isRemovedPackageSystemUpdate = true;
15653                    }
15654                }
15655            }
15656        }
15657
15658        if (disabledPs.versionCode < deletedPs.versionCode) {
15659            // Delete data for downgrades
15660            flags &= ~PackageManager.DELETE_KEEP_DATA;
15661        } else {
15662            // Preserve data by setting flag
15663            flags |= PackageManager.DELETE_KEEP_DATA;
15664        }
15665
15666        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15667                outInfo, writeSettings, disabledPs.pkg);
15668        if (!ret) {
15669            return false;
15670        }
15671
15672        // writer
15673        synchronized (mPackages) {
15674            // Reinstate the old system package
15675            enableSystemPackageLPw(disabledPs.pkg);
15676            // Remove any native libraries from the upgraded package.
15677            removeNativeBinariesLI(deletedPs);
15678        }
15679
15680        // Install the system package
15681        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15682        int parseFlags = mDefParseFlags
15683                | PackageParser.PARSE_MUST_BE_APK
15684                | PackageParser.PARSE_IS_SYSTEM
15685                | PackageParser.PARSE_IS_SYSTEM_DIR;
15686        if (locationIsPrivileged(disabledPs.codePath)) {
15687            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15688        }
15689
15690        final PackageParser.Package newPkg;
15691        try {
15692            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15693        } catch (PackageManagerException e) {
15694            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15695                    + e.getMessage());
15696            return false;
15697        }
15698
15699        prepareAppDataAfterInstallLIF(newPkg);
15700
15701        // writer
15702        synchronized (mPackages) {
15703            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15704
15705            // Propagate the permissions state as we do not want to drop on the floor
15706            // runtime permissions. The update permissions method below will take
15707            // care of removing obsolete permissions and grant install permissions.
15708            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15709            updatePermissionsLPw(newPkg.packageName, newPkg,
15710                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15711
15712            if (applyUserRestrictions) {
15713                if (DEBUG_REMOVE) {
15714                    Slog.d(TAG, "Propagating install state across reinstall");
15715                }
15716                for (int userId : allUserHandles) {
15717                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15718                    if (DEBUG_REMOVE) {
15719                        Slog.d(TAG, "    user " + userId + " => " + installed);
15720                    }
15721                    ps.setInstalled(installed, userId);
15722
15723                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15724                }
15725                // Regardless of writeSettings we need to ensure that this restriction
15726                // state propagation is persisted
15727                mSettings.writeAllUsersPackageRestrictionsLPr();
15728            }
15729            // can downgrade to reader here
15730            if (writeSettings) {
15731                mSettings.writeLPr();
15732            }
15733        }
15734        return true;
15735    }
15736
15737    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15738            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15739            PackageRemovedInfo outInfo, boolean writeSettings,
15740            PackageParser.Package replacingPackage) {
15741        synchronized (mPackages) {
15742            if (outInfo != null) {
15743                outInfo.uid = ps.appId;
15744            }
15745
15746            if (outInfo != null && outInfo.removedChildPackages != null) {
15747                final int childCount = (ps.childPackageNames != null)
15748                        ? ps.childPackageNames.size() : 0;
15749                for (int i = 0; i < childCount; i++) {
15750                    String childPackageName = ps.childPackageNames.get(i);
15751                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15752                    if (childPs == null) {
15753                        return false;
15754                    }
15755                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15756                            childPackageName);
15757                    if (childInfo != null) {
15758                        childInfo.uid = childPs.appId;
15759                    }
15760                }
15761            }
15762        }
15763
15764        // Delete package data from internal structures and also remove data if flag is set
15765        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15766
15767        // Delete the child packages data
15768        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15769        for (int i = 0; i < childCount; i++) {
15770            PackageSetting childPs;
15771            synchronized (mPackages) {
15772                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15773            }
15774            if (childPs != null) {
15775                PackageRemovedInfo childOutInfo = (outInfo != null
15776                        && outInfo.removedChildPackages != null)
15777                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15778                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15779                        && (replacingPackage != null
15780                        && !replacingPackage.hasChildPackage(childPs.name))
15781                        ? flags & ~DELETE_KEEP_DATA : flags;
15782                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15783                        deleteFlags, writeSettings);
15784            }
15785        }
15786
15787        // Delete application code and resources only for parent packages
15788        if (ps.parentPackageName == null) {
15789            if (deleteCodeAndResources && (outInfo != null)) {
15790                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15791                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15792                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15793            }
15794        }
15795
15796        return true;
15797    }
15798
15799    @Override
15800    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15801            int userId) {
15802        mContext.enforceCallingOrSelfPermission(
15803                android.Manifest.permission.DELETE_PACKAGES, null);
15804        synchronized (mPackages) {
15805            PackageSetting ps = mSettings.mPackages.get(packageName);
15806            if (ps == null) {
15807                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15808                return false;
15809            }
15810            if (!ps.getInstalled(userId)) {
15811                // Can't block uninstall for an app that is not installed or enabled.
15812                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15813                return false;
15814            }
15815            ps.setBlockUninstall(blockUninstall, userId);
15816            mSettings.writePackageRestrictionsLPr(userId);
15817        }
15818        return true;
15819    }
15820
15821    @Override
15822    public boolean getBlockUninstallForUser(String packageName, int userId) {
15823        synchronized (mPackages) {
15824            PackageSetting ps = mSettings.mPackages.get(packageName);
15825            if (ps == null) {
15826                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15827                return false;
15828            }
15829            return ps.getBlockUninstall(userId);
15830        }
15831    }
15832
15833    @Override
15834    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15835        int callingUid = Binder.getCallingUid();
15836        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15837            throw new SecurityException(
15838                    "setRequiredForSystemUser can only be run by the system or root");
15839        }
15840        synchronized (mPackages) {
15841            PackageSetting ps = mSettings.mPackages.get(packageName);
15842            if (ps == null) {
15843                Log.w(TAG, "Package doesn't exist: " + packageName);
15844                return false;
15845            }
15846            if (systemUserApp) {
15847                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15848            } else {
15849                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15850            }
15851            mSettings.writeLPr();
15852        }
15853        return true;
15854    }
15855
15856    /*
15857     * This method handles package deletion in general
15858     */
15859    private boolean deletePackageLIF(String packageName, UserHandle user,
15860            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15861            PackageRemovedInfo outInfo, boolean writeSettings,
15862            PackageParser.Package replacingPackage) {
15863        if (packageName == null) {
15864            Slog.w(TAG, "Attempt to delete null packageName.");
15865            return false;
15866        }
15867
15868        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15869
15870        PackageSetting ps;
15871
15872        synchronized (mPackages) {
15873            ps = mSettings.mPackages.get(packageName);
15874            if (ps == null) {
15875                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15876                return false;
15877            }
15878
15879            if (ps.parentPackageName != null && (!isSystemApp(ps)
15880                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15881                if (DEBUG_REMOVE) {
15882                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15883                            + ((user == null) ? UserHandle.USER_ALL : user));
15884                }
15885                final int removedUserId = (user != null) ? user.getIdentifier()
15886                        : UserHandle.USER_ALL;
15887                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15888                    return false;
15889                }
15890                markPackageUninstalledForUserLPw(ps, user);
15891                scheduleWritePackageRestrictionsLocked(user);
15892                return true;
15893            }
15894        }
15895
15896        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15897                && user.getIdentifier() != UserHandle.USER_ALL)) {
15898            // The caller is asking that the package only be deleted for a single
15899            // user.  To do this, we just mark its uninstalled state and delete
15900            // its data. If this is a system app, we only allow this to happen if
15901            // they have set the special DELETE_SYSTEM_APP which requests different
15902            // semantics than normal for uninstalling system apps.
15903            markPackageUninstalledForUserLPw(ps, user);
15904
15905            if (!isSystemApp(ps)) {
15906                // Do not uninstall the APK if an app should be cached
15907                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15908                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15909                    // Other user still have this package installed, so all
15910                    // we need to do is clear this user's data and save that
15911                    // it is uninstalled.
15912                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15913                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15914                        return false;
15915                    }
15916                    scheduleWritePackageRestrictionsLocked(user);
15917                    return true;
15918                } else {
15919                    // We need to set it back to 'installed' so the uninstall
15920                    // broadcasts will be sent correctly.
15921                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15922                    ps.setInstalled(true, user.getIdentifier());
15923                }
15924            } else {
15925                // This is a system app, so we assume that the
15926                // other users still have this package installed, so all
15927                // we need to do is clear this user's data and save that
15928                // it is uninstalled.
15929                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15930                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15931                    return false;
15932                }
15933                scheduleWritePackageRestrictionsLocked(user);
15934                return true;
15935            }
15936        }
15937
15938        // If we are deleting a composite package for all users, keep track
15939        // of result for each child.
15940        if (ps.childPackageNames != null && outInfo != null) {
15941            synchronized (mPackages) {
15942                final int childCount = ps.childPackageNames.size();
15943                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15944                for (int i = 0; i < childCount; i++) {
15945                    String childPackageName = ps.childPackageNames.get(i);
15946                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15947                    childInfo.removedPackage = childPackageName;
15948                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15949                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15950                    if (childPs != null) {
15951                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15952                    }
15953                }
15954            }
15955        }
15956
15957        boolean ret = false;
15958        if (isSystemApp(ps)) {
15959            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15960            // When an updated system application is deleted we delete the existing resources
15961            // as well and fall back to existing code in system partition
15962            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15963        } else {
15964            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15965            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15966                    outInfo, writeSettings, replacingPackage);
15967        }
15968
15969        // Take a note whether we deleted the package for all users
15970        if (outInfo != null) {
15971            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15972            if (outInfo.removedChildPackages != null) {
15973                synchronized (mPackages) {
15974                    final int childCount = outInfo.removedChildPackages.size();
15975                    for (int i = 0; i < childCount; i++) {
15976                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15977                        if (childInfo != null) {
15978                            childInfo.removedForAllUsers = mPackages.get(
15979                                    childInfo.removedPackage) == null;
15980                        }
15981                    }
15982                }
15983            }
15984            // If we uninstalled an update to a system app there may be some
15985            // child packages that appeared as they are declared in the system
15986            // app but were not declared in the update.
15987            if (isSystemApp(ps)) {
15988                synchronized (mPackages) {
15989                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15990                    final int childCount = (updatedPs.childPackageNames != null)
15991                            ? updatedPs.childPackageNames.size() : 0;
15992                    for (int i = 0; i < childCount; i++) {
15993                        String childPackageName = updatedPs.childPackageNames.get(i);
15994                        if (outInfo.removedChildPackages == null
15995                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15996                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15997                            if (childPs == null) {
15998                                continue;
15999                            }
16000                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16001                            installRes.name = childPackageName;
16002                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16003                            installRes.pkg = mPackages.get(childPackageName);
16004                            installRes.uid = childPs.pkg.applicationInfo.uid;
16005                            if (outInfo.appearedChildPackages == null) {
16006                                outInfo.appearedChildPackages = new ArrayMap<>();
16007                            }
16008                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16009                        }
16010                    }
16011                }
16012            }
16013        }
16014
16015        return ret;
16016    }
16017
16018    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16019        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16020                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16021        for (int nextUserId : userIds) {
16022            if (DEBUG_REMOVE) {
16023                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16024            }
16025            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16026                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16027                    false /*hidden*/, false /*suspended*/, null, null, null,
16028                    false /*blockUninstall*/,
16029                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16030        }
16031    }
16032
16033    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16034            PackageRemovedInfo outInfo) {
16035        final PackageParser.Package pkg;
16036        synchronized (mPackages) {
16037            pkg = mPackages.get(ps.name);
16038        }
16039
16040        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16041                : new int[] {userId};
16042        for (int nextUserId : userIds) {
16043            if (DEBUG_REMOVE) {
16044                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16045                        + nextUserId);
16046            }
16047
16048            destroyAppDataLIF(pkg, userId,
16049                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16050            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16051            schedulePackageCleaning(ps.name, nextUserId, false);
16052            synchronized (mPackages) {
16053                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16054                    scheduleWritePackageRestrictionsLocked(nextUserId);
16055                }
16056                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16057            }
16058        }
16059
16060        if (outInfo != null) {
16061            outInfo.removedPackage = ps.name;
16062            outInfo.removedAppId = ps.appId;
16063            outInfo.removedUsers = userIds;
16064        }
16065
16066        return true;
16067    }
16068
16069    private final class ClearStorageConnection implements ServiceConnection {
16070        IMediaContainerService mContainerService;
16071
16072        @Override
16073        public void onServiceConnected(ComponentName name, IBinder service) {
16074            synchronized (this) {
16075                mContainerService = IMediaContainerService.Stub.asInterface(service);
16076                notifyAll();
16077            }
16078        }
16079
16080        @Override
16081        public void onServiceDisconnected(ComponentName name) {
16082        }
16083    }
16084
16085    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16086        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16087
16088        final boolean mounted;
16089        if (Environment.isExternalStorageEmulated()) {
16090            mounted = true;
16091        } else {
16092            final String status = Environment.getExternalStorageState();
16093
16094            mounted = status.equals(Environment.MEDIA_MOUNTED)
16095                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16096        }
16097
16098        if (!mounted) {
16099            return;
16100        }
16101
16102        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16103        int[] users;
16104        if (userId == UserHandle.USER_ALL) {
16105            users = sUserManager.getUserIds();
16106        } else {
16107            users = new int[] { userId };
16108        }
16109        final ClearStorageConnection conn = new ClearStorageConnection();
16110        if (mContext.bindServiceAsUser(
16111                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16112            try {
16113                for (int curUser : users) {
16114                    long timeout = SystemClock.uptimeMillis() + 5000;
16115                    synchronized (conn) {
16116                        long now = SystemClock.uptimeMillis();
16117                        while (conn.mContainerService == null && now < timeout) {
16118                            try {
16119                                conn.wait(timeout - now);
16120                            } catch (InterruptedException e) {
16121                            }
16122                        }
16123                    }
16124                    if (conn.mContainerService == null) {
16125                        return;
16126                    }
16127
16128                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16129                    clearDirectory(conn.mContainerService,
16130                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16131                    if (allData) {
16132                        clearDirectory(conn.mContainerService,
16133                                userEnv.buildExternalStorageAppDataDirs(packageName));
16134                        clearDirectory(conn.mContainerService,
16135                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16136                    }
16137                }
16138            } finally {
16139                mContext.unbindService(conn);
16140            }
16141        }
16142    }
16143
16144    @Override
16145    public void clearApplicationProfileData(String packageName) {
16146        enforceSystemOrRoot("Only the system can clear all profile data");
16147
16148        final PackageParser.Package pkg;
16149        synchronized (mPackages) {
16150            pkg = mPackages.get(packageName);
16151        }
16152
16153        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16154            synchronized (mInstallLock) {
16155                clearAppProfilesLIF(pkg);
16156            }
16157        }
16158    }
16159
16160    @Override
16161    public void clearApplicationUserData(final String packageName,
16162            final IPackageDataObserver observer, final int userId) {
16163        mContext.enforceCallingOrSelfPermission(
16164                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16165
16166        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16167                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16168
16169        final DevicePolicyManagerInternal dpmi = LocalServices
16170                .getService(DevicePolicyManagerInternal.class);
16171        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16172            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16173        }
16174        // Queue up an async operation since the package deletion may take a little while.
16175        mHandler.post(new Runnable() {
16176            public void run() {
16177                mHandler.removeCallbacks(this);
16178                final boolean succeeded;
16179                try (PackageFreezer freezer = freezePackage(packageName,
16180                        "clearApplicationUserData")) {
16181                    synchronized (mInstallLock) {
16182                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16183                    }
16184                    clearExternalStorageDataSync(packageName, userId, true);
16185                }
16186                if (succeeded) {
16187                    // invoke DeviceStorageMonitor's update method to clear any notifications
16188                    DeviceStorageMonitorInternal dsm = LocalServices
16189                            .getService(DeviceStorageMonitorInternal.class);
16190                    if (dsm != null) {
16191                        dsm.checkMemory();
16192                    }
16193                }
16194                if(observer != null) {
16195                    try {
16196                        observer.onRemoveCompleted(packageName, succeeded);
16197                    } catch (RemoteException e) {
16198                        Log.i(TAG, "Observer no longer exists.");
16199                    }
16200                } //end if observer
16201            } //end run
16202        });
16203    }
16204
16205    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16206        if (packageName == null) {
16207            Slog.w(TAG, "Attempt to delete null packageName.");
16208            return false;
16209        }
16210
16211        // Try finding details about the requested package
16212        PackageParser.Package pkg;
16213        synchronized (mPackages) {
16214            pkg = mPackages.get(packageName);
16215            if (pkg == null) {
16216                final PackageSetting ps = mSettings.mPackages.get(packageName);
16217                if (ps != null) {
16218                    pkg = ps.pkg;
16219                }
16220            }
16221
16222            if (pkg == null) {
16223                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16224                return false;
16225            }
16226
16227            PackageSetting ps = (PackageSetting) pkg.mExtras;
16228            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16229        }
16230
16231        clearAppDataLIF(pkg, userId,
16232                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16233
16234        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16235        removeKeystoreDataIfNeeded(userId, appId);
16236
16237        final UserManager um = mContext.getSystemService(UserManager.class);
16238        final int flags;
16239        if (um.isUserUnlockingOrUnlocked(userId)) {
16240            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16241        } else if (um.isUserRunning(userId)) {
16242            flags = StorageManager.FLAG_STORAGE_DE;
16243        } else {
16244            flags = 0;
16245        }
16246        prepareAppDataContentsLIF(pkg, userId, flags);
16247
16248        return true;
16249    }
16250
16251    /**
16252     * Reverts user permission state changes (permissions and flags) in
16253     * all packages for a given user.
16254     *
16255     * @param userId The device user for which to do a reset.
16256     */
16257    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16258        final int packageCount = mPackages.size();
16259        for (int i = 0; i < packageCount; i++) {
16260            PackageParser.Package pkg = mPackages.valueAt(i);
16261            PackageSetting ps = (PackageSetting) pkg.mExtras;
16262            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16263        }
16264    }
16265
16266    private void resetNetworkPolicies(int userId) {
16267        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16268    }
16269
16270    /**
16271     * Reverts user permission state changes (permissions and flags).
16272     *
16273     * @param ps The package for which to reset.
16274     * @param userId The device user for which to do a reset.
16275     */
16276    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16277            final PackageSetting ps, final int userId) {
16278        if (ps.pkg == null) {
16279            return;
16280        }
16281
16282        // These are flags that can change base on user actions.
16283        final int userSettableMask = FLAG_PERMISSION_USER_SET
16284                | FLAG_PERMISSION_USER_FIXED
16285                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16286                | FLAG_PERMISSION_REVIEW_REQUIRED;
16287
16288        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16289                | FLAG_PERMISSION_POLICY_FIXED;
16290
16291        boolean writeInstallPermissions = false;
16292        boolean writeRuntimePermissions = false;
16293
16294        final int permissionCount = ps.pkg.requestedPermissions.size();
16295        for (int i = 0; i < permissionCount; i++) {
16296            String permission = ps.pkg.requestedPermissions.get(i);
16297
16298            BasePermission bp = mSettings.mPermissions.get(permission);
16299            if (bp == null) {
16300                continue;
16301            }
16302
16303            // If shared user we just reset the state to which only this app contributed.
16304            if (ps.sharedUser != null) {
16305                boolean used = false;
16306                final int packageCount = ps.sharedUser.packages.size();
16307                for (int j = 0; j < packageCount; j++) {
16308                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16309                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16310                            && pkg.pkg.requestedPermissions.contains(permission)) {
16311                        used = true;
16312                        break;
16313                    }
16314                }
16315                if (used) {
16316                    continue;
16317                }
16318            }
16319
16320            PermissionsState permissionsState = ps.getPermissionsState();
16321
16322            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16323
16324            // Always clear the user settable flags.
16325            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16326                    bp.name) != null;
16327            // If permission review is enabled and this is a legacy app, mark the
16328            // permission as requiring a review as this is the initial state.
16329            int flags = 0;
16330            if (Build.PERMISSIONS_REVIEW_REQUIRED
16331                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16332                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16333            }
16334            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16335                if (hasInstallState) {
16336                    writeInstallPermissions = true;
16337                } else {
16338                    writeRuntimePermissions = true;
16339                }
16340            }
16341
16342            // Below is only runtime permission handling.
16343            if (!bp.isRuntime()) {
16344                continue;
16345            }
16346
16347            // Never clobber system or policy.
16348            if ((oldFlags & policyOrSystemFlags) != 0) {
16349                continue;
16350            }
16351
16352            // If this permission was granted by default, make sure it is.
16353            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16354                if (permissionsState.grantRuntimePermission(bp, userId)
16355                        != PERMISSION_OPERATION_FAILURE) {
16356                    writeRuntimePermissions = true;
16357                }
16358            // If permission review is enabled the permissions for a legacy apps
16359            // are represented as constantly granted runtime ones, so don't revoke.
16360            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16361                // Otherwise, reset the permission.
16362                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16363                switch (revokeResult) {
16364                    case PERMISSION_OPERATION_SUCCESS:
16365                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16366                        writeRuntimePermissions = true;
16367                        final int appId = ps.appId;
16368                        mHandler.post(new Runnable() {
16369                            @Override
16370                            public void run() {
16371                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16372                            }
16373                        });
16374                    } break;
16375                }
16376            }
16377        }
16378
16379        // Synchronously write as we are taking permissions away.
16380        if (writeRuntimePermissions) {
16381            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16382        }
16383
16384        // Synchronously write as we are taking permissions away.
16385        if (writeInstallPermissions) {
16386            mSettings.writeLPr();
16387        }
16388    }
16389
16390    /**
16391     * Remove entries from the keystore daemon. Will only remove it if the
16392     * {@code appId} is valid.
16393     */
16394    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16395        if (appId < 0) {
16396            return;
16397        }
16398
16399        final KeyStore keyStore = KeyStore.getInstance();
16400        if (keyStore != null) {
16401            if (userId == UserHandle.USER_ALL) {
16402                for (final int individual : sUserManager.getUserIds()) {
16403                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16404                }
16405            } else {
16406                keyStore.clearUid(UserHandle.getUid(userId, appId));
16407            }
16408        } else {
16409            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16410        }
16411    }
16412
16413    @Override
16414    public void deleteApplicationCacheFiles(final String packageName,
16415            final IPackageDataObserver observer) {
16416        final int userId = UserHandle.getCallingUserId();
16417        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16418    }
16419
16420    @Override
16421    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16422            final IPackageDataObserver observer) {
16423        mContext.enforceCallingOrSelfPermission(
16424                android.Manifest.permission.DELETE_CACHE_FILES, null);
16425        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16426                /* requireFullPermission= */ true, /* checkShell= */ false,
16427                "delete application cache files");
16428
16429        final PackageParser.Package pkg;
16430        synchronized (mPackages) {
16431            pkg = mPackages.get(packageName);
16432        }
16433
16434        // Queue up an async operation since the package deletion may take a little while.
16435        mHandler.post(new Runnable() {
16436            public void run() {
16437                synchronized (mInstallLock) {
16438                    final int flags = StorageManager.FLAG_STORAGE_DE
16439                            | StorageManager.FLAG_STORAGE_CE;
16440                    // We're only clearing cache files, so we don't care if the
16441                    // app is unfrozen and still able to run
16442                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16443                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16444                }
16445                clearExternalStorageDataSync(packageName, userId, false);
16446                if (observer != null) {
16447                    try {
16448                        observer.onRemoveCompleted(packageName, true);
16449                    } catch (RemoteException e) {
16450                        Log.i(TAG, "Observer no longer exists.");
16451                    }
16452                }
16453            }
16454        });
16455    }
16456
16457    @Override
16458    public void getPackageSizeInfo(final String packageName, int userHandle,
16459            final IPackageStatsObserver observer) {
16460        mContext.enforceCallingOrSelfPermission(
16461                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16462        if (packageName == null) {
16463            throw new IllegalArgumentException("Attempt to get size of null packageName");
16464        }
16465
16466        PackageStats stats = new PackageStats(packageName, userHandle);
16467
16468        /*
16469         * Queue up an async operation since the package measurement may take a
16470         * little while.
16471         */
16472        Message msg = mHandler.obtainMessage(INIT_COPY);
16473        msg.obj = new MeasureParams(stats, observer);
16474        mHandler.sendMessage(msg);
16475    }
16476
16477    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16478        final PackageSetting ps;
16479        synchronized (mPackages) {
16480            ps = mSettings.mPackages.get(packageName);
16481            if (ps == null) {
16482                Slog.w(TAG, "Failed to find settings for " + packageName);
16483                return false;
16484            }
16485        }
16486        try {
16487            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16488                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16489                    ps.getCeDataInode(userId), ps.codePathString, stats);
16490        } catch (InstallerException e) {
16491            Slog.w(TAG, String.valueOf(e));
16492            return false;
16493        }
16494
16495        // For now, ignore code size of packages on system partition
16496        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16497            stats.codeSize = 0;
16498        }
16499
16500        return true;
16501    }
16502
16503    private int getUidTargetSdkVersionLockedLPr(int uid) {
16504        Object obj = mSettings.getUserIdLPr(uid);
16505        if (obj instanceof SharedUserSetting) {
16506            final SharedUserSetting sus = (SharedUserSetting) obj;
16507            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16508            final Iterator<PackageSetting> it = sus.packages.iterator();
16509            while (it.hasNext()) {
16510                final PackageSetting ps = it.next();
16511                if (ps.pkg != null) {
16512                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16513                    if (v < vers) vers = v;
16514                }
16515            }
16516            return vers;
16517        } else if (obj instanceof PackageSetting) {
16518            final PackageSetting ps = (PackageSetting) obj;
16519            if (ps.pkg != null) {
16520                return ps.pkg.applicationInfo.targetSdkVersion;
16521            }
16522        }
16523        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16524    }
16525
16526    @Override
16527    public void addPreferredActivity(IntentFilter filter, int match,
16528            ComponentName[] set, ComponentName activity, int userId) {
16529        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16530                "Adding preferred");
16531    }
16532
16533    private void addPreferredActivityInternal(IntentFilter filter, int match,
16534            ComponentName[] set, ComponentName activity, boolean always, int userId,
16535            String opname) {
16536        // writer
16537        int callingUid = Binder.getCallingUid();
16538        enforceCrossUserPermission(callingUid, userId,
16539                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16540        if (filter.countActions() == 0) {
16541            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16542            return;
16543        }
16544        synchronized (mPackages) {
16545            if (mContext.checkCallingOrSelfPermission(
16546                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16547                    != PackageManager.PERMISSION_GRANTED) {
16548                if (getUidTargetSdkVersionLockedLPr(callingUid)
16549                        < Build.VERSION_CODES.FROYO) {
16550                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16551                            + callingUid);
16552                    return;
16553                }
16554                mContext.enforceCallingOrSelfPermission(
16555                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16556            }
16557
16558            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16559            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16560                    + userId + ":");
16561            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16562            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16563            scheduleWritePackageRestrictionsLocked(userId);
16564        }
16565    }
16566
16567    @Override
16568    public void replacePreferredActivity(IntentFilter filter, int match,
16569            ComponentName[] set, ComponentName activity, int userId) {
16570        if (filter.countActions() != 1) {
16571            throw new IllegalArgumentException(
16572                    "replacePreferredActivity expects filter to have only 1 action.");
16573        }
16574        if (filter.countDataAuthorities() != 0
16575                || filter.countDataPaths() != 0
16576                || filter.countDataSchemes() > 1
16577                || filter.countDataTypes() != 0) {
16578            throw new IllegalArgumentException(
16579                    "replacePreferredActivity expects filter to have no data authorities, " +
16580                    "paths, or types; and at most one scheme.");
16581        }
16582
16583        final int callingUid = Binder.getCallingUid();
16584        enforceCrossUserPermission(callingUid, userId,
16585                true /* requireFullPermission */, false /* checkShell */,
16586                "replace preferred activity");
16587        synchronized (mPackages) {
16588            if (mContext.checkCallingOrSelfPermission(
16589                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16590                    != PackageManager.PERMISSION_GRANTED) {
16591                if (getUidTargetSdkVersionLockedLPr(callingUid)
16592                        < Build.VERSION_CODES.FROYO) {
16593                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16594                            + Binder.getCallingUid());
16595                    return;
16596                }
16597                mContext.enforceCallingOrSelfPermission(
16598                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16599            }
16600
16601            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16602            if (pir != null) {
16603                // Get all of the existing entries that exactly match this filter.
16604                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16605                if (existing != null && existing.size() == 1) {
16606                    PreferredActivity cur = existing.get(0);
16607                    if (DEBUG_PREFERRED) {
16608                        Slog.i(TAG, "Checking replace of preferred:");
16609                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16610                        if (!cur.mPref.mAlways) {
16611                            Slog.i(TAG, "  -- CUR; not mAlways!");
16612                        } else {
16613                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16614                            Slog.i(TAG, "  -- CUR: mSet="
16615                                    + Arrays.toString(cur.mPref.mSetComponents));
16616                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16617                            Slog.i(TAG, "  -- NEW: mMatch="
16618                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16619                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16620                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16621                        }
16622                    }
16623                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16624                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16625                            && cur.mPref.sameSet(set)) {
16626                        // Setting the preferred activity to what it happens to be already
16627                        if (DEBUG_PREFERRED) {
16628                            Slog.i(TAG, "Replacing with same preferred activity "
16629                                    + cur.mPref.mShortComponent + " for user "
16630                                    + userId + ":");
16631                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16632                        }
16633                        return;
16634                    }
16635                }
16636
16637                if (existing != null) {
16638                    if (DEBUG_PREFERRED) {
16639                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16640                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16641                    }
16642                    for (int i = 0; i < existing.size(); i++) {
16643                        PreferredActivity pa = existing.get(i);
16644                        if (DEBUG_PREFERRED) {
16645                            Slog.i(TAG, "Removing existing preferred activity "
16646                                    + pa.mPref.mComponent + ":");
16647                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16648                        }
16649                        pir.removeFilter(pa);
16650                    }
16651                }
16652            }
16653            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16654                    "Replacing preferred");
16655        }
16656    }
16657
16658    @Override
16659    public void clearPackagePreferredActivities(String packageName) {
16660        final int uid = Binder.getCallingUid();
16661        // writer
16662        synchronized (mPackages) {
16663            PackageParser.Package pkg = mPackages.get(packageName);
16664            if (pkg == null || pkg.applicationInfo.uid != uid) {
16665                if (mContext.checkCallingOrSelfPermission(
16666                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16667                        != PackageManager.PERMISSION_GRANTED) {
16668                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16669                            < Build.VERSION_CODES.FROYO) {
16670                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16671                                + Binder.getCallingUid());
16672                        return;
16673                    }
16674                    mContext.enforceCallingOrSelfPermission(
16675                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16676                }
16677            }
16678
16679            int user = UserHandle.getCallingUserId();
16680            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16681                scheduleWritePackageRestrictionsLocked(user);
16682            }
16683        }
16684    }
16685
16686    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16687    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16688        ArrayList<PreferredActivity> removed = null;
16689        boolean changed = false;
16690        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16691            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16692            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16693            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16694                continue;
16695            }
16696            Iterator<PreferredActivity> it = pir.filterIterator();
16697            while (it.hasNext()) {
16698                PreferredActivity pa = it.next();
16699                // Mark entry for removal only if it matches the package name
16700                // and the entry is of type "always".
16701                if (packageName == null ||
16702                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16703                                && pa.mPref.mAlways)) {
16704                    if (removed == null) {
16705                        removed = new ArrayList<PreferredActivity>();
16706                    }
16707                    removed.add(pa);
16708                }
16709            }
16710            if (removed != null) {
16711                for (int j=0; j<removed.size(); j++) {
16712                    PreferredActivity pa = removed.get(j);
16713                    pir.removeFilter(pa);
16714                }
16715                changed = true;
16716            }
16717        }
16718        return changed;
16719    }
16720
16721    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16722    private void clearIntentFilterVerificationsLPw(int userId) {
16723        final int packageCount = mPackages.size();
16724        for (int i = 0; i < packageCount; i++) {
16725            PackageParser.Package pkg = mPackages.valueAt(i);
16726            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16727        }
16728    }
16729
16730    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16731    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16732        if (userId == UserHandle.USER_ALL) {
16733            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16734                    sUserManager.getUserIds())) {
16735                for (int oneUserId : sUserManager.getUserIds()) {
16736                    scheduleWritePackageRestrictionsLocked(oneUserId);
16737                }
16738            }
16739        } else {
16740            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16741                scheduleWritePackageRestrictionsLocked(userId);
16742            }
16743        }
16744    }
16745
16746    void clearDefaultBrowserIfNeeded(String packageName) {
16747        for (int oneUserId : sUserManager.getUserIds()) {
16748            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16749            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16750            if (packageName.equals(defaultBrowserPackageName)) {
16751                setDefaultBrowserPackageName(null, oneUserId);
16752            }
16753        }
16754    }
16755
16756    @Override
16757    public void resetApplicationPreferences(int userId) {
16758        mContext.enforceCallingOrSelfPermission(
16759                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16760        final long identity = Binder.clearCallingIdentity();
16761        // writer
16762        try {
16763            synchronized (mPackages) {
16764                clearPackagePreferredActivitiesLPw(null, userId);
16765                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16766                // TODO: We have to reset the default SMS and Phone. This requires
16767                // significant refactoring to keep all default apps in the package
16768                // manager (cleaner but more work) or have the services provide
16769                // callbacks to the package manager to request a default app reset.
16770                applyFactoryDefaultBrowserLPw(userId);
16771                clearIntentFilterVerificationsLPw(userId);
16772                primeDomainVerificationsLPw(userId);
16773                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16774                scheduleWritePackageRestrictionsLocked(userId);
16775            }
16776            resetNetworkPolicies(userId);
16777        } finally {
16778            Binder.restoreCallingIdentity(identity);
16779        }
16780    }
16781
16782    @Override
16783    public int getPreferredActivities(List<IntentFilter> outFilters,
16784            List<ComponentName> outActivities, String packageName) {
16785
16786        int num = 0;
16787        final int userId = UserHandle.getCallingUserId();
16788        // reader
16789        synchronized (mPackages) {
16790            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16791            if (pir != null) {
16792                final Iterator<PreferredActivity> it = pir.filterIterator();
16793                while (it.hasNext()) {
16794                    final PreferredActivity pa = it.next();
16795                    if (packageName == null
16796                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16797                                    && pa.mPref.mAlways)) {
16798                        if (outFilters != null) {
16799                            outFilters.add(new IntentFilter(pa));
16800                        }
16801                        if (outActivities != null) {
16802                            outActivities.add(pa.mPref.mComponent);
16803                        }
16804                    }
16805                }
16806            }
16807        }
16808
16809        return num;
16810    }
16811
16812    @Override
16813    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16814            int userId) {
16815        int callingUid = Binder.getCallingUid();
16816        if (callingUid != Process.SYSTEM_UID) {
16817            throw new SecurityException(
16818                    "addPersistentPreferredActivity can only be run by the system");
16819        }
16820        if (filter.countActions() == 0) {
16821            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16822            return;
16823        }
16824        synchronized (mPackages) {
16825            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16826                    ":");
16827            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16828            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16829                    new PersistentPreferredActivity(filter, activity));
16830            scheduleWritePackageRestrictionsLocked(userId);
16831        }
16832    }
16833
16834    @Override
16835    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16836        int callingUid = Binder.getCallingUid();
16837        if (callingUid != Process.SYSTEM_UID) {
16838            throw new SecurityException(
16839                    "clearPackagePersistentPreferredActivities can only be run by the system");
16840        }
16841        ArrayList<PersistentPreferredActivity> removed = null;
16842        boolean changed = false;
16843        synchronized (mPackages) {
16844            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16845                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16846                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16847                        .valueAt(i);
16848                if (userId != thisUserId) {
16849                    continue;
16850                }
16851                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16852                while (it.hasNext()) {
16853                    PersistentPreferredActivity ppa = it.next();
16854                    // Mark entry for removal only if it matches the package name.
16855                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16856                        if (removed == null) {
16857                            removed = new ArrayList<PersistentPreferredActivity>();
16858                        }
16859                        removed.add(ppa);
16860                    }
16861                }
16862                if (removed != null) {
16863                    for (int j=0; j<removed.size(); j++) {
16864                        PersistentPreferredActivity ppa = removed.get(j);
16865                        ppir.removeFilter(ppa);
16866                    }
16867                    changed = true;
16868                }
16869            }
16870
16871            if (changed) {
16872                scheduleWritePackageRestrictionsLocked(userId);
16873            }
16874        }
16875    }
16876
16877    /**
16878     * Common machinery for picking apart a restored XML blob and passing
16879     * it to a caller-supplied functor to be applied to the running system.
16880     */
16881    private void restoreFromXml(XmlPullParser parser, int userId,
16882            String expectedStartTag, BlobXmlRestorer functor)
16883            throws IOException, XmlPullParserException {
16884        int type;
16885        while ((type = parser.next()) != XmlPullParser.START_TAG
16886                && type != XmlPullParser.END_DOCUMENT) {
16887        }
16888        if (type != XmlPullParser.START_TAG) {
16889            // oops didn't find a start tag?!
16890            if (DEBUG_BACKUP) {
16891                Slog.e(TAG, "Didn't find start tag during restore");
16892            }
16893            return;
16894        }
16895Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16896        // this is supposed to be TAG_PREFERRED_BACKUP
16897        if (!expectedStartTag.equals(parser.getName())) {
16898            if (DEBUG_BACKUP) {
16899                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16900            }
16901            return;
16902        }
16903
16904        // skip interfering stuff, then we're aligned with the backing implementation
16905        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16906Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16907        functor.apply(parser, userId);
16908    }
16909
16910    private interface BlobXmlRestorer {
16911        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16912    }
16913
16914    /**
16915     * Non-Binder method, support for the backup/restore mechanism: write the
16916     * full set of preferred activities in its canonical XML format.  Returns the
16917     * XML output as a byte array, or null if there is none.
16918     */
16919    @Override
16920    public byte[] getPreferredActivityBackup(int userId) {
16921        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16922            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16923        }
16924
16925        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16926        try {
16927            final XmlSerializer serializer = new FastXmlSerializer();
16928            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16929            serializer.startDocument(null, true);
16930            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16931
16932            synchronized (mPackages) {
16933                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16934            }
16935
16936            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16937            serializer.endDocument();
16938            serializer.flush();
16939        } catch (Exception e) {
16940            if (DEBUG_BACKUP) {
16941                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16942            }
16943            return null;
16944        }
16945
16946        return dataStream.toByteArray();
16947    }
16948
16949    @Override
16950    public void restorePreferredActivities(byte[] backup, int userId) {
16951        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16952            throw new SecurityException("Only the system may call restorePreferredActivities()");
16953        }
16954
16955        try {
16956            final XmlPullParser parser = Xml.newPullParser();
16957            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16958            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16959                    new BlobXmlRestorer() {
16960                        @Override
16961                        public void apply(XmlPullParser parser, int userId)
16962                                throws XmlPullParserException, IOException {
16963                            synchronized (mPackages) {
16964                                mSettings.readPreferredActivitiesLPw(parser, userId);
16965                            }
16966                        }
16967                    } );
16968        } catch (Exception e) {
16969            if (DEBUG_BACKUP) {
16970                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16971            }
16972        }
16973    }
16974
16975    /**
16976     * Non-Binder method, support for the backup/restore mechanism: write the
16977     * default browser (etc) settings in its canonical XML format.  Returns the default
16978     * browser XML representation as a byte array, or null if there is none.
16979     */
16980    @Override
16981    public byte[] getDefaultAppsBackup(int userId) {
16982        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16983            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16984        }
16985
16986        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16987        try {
16988            final XmlSerializer serializer = new FastXmlSerializer();
16989            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16990            serializer.startDocument(null, true);
16991            serializer.startTag(null, TAG_DEFAULT_APPS);
16992
16993            synchronized (mPackages) {
16994                mSettings.writeDefaultAppsLPr(serializer, userId);
16995            }
16996
16997            serializer.endTag(null, TAG_DEFAULT_APPS);
16998            serializer.endDocument();
16999            serializer.flush();
17000        } catch (Exception e) {
17001            if (DEBUG_BACKUP) {
17002                Slog.e(TAG, "Unable to write default apps for backup", e);
17003            }
17004            return null;
17005        }
17006
17007        return dataStream.toByteArray();
17008    }
17009
17010    @Override
17011    public void restoreDefaultApps(byte[] backup, int userId) {
17012        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17013            throw new SecurityException("Only the system may call restoreDefaultApps()");
17014        }
17015
17016        try {
17017            final XmlPullParser parser = Xml.newPullParser();
17018            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17019            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17020                    new BlobXmlRestorer() {
17021                        @Override
17022                        public void apply(XmlPullParser parser, int userId)
17023                                throws XmlPullParserException, IOException {
17024                            synchronized (mPackages) {
17025                                mSettings.readDefaultAppsLPw(parser, userId);
17026                            }
17027                        }
17028                    } );
17029        } catch (Exception e) {
17030            if (DEBUG_BACKUP) {
17031                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17032            }
17033        }
17034    }
17035
17036    @Override
17037    public byte[] getIntentFilterVerificationBackup(int userId) {
17038        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17039            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
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_INTENT_FILTER_VERIFICATION);
17048
17049            synchronized (mPackages) {
17050                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17051            }
17052
17053            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
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 restoreIntentFilterVerification(byte[] backup, int userId) {
17068        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17069            throw new SecurityException("Only the system may call restorePreferredActivities()");
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_INTENT_FILTER_VERIFICATION,
17076                    new BlobXmlRestorer() {
17077                        @Override
17078                        public void apply(XmlPullParser parser, int userId)
17079                                throws XmlPullParserException, IOException {
17080                            synchronized (mPackages) {
17081                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17082                                mSettings.writeLPr();
17083                            }
17084                        }
17085                    } );
17086        } catch (Exception e) {
17087            if (DEBUG_BACKUP) {
17088                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17089            }
17090        }
17091    }
17092
17093    @Override
17094    public byte[] getPermissionGrantBackup(int userId) {
17095        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17096            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17097        }
17098
17099        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17100        try {
17101            final XmlSerializer serializer = new FastXmlSerializer();
17102            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17103            serializer.startDocument(null, true);
17104            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17105
17106            synchronized (mPackages) {
17107                serializeRuntimePermissionGrantsLPr(serializer, userId);
17108            }
17109
17110            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17111            serializer.endDocument();
17112            serializer.flush();
17113        } catch (Exception e) {
17114            if (DEBUG_BACKUP) {
17115                Slog.e(TAG, "Unable to write default apps for backup", e);
17116            }
17117            return null;
17118        }
17119
17120        return dataStream.toByteArray();
17121    }
17122
17123    @Override
17124    public void restorePermissionGrants(byte[] backup, int userId) {
17125        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17126            throw new SecurityException("Only the system may call restorePermissionGrants()");
17127        }
17128
17129        try {
17130            final XmlPullParser parser = Xml.newPullParser();
17131            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17132            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17133                    new BlobXmlRestorer() {
17134                        @Override
17135                        public void apply(XmlPullParser parser, int userId)
17136                                throws XmlPullParserException, IOException {
17137                            synchronized (mPackages) {
17138                                processRestoredPermissionGrantsLPr(parser, userId);
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    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17150            throws IOException {
17151        serializer.startTag(null, TAG_ALL_GRANTS);
17152
17153        final int N = mSettings.mPackages.size();
17154        for (int i = 0; i < N; i++) {
17155            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17156            boolean pkgGrantsKnown = false;
17157
17158            PermissionsState packagePerms = ps.getPermissionsState();
17159
17160            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17161                final int grantFlags = state.getFlags();
17162                // only look at grants that are not system/policy fixed
17163                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17164                    final boolean isGranted = state.isGranted();
17165                    // And only back up the user-twiddled state bits
17166                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17167                        final String packageName = mSettings.mPackages.keyAt(i);
17168                        if (!pkgGrantsKnown) {
17169                            serializer.startTag(null, TAG_GRANT);
17170                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17171                            pkgGrantsKnown = true;
17172                        }
17173
17174                        final boolean userSet =
17175                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17176                        final boolean userFixed =
17177                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17178                        final boolean revoke =
17179                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17180
17181                        serializer.startTag(null, TAG_PERMISSION);
17182                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17183                        if (isGranted) {
17184                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17185                        }
17186                        if (userSet) {
17187                            serializer.attribute(null, ATTR_USER_SET, "true");
17188                        }
17189                        if (userFixed) {
17190                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17191                        }
17192                        if (revoke) {
17193                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17194                        }
17195                        serializer.endTag(null, TAG_PERMISSION);
17196                    }
17197                }
17198            }
17199
17200            if (pkgGrantsKnown) {
17201                serializer.endTag(null, TAG_GRANT);
17202            }
17203        }
17204
17205        serializer.endTag(null, TAG_ALL_GRANTS);
17206    }
17207
17208    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17209            throws XmlPullParserException, IOException {
17210        String pkgName = null;
17211        int outerDepth = parser.getDepth();
17212        int type;
17213        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17214                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17215            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17216                continue;
17217            }
17218
17219            final String tagName = parser.getName();
17220            if (tagName.equals(TAG_GRANT)) {
17221                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17222                if (DEBUG_BACKUP) {
17223                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17224                }
17225            } else if (tagName.equals(TAG_PERMISSION)) {
17226
17227                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17228                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17229
17230                int newFlagSet = 0;
17231                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17232                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17233                }
17234                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17235                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17236                }
17237                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17238                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17239                }
17240                if (DEBUG_BACKUP) {
17241                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17242                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17243                }
17244                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17245                if (ps != null) {
17246                    // Already installed so we apply the grant immediately
17247                    if (DEBUG_BACKUP) {
17248                        Slog.v(TAG, "        + already installed; applying");
17249                    }
17250                    PermissionsState perms = ps.getPermissionsState();
17251                    BasePermission bp = mSettings.mPermissions.get(permName);
17252                    if (bp != null) {
17253                        if (isGranted) {
17254                            perms.grantRuntimePermission(bp, userId);
17255                        }
17256                        if (newFlagSet != 0) {
17257                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17258                        }
17259                    }
17260                } else {
17261                    // Need to wait for post-restore install to apply the grant
17262                    if (DEBUG_BACKUP) {
17263                        Slog.v(TAG, "        - not yet installed; saving for later");
17264                    }
17265                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17266                            isGranted, newFlagSet, userId);
17267                }
17268            } else {
17269                PackageManagerService.reportSettingsProblem(Log.WARN,
17270                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17271                XmlUtils.skipCurrentTag(parser);
17272            }
17273        }
17274
17275        scheduleWriteSettingsLocked();
17276        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17277    }
17278
17279    @Override
17280    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17281            int sourceUserId, int targetUserId, int flags) {
17282        mContext.enforceCallingOrSelfPermission(
17283                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17284        int callingUid = Binder.getCallingUid();
17285        enforceOwnerRights(ownerPackage, callingUid);
17286        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17287        if (intentFilter.countActions() == 0) {
17288            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17289            return;
17290        }
17291        synchronized (mPackages) {
17292            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17293                    ownerPackage, targetUserId, flags);
17294            CrossProfileIntentResolver resolver =
17295                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17296            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17297            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17298            if (existing != null) {
17299                int size = existing.size();
17300                for (int i = 0; i < size; i++) {
17301                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17302                        return;
17303                    }
17304                }
17305            }
17306            resolver.addFilter(newFilter);
17307            scheduleWritePackageRestrictionsLocked(sourceUserId);
17308        }
17309    }
17310
17311    @Override
17312    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17313        mContext.enforceCallingOrSelfPermission(
17314                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17315        int callingUid = Binder.getCallingUid();
17316        enforceOwnerRights(ownerPackage, callingUid);
17317        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17318        synchronized (mPackages) {
17319            CrossProfileIntentResolver resolver =
17320                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17321            ArraySet<CrossProfileIntentFilter> set =
17322                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17323            for (CrossProfileIntentFilter filter : set) {
17324                if (filter.getOwnerPackage().equals(ownerPackage)) {
17325                    resolver.removeFilter(filter);
17326                }
17327            }
17328            scheduleWritePackageRestrictionsLocked(sourceUserId);
17329        }
17330    }
17331
17332    // Enforcing that callingUid is owning pkg on userId
17333    private void enforceOwnerRights(String pkg, int callingUid) {
17334        // The system owns everything.
17335        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17336            return;
17337        }
17338        int callingUserId = UserHandle.getUserId(callingUid);
17339        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17340        if (pi == null) {
17341            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17342                    + callingUserId);
17343        }
17344        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17345            throw new SecurityException("Calling uid " + callingUid
17346                    + " does not own package " + pkg);
17347        }
17348    }
17349
17350    @Override
17351    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17352        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17353    }
17354
17355    private Intent getHomeIntent() {
17356        Intent intent = new Intent(Intent.ACTION_MAIN);
17357        intent.addCategory(Intent.CATEGORY_HOME);
17358        return intent;
17359    }
17360
17361    private IntentFilter getHomeFilter() {
17362        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17363        filter.addCategory(Intent.CATEGORY_HOME);
17364        filter.addCategory(Intent.CATEGORY_DEFAULT);
17365        return filter;
17366    }
17367
17368    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17369            int userId) {
17370        Intent intent  = getHomeIntent();
17371        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17372                PackageManager.GET_META_DATA, userId);
17373        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17374                true, false, false, userId);
17375
17376        allHomeCandidates.clear();
17377        if (list != null) {
17378            for (ResolveInfo ri : list) {
17379                allHomeCandidates.add(ri);
17380            }
17381        }
17382        return (preferred == null || preferred.activityInfo == null)
17383                ? null
17384                : new ComponentName(preferred.activityInfo.packageName,
17385                        preferred.activityInfo.name);
17386    }
17387
17388    @Override
17389    public void setHomeActivity(ComponentName comp, int userId) {
17390        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17391        getHomeActivitiesAsUser(homeActivities, userId);
17392
17393        boolean found = false;
17394
17395        final int size = homeActivities.size();
17396        final ComponentName[] set = new ComponentName[size];
17397        for (int i = 0; i < size; i++) {
17398            final ResolveInfo candidate = homeActivities.get(i);
17399            final ActivityInfo info = candidate.activityInfo;
17400            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17401            set[i] = activityName;
17402            if (!found && activityName.equals(comp)) {
17403                found = true;
17404            }
17405        }
17406        if (!found) {
17407            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17408                    + userId);
17409        }
17410        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17411                set, comp, userId);
17412    }
17413
17414    private @Nullable String getSetupWizardPackageName() {
17415        final Intent intent = new Intent(Intent.ACTION_MAIN);
17416        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17417
17418        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17419                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17420                        | MATCH_DISABLED_COMPONENTS,
17421                UserHandle.myUserId());
17422        if (matches.size() == 1) {
17423            return matches.get(0).getComponentInfo().packageName;
17424        } else {
17425            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17426                    + ": matches=" + matches);
17427            return null;
17428        }
17429    }
17430
17431    @Override
17432    public void setApplicationEnabledSetting(String appPackageName,
17433            int newState, int flags, int userId, String callingPackage) {
17434        if (!sUserManager.exists(userId)) return;
17435        if (callingPackage == null) {
17436            callingPackage = Integer.toString(Binder.getCallingUid());
17437        }
17438        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17439    }
17440
17441    @Override
17442    public void setComponentEnabledSetting(ComponentName componentName,
17443            int newState, int flags, int userId) {
17444        if (!sUserManager.exists(userId)) return;
17445        setEnabledSetting(componentName.getPackageName(),
17446                componentName.getClassName(), newState, flags, userId, null);
17447    }
17448
17449    private void setEnabledSetting(final String packageName, String className, int newState,
17450            final int flags, int userId, String callingPackage) {
17451        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17452              || newState == COMPONENT_ENABLED_STATE_ENABLED
17453              || newState == COMPONENT_ENABLED_STATE_DISABLED
17454              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17455              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17456            throw new IllegalArgumentException("Invalid new component state: "
17457                    + newState);
17458        }
17459        PackageSetting pkgSetting;
17460        final int uid = Binder.getCallingUid();
17461        final int permission;
17462        if (uid == Process.SYSTEM_UID) {
17463            permission = PackageManager.PERMISSION_GRANTED;
17464        } else {
17465            permission = mContext.checkCallingOrSelfPermission(
17466                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17467        }
17468        enforceCrossUserPermission(uid, userId,
17469                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17470        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17471        boolean sendNow = false;
17472        boolean isApp = (className == null);
17473        String componentName = isApp ? packageName : className;
17474        int packageUid = -1;
17475        ArrayList<String> components;
17476
17477        // writer
17478        synchronized (mPackages) {
17479            pkgSetting = mSettings.mPackages.get(packageName);
17480            if (pkgSetting == null) {
17481                if (className == null) {
17482                    throw new IllegalArgumentException("Unknown package: " + packageName);
17483                }
17484                throw new IllegalArgumentException(
17485                        "Unknown component: " + packageName + "/" + className);
17486            }
17487            // Allow root and verify that userId is not being specified by a different user
17488            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17489                throw new SecurityException(
17490                        "Permission Denial: attempt to change component state from pid="
17491                        + Binder.getCallingPid()
17492                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17493            }
17494            if (className == null) {
17495                // We're dealing with an application/package level state change
17496                if (pkgSetting.getEnabled(userId) == newState) {
17497                    // Nothing to do
17498                    return;
17499                }
17500                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17501                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17502                    // Don't care about who enables an app.
17503                    callingPackage = null;
17504                }
17505                pkgSetting.setEnabled(newState, userId, callingPackage);
17506                // pkgSetting.pkg.mSetEnabled = newState;
17507            } else {
17508                // We're dealing with a component level state change
17509                // First, verify that this is a valid class name.
17510                PackageParser.Package pkg = pkgSetting.pkg;
17511                if (pkg == null || !pkg.hasComponentClassName(className)) {
17512                    if (pkg != null &&
17513                            pkg.applicationInfo.targetSdkVersion >=
17514                                    Build.VERSION_CODES.JELLY_BEAN) {
17515                        throw new IllegalArgumentException("Component class " + className
17516                                + " does not exist in " + packageName);
17517                    } else {
17518                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17519                                + className + " does not exist in " + packageName);
17520                    }
17521                }
17522                switch (newState) {
17523                case COMPONENT_ENABLED_STATE_ENABLED:
17524                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17525                        return;
17526                    }
17527                    break;
17528                case COMPONENT_ENABLED_STATE_DISABLED:
17529                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17530                        return;
17531                    }
17532                    break;
17533                case COMPONENT_ENABLED_STATE_DEFAULT:
17534                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17535                        return;
17536                    }
17537                    break;
17538                default:
17539                    Slog.e(TAG, "Invalid new component state: " + newState);
17540                    return;
17541                }
17542            }
17543            scheduleWritePackageRestrictionsLocked(userId);
17544            components = mPendingBroadcasts.get(userId, packageName);
17545            final boolean newPackage = components == null;
17546            if (newPackage) {
17547                components = new ArrayList<String>();
17548            }
17549            if (!components.contains(componentName)) {
17550                components.add(componentName);
17551            }
17552            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17553                sendNow = true;
17554                // Purge entry from pending broadcast list if another one exists already
17555                // since we are sending one right away.
17556                mPendingBroadcasts.remove(userId, packageName);
17557            } else {
17558                if (newPackage) {
17559                    mPendingBroadcasts.put(userId, packageName, components);
17560                }
17561                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17562                    // Schedule a message
17563                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17564                }
17565            }
17566        }
17567
17568        long callingId = Binder.clearCallingIdentity();
17569        try {
17570            if (sendNow) {
17571                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17572                sendPackageChangedBroadcast(packageName,
17573                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17574            }
17575        } finally {
17576            Binder.restoreCallingIdentity(callingId);
17577        }
17578    }
17579
17580    @Override
17581    public void flushPackageRestrictionsAsUser(int userId) {
17582        if (!sUserManager.exists(userId)) {
17583            return;
17584        }
17585        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17586                false /* checkShell */, "flushPackageRestrictions");
17587        synchronized (mPackages) {
17588            mSettings.writePackageRestrictionsLPr(userId);
17589            mDirtyUsers.remove(userId);
17590            if (mDirtyUsers.isEmpty()) {
17591                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17592            }
17593        }
17594    }
17595
17596    private void sendPackageChangedBroadcast(String packageName,
17597            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17598        if (DEBUG_INSTALL)
17599            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17600                    + componentNames);
17601        Bundle extras = new Bundle(4);
17602        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17603        String nameList[] = new String[componentNames.size()];
17604        componentNames.toArray(nameList);
17605        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17606        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17607        extras.putInt(Intent.EXTRA_UID, packageUid);
17608        // If this is not reporting a change of the overall package, then only send it
17609        // to registered receivers.  We don't want to launch a swath of apps for every
17610        // little component state change.
17611        final int flags = !componentNames.contains(packageName)
17612                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17613        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17614                new int[] {UserHandle.getUserId(packageUid)});
17615    }
17616
17617    @Override
17618    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17619        if (!sUserManager.exists(userId)) return;
17620        final int uid = Binder.getCallingUid();
17621        final int permission = mContext.checkCallingOrSelfPermission(
17622                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17623        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17624        enforceCrossUserPermission(uid, userId,
17625                true /* requireFullPermission */, true /* checkShell */, "stop package");
17626        // writer
17627        synchronized (mPackages) {
17628            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17629                    allowedByPermission, uid, userId)) {
17630                scheduleWritePackageRestrictionsLocked(userId);
17631            }
17632        }
17633    }
17634
17635    @Override
17636    public String getInstallerPackageName(String packageName) {
17637        // reader
17638        synchronized (mPackages) {
17639            return mSettings.getInstallerPackageNameLPr(packageName);
17640        }
17641    }
17642
17643    public boolean isOrphaned(String packageName) {
17644        // reader
17645        synchronized (mPackages) {
17646            return mSettings.isOrphaned(packageName);
17647        }
17648    }
17649
17650    @Override
17651    public int getApplicationEnabledSetting(String packageName, int userId) {
17652        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17653        int uid = Binder.getCallingUid();
17654        enforceCrossUserPermission(uid, userId,
17655                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17656        // reader
17657        synchronized (mPackages) {
17658            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17659        }
17660    }
17661
17662    @Override
17663    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17664        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17665        int uid = Binder.getCallingUid();
17666        enforceCrossUserPermission(uid, userId,
17667                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17668        // reader
17669        synchronized (mPackages) {
17670            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17671        }
17672    }
17673
17674    @Override
17675    public void enterSafeMode() {
17676        enforceSystemOrRoot("Only the system can request entering safe mode");
17677
17678        if (!mSystemReady) {
17679            mSafeMode = true;
17680        }
17681    }
17682
17683    @Override
17684    public void systemReady() {
17685        mSystemReady = true;
17686
17687        // Read the compatibilty setting when the system is ready.
17688        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17689                mContext.getContentResolver(),
17690                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17691        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17692        if (DEBUG_SETTINGS) {
17693            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17694        }
17695
17696        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17697
17698        synchronized (mPackages) {
17699            // Verify that all of the preferred activity components actually
17700            // exist.  It is possible for applications to be updated and at
17701            // that point remove a previously declared activity component that
17702            // had been set as a preferred activity.  We try to clean this up
17703            // the next time we encounter that preferred activity, but it is
17704            // possible for the user flow to never be able to return to that
17705            // situation so here we do a sanity check to make sure we haven't
17706            // left any junk around.
17707            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17708            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17709                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17710                removed.clear();
17711                for (PreferredActivity pa : pir.filterSet()) {
17712                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17713                        removed.add(pa);
17714                    }
17715                }
17716                if (removed.size() > 0) {
17717                    for (int r=0; r<removed.size(); r++) {
17718                        PreferredActivity pa = removed.get(r);
17719                        Slog.w(TAG, "Removing dangling preferred activity: "
17720                                + pa.mPref.mComponent);
17721                        pir.removeFilter(pa);
17722                    }
17723                    mSettings.writePackageRestrictionsLPr(
17724                            mSettings.mPreferredActivities.keyAt(i));
17725                }
17726            }
17727
17728            for (int userId : UserManagerService.getInstance().getUserIds()) {
17729                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17730                    grantPermissionsUserIds = ArrayUtils.appendInt(
17731                            grantPermissionsUserIds, userId);
17732                }
17733            }
17734        }
17735        sUserManager.systemReady();
17736
17737        // If we upgraded grant all default permissions before kicking off.
17738        for (int userId : grantPermissionsUserIds) {
17739            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17740        }
17741
17742        // Kick off any messages waiting for system ready
17743        if (mPostSystemReadyMessages != null) {
17744            for (Message msg : mPostSystemReadyMessages) {
17745                msg.sendToTarget();
17746            }
17747            mPostSystemReadyMessages = null;
17748        }
17749
17750        // Watch for external volumes that come and go over time
17751        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17752        storage.registerListener(mStorageListener);
17753
17754        mInstallerService.systemReady();
17755        mPackageDexOptimizer.systemReady();
17756
17757        MountServiceInternal mountServiceInternal = LocalServices.getService(
17758                MountServiceInternal.class);
17759        mountServiceInternal.addExternalStoragePolicy(
17760                new MountServiceInternal.ExternalStorageMountPolicy() {
17761            @Override
17762            public int getMountMode(int uid, String packageName) {
17763                if (Process.isIsolated(uid)) {
17764                    return Zygote.MOUNT_EXTERNAL_NONE;
17765                }
17766                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17767                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17768                }
17769                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17770                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17771                }
17772                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17773                    return Zygote.MOUNT_EXTERNAL_READ;
17774                }
17775                return Zygote.MOUNT_EXTERNAL_WRITE;
17776            }
17777
17778            @Override
17779            public boolean hasExternalStorage(int uid, String packageName) {
17780                return true;
17781            }
17782        });
17783
17784        // Now that we're mostly running, clean up stale users and apps
17785        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17786        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17787    }
17788
17789    @Override
17790    public boolean isSafeMode() {
17791        return mSafeMode;
17792    }
17793
17794    @Override
17795    public boolean hasSystemUidErrors() {
17796        return mHasSystemUidErrors;
17797    }
17798
17799    static String arrayToString(int[] array) {
17800        StringBuffer buf = new StringBuffer(128);
17801        buf.append('[');
17802        if (array != null) {
17803            for (int i=0; i<array.length; i++) {
17804                if (i > 0) buf.append(", ");
17805                buf.append(array[i]);
17806            }
17807        }
17808        buf.append(']');
17809        return buf.toString();
17810    }
17811
17812    static class DumpState {
17813        public static final int DUMP_LIBS = 1 << 0;
17814        public static final int DUMP_FEATURES = 1 << 1;
17815        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17816        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17817        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17818        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17819        public static final int DUMP_PERMISSIONS = 1 << 6;
17820        public static final int DUMP_PACKAGES = 1 << 7;
17821        public static final int DUMP_SHARED_USERS = 1 << 8;
17822        public static final int DUMP_MESSAGES = 1 << 9;
17823        public static final int DUMP_PROVIDERS = 1 << 10;
17824        public static final int DUMP_VERIFIERS = 1 << 11;
17825        public static final int DUMP_PREFERRED = 1 << 12;
17826        public static final int DUMP_PREFERRED_XML = 1 << 13;
17827        public static final int DUMP_KEYSETS = 1 << 14;
17828        public static final int DUMP_VERSION = 1 << 15;
17829        public static final int DUMP_INSTALLS = 1 << 16;
17830        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17831        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17832        public static final int DUMP_FROZEN = 1 << 19;
17833        public static final int DUMP_DEXOPT = 1 << 20;
17834
17835        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17836
17837        private int mTypes;
17838
17839        private int mOptions;
17840
17841        private boolean mTitlePrinted;
17842
17843        private SharedUserSetting mSharedUser;
17844
17845        public boolean isDumping(int type) {
17846            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17847                return true;
17848            }
17849
17850            return (mTypes & type) != 0;
17851        }
17852
17853        public void setDump(int type) {
17854            mTypes |= type;
17855        }
17856
17857        public boolean isOptionEnabled(int option) {
17858            return (mOptions & option) != 0;
17859        }
17860
17861        public void setOptionEnabled(int option) {
17862            mOptions |= option;
17863        }
17864
17865        public boolean onTitlePrinted() {
17866            final boolean printed = mTitlePrinted;
17867            mTitlePrinted = true;
17868            return printed;
17869        }
17870
17871        public boolean getTitlePrinted() {
17872            return mTitlePrinted;
17873        }
17874
17875        public void setTitlePrinted(boolean enabled) {
17876            mTitlePrinted = enabled;
17877        }
17878
17879        public SharedUserSetting getSharedUser() {
17880            return mSharedUser;
17881        }
17882
17883        public void setSharedUser(SharedUserSetting user) {
17884            mSharedUser = user;
17885        }
17886    }
17887
17888    @Override
17889    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17890            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17891        (new PackageManagerShellCommand(this)).exec(
17892                this, in, out, err, args, resultReceiver);
17893    }
17894
17895    @Override
17896    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17897        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17898                != PackageManager.PERMISSION_GRANTED) {
17899            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17900                    + Binder.getCallingPid()
17901                    + ", uid=" + Binder.getCallingUid()
17902                    + " without permission "
17903                    + android.Manifest.permission.DUMP);
17904            return;
17905        }
17906
17907        DumpState dumpState = new DumpState();
17908        boolean fullPreferred = false;
17909        boolean checkin = false;
17910
17911        String packageName = null;
17912        ArraySet<String> permissionNames = null;
17913
17914        int opti = 0;
17915        while (opti < args.length) {
17916            String opt = args[opti];
17917            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17918                break;
17919            }
17920            opti++;
17921
17922            if ("-a".equals(opt)) {
17923                // Right now we only know how to print all.
17924            } else if ("-h".equals(opt)) {
17925                pw.println("Package manager dump options:");
17926                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17927                pw.println("    --checkin: dump for a checkin");
17928                pw.println("    -f: print details of intent filters");
17929                pw.println("    -h: print this help");
17930                pw.println("  cmd may be one of:");
17931                pw.println("    l[ibraries]: list known shared libraries");
17932                pw.println("    f[eatures]: list device features");
17933                pw.println("    k[eysets]: print known keysets");
17934                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17935                pw.println("    perm[issions]: dump permissions");
17936                pw.println("    permission [name ...]: dump declaration and use of given permission");
17937                pw.println("    pref[erred]: print preferred package settings");
17938                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17939                pw.println("    prov[iders]: dump content providers");
17940                pw.println("    p[ackages]: dump installed packages");
17941                pw.println("    s[hared-users]: dump shared user IDs");
17942                pw.println("    m[essages]: print collected runtime messages");
17943                pw.println("    v[erifiers]: print package verifier info");
17944                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17945                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17946                pw.println("    version: print database version info");
17947                pw.println("    write: write current settings now");
17948                pw.println("    installs: details about install sessions");
17949                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17950                pw.println("    dexopt: dump dexopt state");
17951                pw.println("    <package.name>: info about given package");
17952                return;
17953            } else if ("--checkin".equals(opt)) {
17954                checkin = true;
17955            } else if ("-f".equals(opt)) {
17956                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17957            } else {
17958                pw.println("Unknown argument: " + opt + "; use -h for help");
17959            }
17960        }
17961
17962        // Is the caller requesting to dump a particular piece of data?
17963        if (opti < args.length) {
17964            String cmd = args[opti];
17965            opti++;
17966            // Is this a package name?
17967            if ("android".equals(cmd) || cmd.contains(".")) {
17968                packageName = cmd;
17969                // When dumping a single package, we always dump all of its
17970                // filter information since the amount of data will be reasonable.
17971                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17972            } else if ("check-permission".equals(cmd)) {
17973                if (opti >= args.length) {
17974                    pw.println("Error: check-permission missing permission argument");
17975                    return;
17976                }
17977                String perm = args[opti];
17978                opti++;
17979                if (opti >= args.length) {
17980                    pw.println("Error: check-permission missing package argument");
17981                    return;
17982                }
17983                String pkg = args[opti];
17984                opti++;
17985                int user = UserHandle.getUserId(Binder.getCallingUid());
17986                if (opti < args.length) {
17987                    try {
17988                        user = Integer.parseInt(args[opti]);
17989                    } catch (NumberFormatException e) {
17990                        pw.println("Error: check-permission user argument is not a number: "
17991                                + args[opti]);
17992                        return;
17993                    }
17994                }
17995                pw.println(checkPermission(perm, pkg, user));
17996                return;
17997            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17998                dumpState.setDump(DumpState.DUMP_LIBS);
17999            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18000                dumpState.setDump(DumpState.DUMP_FEATURES);
18001            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18002                if (opti >= args.length) {
18003                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18004                            | DumpState.DUMP_SERVICE_RESOLVERS
18005                            | DumpState.DUMP_RECEIVER_RESOLVERS
18006                            | DumpState.DUMP_CONTENT_RESOLVERS);
18007                } else {
18008                    while (opti < args.length) {
18009                        String name = args[opti];
18010                        if ("a".equals(name) || "activity".equals(name)) {
18011                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18012                        } else if ("s".equals(name) || "service".equals(name)) {
18013                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18014                        } else if ("r".equals(name) || "receiver".equals(name)) {
18015                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18016                        } else if ("c".equals(name) || "content".equals(name)) {
18017                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18018                        } else {
18019                            pw.println("Error: unknown resolver table type: " + name);
18020                            return;
18021                        }
18022                        opti++;
18023                    }
18024                }
18025            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18026                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18027            } else if ("permission".equals(cmd)) {
18028                if (opti >= args.length) {
18029                    pw.println("Error: permission requires permission name");
18030                    return;
18031                }
18032                permissionNames = new ArraySet<>();
18033                while (opti < args.length) {
18034                    permissionNames.add(args[opti]);
18035                    opti++;
18036                }
18037                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18038                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18039            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18040                dumpState.setDump(DumpState.DUMP_PREFERRED);
18041            } else if ("preferred-xml".equals(cmd)) {
18042                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18043                if (opti < args.length && "--full".equals(args[opti])) {
18044                    fullPreferred = true;
18045                    opti++;
18046                }
18047            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18048                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18049            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18050                dumpState.setDump(DumpState.DUMP_PACKAGES);
18051            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18052                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18053            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18054                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18055            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18056                dumpState.setDump(DumpState.DUMP_MESSAGES);
18057            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18058                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18059            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18060                    || "intent-filter-verifiers".equals(cmd)) {
18061                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18062            } else if ("version".equals(cmd)) {
18063                dumpState.setDump(DumpState.DUMP_VERSION);
18064            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18065                dumpState.setDump(DumpState.DUMP_KEYSETS);
18066            } else if ("installs".equals(cmd)) {
18067                dumpState.setDump(DumpState.DUMP_INSTALLS);
18068            } else if ("frozen".equals(cmd)) {
18069                dumpState.setDump(DumpState.DUMP_FROZEN);
18070            } else if ("dexopt".equals(cmd)) {
18071                dumpState.setDump(DumpState.DUMP_DEXOPT);
18072            } else if ("write".equals(cmd)) {
18073                synchronized (mPackages) {
18074                    mSettings.writeLPr();
18075                    pw.println("Settings written.");
18076                    return;
18077                }
18078            }
18079        }
18080
18081        if (checkin) {
18082            pw.println("vers,1");
18083        }
18084
18085        // reader
18086        synchronized (mPackages) {
18087            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18088                if (!checkin) {
18089                    if (dumpState.onTitlePrinted())
18090                        pw.println();
18091                    pw.println("Database versions:");
18092                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18093                }
18094            }
18095
18096            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18097                if (!checkin) {
18098                    if (dumpState.onTitlePrinted())
18099                        pw.println();
18100                    pw.println("Verifiers:");
18101                    pw.print("  Required: ");
18102                    pw.print(mRequiredVerifierPackage);
18103                    pw.print(" (uid=");
18104                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18105                            UserHandle.USER_SYSTEM));
18106                    pw.println(")");
18107                } else if (mRequiredVerifierPackage != null) {
18108                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18109                    pw.print(",");
18110                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18111                            UserHandle.USER_SYSTEM));
18112                }
18113            }
18114
18115            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18116                    packageName == null) {
18117                if (mIntentFilterVerifierComponent != null) {
18118                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18119                    if (!checkin) {
18120                        if (dumpState.onTitlePrinted())
18121                            pw.println();
18122                        pw.println("Intent Filter Verifier:");
18123                        pw.print("  Using: ");
18124                        pw.print(verifierPackageName);
18125                        pw.print(" (uid=");
18126                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18127                                UserHandle.USER_SYSTEM));
18128                        pw.println(")");
18129                    } else if (verifierPackageName != null) {
18130                        pw.print("ifv,"); pw.print(verifierPackageName);
18131                        pw.print(",");
18132                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18133                                UserHandle.USER_SYSTEM));
18134                    }
18135                } else {
18136                    pw.println();
18137                    pw.println("No Intent Filter Verifier available!");
18138                }
18139            }
18140
18141            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18142                boolean printedHeader = false;
18143                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18144                while (it.hasNext()) {
18145                    String name = it.next();
18146                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18147                    if (!checkin) {
18148                        if (!printedHeader) {
18149                            if (dumpState.onTitlePrinted())
18150                                pw.println();
18151                            pw.println("Libraries:");
18152                            printedHeader = true;
18153                        }
18154                        pw.print("  ");
18155                    } else {
18156                        pw.print("lib,");
18157                    }
18158                    pw.print(name);
18159                    if (!checkin) {
18160                        pw.print(" -> ");
18161                    }
18162                    if (ent.path != null) {
18163                        if (!checkin) {
18164                            pw.print("(jar) ");
18165                            pw.print(ent.path);
18166                        } else {
18167                            pw.print(",jar,");
18168                            pw.print(ent.path);
18169                        }
18170                    } else {
18171                        if (!checkin) {
18172                            pw.print("(apk) ");
18173                            pw.print(ent.apk);
18174                        } else {
18175                            pw.print(",apk,");
18176                            pw.print(ent.apk);
18177                        }
18178                    }
18179                    pw.println();
18180                }
18181            }
18182
18183            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18184                if (dumpState.onTitlePrinted())
18185                    pw.println();
18186                if (!checkin) {
18187                    pw.println("Features:");
18188                }
18189
18190                for (FeatureInfo feat : mAvailableFeatures.values()) {
18191                    if (checkin) {
18192                        pw.print("feat,");
18193                        pw.print(feat.name);
18194                        pw.print(",");
18195                        pw.println(feat.version);
18196                    } else {
18197                        pw.print("  ");
18198                        pw.print(feat.name);
18199                        if (feat.version > 0) {
18200                            pw.print(" version=");
18201                            pw.print(feat.version);
18202                        }
18203                        pw.println();
18204                    }
18205                }
18206            }
18207
18208            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18209                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18210                        : "Activity Resolver Table:", "  ", packageName,
18211                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18212                    dumpState.setTitlePrinted(true);
18213                }
18214            }
18215            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18216                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18217                        : "Receiver Resolver Table:", "  ", packageName,
18218                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18219                    dumpState.setTitlePrinted(true);
18220                }
18221            }
18222            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18223                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18224                        : "Service Resolver Table:", "  ", packageName,
18225                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18226                    dumpState.setTitlePrinted(true);
18227                }
18228            }
18229            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18230                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18231                        : "Provider Resolver Table:", "  ", packageName,
18232                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18233                    dumpState.setTitlePrinted(true);
18234                }
18235            }
18236
18237            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18238                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18239                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18240                    int user = mSettings.mPreferredActivities.keyAt(i);
18241                    if (pir.dump(pw,
18242                            dumpState.getTitlePrinted()
18243                                ? "\nPreferred Activities User " + user + ":"
18244                                : "Preferred Activities User " + user + ":", "  ",
18245                            packageName, true, false)) {
18246                        dumpState.setTitlePrinted(true);
18247                    }
18248                }
18249            }
18250
18251            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18252                pw.flush();
18253                FileOutputStream fout = new FileOutputStream(fd);
18254                BufferedOutputStream str = new BufferedOutputStream(fout);
18255                XmlSerializer serializer = new FastXmlSerializer();
18256                try {
18257                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18258                    serializer.startDocument(null, true);
18259                    serializer.setFeature(
18260                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18261                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18262                    serializer.endDocument();
18263                    serializer.flush();
18264                } catch (IllegalArgumentException e) {
18265                    pw.println("Failed writing: " + e);
18266                } catch (IllegalStateException e) {
18267                    pw.println("Failed writing: " + e);
18268                } catch (IOException e) {
18269                    pw.println("Failed writing: " + e);
18270                }
18271            }
18272
18273            if (!checkin
18274                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18275                    && packageName == null) {
18276                pw.println();
18277                int count = mSettings.mPackages.size();
18278                if (count == 0) {
18279                    pw.println("No applications!");
18280                    pw.println();
18281                } else {
18282                    final String prefix = "  ";
18283                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18284                    if (allPackageSettings.size() == 0) {
18285                        pw.println("No domain preferred apps!");
18286                        pw.println();
18287                    } else {
18288                        pw.println("App verification status:");
18289                        pw.println();
18290                        count = 0;
18291                        for (PackageSetting ps : allPackageSettings) {
18292                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18293                            if (ivi == null || ivi.getPackageName() == null) continue;
18294                            pw.println(prefix + "Package: " + ivi.getPackageName());
18295                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18296                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18297                            pw.println();
18298                            count++;
18299                        }
18300                        if (count == 0) {
18301                            pw.println(prefix + "No app verification established.");
18302                            pw.println();
18303                        }
18304                        for (int userId : sUserManager.getUserIds()) {
18305                            pw.println("App linkages for user " + userId + ":");
18306                            pw.println();
18307                            count = 0;
18308                            for (PackageSetting ps : allPackageSettings) {
18309                                final long status = ps.getDomainVerificationStatusForUser(userId);
18310                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18311                                    continue;
18312                                }
18313                                pw.println(prefix + "Package: " + ps.name);
18314                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18315                                String statusStr = IntentFilterVerificationInfo.
18316                                        getStatusStringFromValue(status);
18317                                pw.println(prefix + "Status:  " + statusStr);
18318                                pw.println();
18319                                count++;
18320                            }
18321                            if (count == 0) {
18322                                pw.println(prefix + "No configured app linkages.");
18323                                pw.println();
18324                            }
18325                        }
18326                    }
18327                }
18328            }
18329
18330            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18331                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18332                if (packageName == null && permissionNames == null) {
18333                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18334                        if (iperm == 0) {
18335                            if (dumpState.onTitlePrinted())
18336                                pw.println();
18337                            pw.println("AppOp Permissions:");
18338                        }
18339                        pw.print("  AppOp Permission ");
18340                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18341                        pw.println(":");
18342                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18343                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18344                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18345                        }
18346                    }
18347                }
18348            }
18349
18350            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18351                boolean printedSomething = false;
18352                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18353                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18354                        continue;
18355                    }
18356                    if (!printedSomething) {
18357                        if (dumpState.onTitlePrinted())
18358                            pw.println();
18359                        pw.println("Registered ContentProviders:");
18360                        printedSomething = true;
18361                    }
18362                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18363                    pw.print("    "); pw.println(p.toString());
18364                }
18365                printedSomething = false;
18366                for (Map.Entry<String, PackageParser.Provider> entry :
18367                        mProvidersByAuthority.entrySet()) {
18368                    PackageParser.Provider p = entry.getValue();
18369                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18370                        continue;
18371                    }
18372                    if (!printedSomething) {
18373                        if (dumpState.onTitlePrinted())
18374                            pw.println();
18375                        pw.println("ContentProvider Authorities:");
18376                        printedSomething = true;
18377                    }
18378                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18379                    pw.print("    "); pw.println(p.toString());
18380                    if (p.info != null && p.info.applicationInfo != null) {
18381                        final String appInfo = p.info.applicationInfo.toString();
18382                        pw.print("      applicationInfo="); pw.println(appInfo);
18383                    }
18384                }
18385            }
18386
18387            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18388                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18389            }
18390
18391            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18392                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18393            }
18394
18395            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18396                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18397            }
18398
18399            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18400                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18401            }
18402
18403            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18404                // XXX should handle packageName != null by dumping only install data that
18405                // the given package is involved with.
18406                if (dumpState.onTitlePrinted()) pw.println();
18407                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18408            }
18409
18410            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18411                // XXX should handle packageName != null by dumping only install data that
18412                // the given package is involved with.
18413                if (dumpState.onTitlePrinted()) pw.println();
18414
18415                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18416                ipw.println();
18417                ipw.println("Frozen packages:");
18418                ipw.increaseIndent();
18419                if (mFrozenPackages.size() == 0) {
18420                    ipw.println("(none)");
18421                } else {
18422                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18423                        ipw.println(mFrozenPackages.valueAt(i));
18424                    }
18425                }
18426                ipw.decreaseIndent();
18427            }
18428
18429            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18430                if (dumpState.onTitlePrinted()) pw.println();
18431                dumpDexoptStateLPr(pw, packageName);
18432            }
18433
18434            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18435                if (dumpState.onTitlePrinted()) pw.println();
18436                mSettings.dumpReadMessagesLPr(pw, dumpState);
18437
18438                pw.println();
18439                pw.println("Package warning messages:");
18440                BufferedReader in = null;
18441                String line = null;
18442                try {
18443                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18444                    while ((line = in.readLine()) != null) {
18445                        if (line.contains("ignored: updated version")) continue;
18446                        pw.println(line);
18447                    }
18448                } catch (IOException ignored) {
18449                } finally {
18450                    IoUtils.closeQuietly(in);
18451                }
18452            }
18453
18454            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18455                BufferedReader in = null;
18456                String line = null;
18457                try {
18458                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18459                    while ((line = in.readLine()) != null) {
18460                        if (line.contains("ignored: updated version")) continue;
18461                        pw.print("msg,");
18462                        pw.println(line);
18463                    }
18464                } catch (IOException ignored) {
18465                } finally {
18466                    IoUtils.closeQuietly(in);
18467                }
18468            }
18469        }
18470    }
18471
18472    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18473        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18474        ipw.println();
18475        ipw.println("Dexopt state:");
18476        ipw.increaseIndent();
18477        Collection<PackageParser.Package> packages = null;
18478        if (packageName != null) {
18479            PackageParser.Package targetPackage = mPackages.get(packageName);
18480            if (targetPackage != null) {
18481                packages = Collections.singletonList(targetPackage);
18482            } else {
18483                ipw.println("Unable to find package: " + packageName);
18484                return;
18485            }
18486        } else {
18487            packages = mPackages.values();
18488        }
18489
18490        for (PackageParser.Package pkg : packages) {
18491            ipw.println("[" + pkg.packageName + "]");
18492            ipw.increaseIndent();
18493            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18494            ipw.decreaseIndent();
18495        }
18496    }
18497
18498    private String dumpDomainString(String packageName) {
18499        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18500                .getList();
18501        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18502
18503        ArraySet<String> result = new ArraySet<>();
18504        if (iviList.size() > 0) {
18505            for (IntentFilterVerificationInfo ivi : iviList) {
18506                for (String host : ivi.getDomains()) {
18507                    result.add(host);
18508                }
18509            }
18510        }
18511        if (filters != null && filters.size() > 0) {
18512            for (IntentFilter filter : filters) {
18513                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18514                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18515                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18516                    result.addAll(filter.getHostsList());
18517                }
18518            }
18519        }
18520
18521        StringBuilder sb = new StringBuilder(result.size() * 16);
18522        for (String domain : result) {
18523            if (sb.length() > 0) sb.append(" ");
18524            sb.append(domain);
18525        }
18526        return sb.toString();
18527    }
18528
18529    // ------- apps on sdcard specific code -------
18530    static final boolean DEBUG_SD_INSTALL = false;
18531
18532    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18533
18534    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18535
18536    private boolean mMediaMounted = false;
18537
18538    static String getEncryptKey() {
18539        try {
18540            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18541                    SD_ENCRYPTION_KEYSTORE_NAME);
18542            if (sdEncKey == null) {
18543                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18544                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18545                if (sdEncKey == null) {
18546                    Slog.e(TAG, "Failed to create encryption keys");
18547                    return null;
18548                }
18549            }
18550            return sdEncKey;
18551        } catch (NoSuchAlgorithmException nsae) {
18552            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18553            return null;
18554        } catch (IOException ioe) {
18555            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18556            return null;
18557        }
18558    }
18559
18560    /*
18561     * Update media status on PackageManager.
18562     */
18563    @Override
18564    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18565        int callingUid = Binder.getCallingUid();
18566        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18567            throw new SecurityException("Media status can only be updated by the system");
18568        }
18569        // reader; this apparently protects mMediaMounted, but should probably
18570        // be a different lock in that case.
18571        synchronized (mPackages) {
18572            Log.i(TAG, "Updating external media status from "
18573                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18574                    + (mediaStatus ? "mounted" : "unmounted"));
18575            if (DEBUG_SD_INSTALL)
18576                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18577                        + ", mMediaMounted=" + mMediaMounted);
18578            if (mediaStatus == mMediaMounted) {
18579                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18580                        : 0, -1);
18581                mHandler.sendMessage(msg);
18582                return;
18583            }
18584            mMediaMounted = mediaStatus;
18585        }
18586        // Queue up an async operation since the package installation may take a
18587        // little while.
18588        mHandler.post(new Runnable() {
18589            public void run() {
18590                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18591            }
18592        });
18593    }
18594
18595    /**
18596     * Called by MountService when the initial ASECs to scan are available.
18597     * Should block until all the ASEC containers are finished being scanned.
18598     */
18599    public void scanAvailableAsecs() {
18600        updateExternalMediaStatusInner(true, false, false);
18601    }
18602
18603    /*
18604     * Collect information of applications on external media, map them against
18605     * existing containers and update information based on current mount status.
18606     * Please note that we always have to report status if reportStatus has been
18607     * set to true especially when unloading packages.
18608     */
18609    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18610            boolean externalStorage) {
18611        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18612        int[] uidArr = EmptyArray.INT;
18613
18614        final String[] list = PackageHelper.getSecureContainerList();
18615        if (ArrayUtils.isEmpty(list)) {
18616            Log.i(TAG, "No secure containers found");
18617        } else {
18618            // Process list of secure containers and categorize them
18619            // as active or stale based on their package internal state.
18620
18621            // reader
18622            synchronized (mPackages) {
18623                for (String cid : list) {
18624                    // Leave stages untouched for now; installer service owns them
18625                    if (PackageInstallerService.isStageName(cid)) continue;
18626
18627                    if (DEBUG_SD_INSTALL)
18628                        Log.i(TAG, "Processing container " + cid);
18629                    String pkgName = getAsecPackageName(cid);
18630                    if (pkgName == null) {
18631                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18632                        continue;
18633                    }
18634                    if (DEBUG_SD_INSTALL)
18635                        Log.i(TAG, "Looking for pkg : " + pkgName);
18636
18637                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18638                    if (ps == null) {
18639                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18640                        continue;
18641                    }
18642
18643                    /*
18644                     * Skip packages that are not external if we're unmounting
18645                     * external storage.
18646                     */
18647                    if (externalStorage && !isMounted && !isExternal(ps)) {
18648                        continue;
18649                    }
18650
18651                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18652                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18653                    // The package status is changed only if the code path
18654                    // matches between settings and the container id.
18655                    if (ps.codePathString != null
18656                            && ps.codePathString.startsWith(args.getCodePath())) {
18657                        if (DEBUG_SD_INSTALL) {
18658                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18659                                    + " at code path: " + ps.codePathString);
18660                        }
18661
18662                        // We do have a valid package installed on sdcard
18663                        processCids.put(args, ps.codePathString);
18664                        final int uid = ps.appId;
18665                        if (uid != -1) {
18666                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18667                        }
18668                    } else {
18669                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18670                                + ps.codePathString);
18671                    }
18672                }
18673            }
18674
18675            Arrays.sort(uidArr);
18676        }
18677
18678        // Process packages with valid entries.
18679        if (isMounted) {
18680            if (DEBUG_SD_INSTALL)
18681                Log.i(TAG, "Loading packages");
18682            loadMediaPackages(processCids, uidArr, externalStorage);
18683            startCleaningPackages();
18684            mInstallerService.onSecureContainersAvailable();
18685        } else {
18686            if (DEBUG_SD_INSTALL)
18687                Log.i(TAG, "Unloading packages");
18688            unloadMediaPackages(processCids, uidArr, reportStatus);
18689        }
18690    }
18691
18692    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18693            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18694        final int size = infos.size();
18695        final String[] packageNames = new String[size];
18696        final int[] packageUids = new int[size];
18697        for (int i = 0; i < size; i++) {
18698            final ApplicationInfo info = infos.get(i);
18699            packageNames[i] = info.packageName;
18700            packageUids[i] = info.uid;
18701        }
18702        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18703                finishedReceiver);
18704    }
18705
18706    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18707            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18708        sendResourcesChangedBroadcast(mediaStatus, replacing,
18709                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18710    }
18711
18712    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18713            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18714        int size = pkgList.length;
18715        if (size > 0) {
18716            // Send broadcasts here
18717            Bundle extras = new Bundle();
18718            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18719            if (uidArr != null) {
18720                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18721            }
18722            if (replacing) {
18723                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18724            }
18725            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18726                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18727            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18728        }
18729    }
18730
18731   /*
18732     * Look at potentially valid container ids from processCids If package
18733     * information doesn't match the one on record or package scanning fails,
18734     * the cid is added to list of removeCids. We currently don't delete stale
18735     * containers.
18736     */
18737    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18738            boolean externalStorage) {
18739        ArrayList<String> pkgList = new ArrayList<String>();
18740        Set<AsecInstallArgs> keys = processCids.keySet();
18741
18742        for (AsecInstallArgs args : keys) {
18743            String codePath = processCids.get(args);
18744            if (DEBUG_SD_INSTALL)
18745                Log.i(TAG, "Loading container : " + args.cid);
18746            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18747            try {
18748                // Make sure there are no container errors first.
18749                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18750                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18751                            + " when installing from sdcard");
18752                    continue;
18753                }
18754                // Check code path here.
18755                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18756                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18757                            + " does not match one in settings " + codePath);
18758                    continue;
18759                }
18760                // Parse package
18761                int parseFlags = mDefParseFlags;
18762                if (args.isExternalAsec()) {
18763                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18764                }
18765                if (args.isFwdLocked()) {
18766                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18767                }
18768
18769                synchronized (mInstallLock) {
18770                    PackageParser.Package pkg = null;
18771                    try {
18772                        // Sadly we don't know the package name yet to freeze it
18773                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18774                                SCAN_IGNORE_FROZEN, 0, null);
18775                    } catch (PackageManagerException e) {
18776                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18777                    }
18778                    // Scan the package
18779                    if (pkg != null) {
18780                        /*
18781                         * TODO why is the lock being held? doPostInstall is
18782                         * called in other places without the lock. This needs
18783                         * to be straightened out.
18784                         */
18785                        // writer
18786                        synchronized (mPackages) {
18787                            retCode = PackageManager.INSTALL_SUCCEEDED;
18788                            pkgList.add(pkg.packageName);
18789                            // Post process args
18790                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18791                                    pkg.applicationInfo.uid);
18792                        }
18793                    } else {
18794                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18795                    }
18796                }
18797
18798            } finally {
18799                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18800                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18801                }
18802            }
18803        }
18804        // writer
18805        synchronized (mPackages) {
18806            // If the platform SDK has changed since the last time we booted,
18807            // we need to re-grant app permission to catch any new ones that
18808            // appear. This is really a hack, and means that apps can in some
18809            // cases get permissions that the user didn't initially explicitly
18810            // allow... it would be nice to have some better way to handle
18811            // this situation.
18812            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18813                    : mSettings.getInternalVersion();
18814            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18815                    : StorageManager.UUID_PRIVATE_INTERNAL;
18816
18817            int updateFlags = UPDATE_PERMISSIONS_ALL;
18818            if (ver.sdkVersion != mSdkVersion) {
18819                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18820                        + mSdkVersion + "; regranting permissions for external");
18821                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18822            }
18823            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18824
18825            // Yay, everything is now upgraded
18826            ver.forceCurrent();
18827
18828            // can downgrade to reader
18829            // Persist settings
18830            mSettings.writeLPr();
18831        }
18832        // Send a broadcast to let everyone know we are done processing
18833        if (pkgList.size() > 0) {
18834            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18835        }
18836    }
18837
18838   /*
18839     * Utility method to unload a list of specified containers
18840     */
18841    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18842        // Just unmount all valid containers.
18843        for (AsecInstallArgs arg : cidArgs) {
18844            synchronized (mInstallLock) {
18845                arg.doPostDeleteLI(false);
18846           }
18847       }
18848   }
18849
18850    /*
18851     * Unload packages mounted on external media. This involves deleting package
18852     * data from internal structures, sending broadcasts about disabled packages,
18853     * gc'ing to free up references, unmounting all secure containers
18854     * corresponding to packages on external media, and posting a
18855     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18856     * that we always have to post this message if status has been requested no
18857     * matter what.
18858     */
18859    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18860            final boolean reportStatus) {
18861        if (DEBUG_SD_INSTALL)
18862            Log.i(TAG, "unloading media packages");
18863        ArrayList<String> pkgList = new ArrayList<String>();
18864        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18865        final Set<AsecInstallArgs> keys = processCids.keySet();
18866        for (AsecInstallArgs args : keys) {
18867            String pkgName = args.getPackageName();
18868            if (DEBUG_SD_INSTALL)
18869                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18870            // Delete package internally
18871            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18872            synchronized (mInstallLock) {
18873                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18874                final boolean res;
18875                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18876                        "unloadMediaPackages")) {
18877                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18878                            null);
18879                }
18880                if (res) {
18881                    pkgList.add(pkgName);
18882                } else {
18883                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18884                    failedList.add(args);
18885                }
18886            }
18887        }
18888
18889        // reader
18890        synchronized (mPackages) {
18891            // We didn't update the settings after removing each package;
18892            // write them now for all packages.
18893            mSettings.writeLPr();
18894        }
18895
18896        // We have to absolutely send UPDATED_MEDIA_STATUS only
18897        // after confirming that all the receivers processed the ordered
18898        // broadcast when packages get disabled, force a gc to clean things up.
18899        // and unload all the containers.
18900        if (pkgList.size() > 0) {
18901            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18902                    new IIntentReceiver.Stub() {
18903                public void performReceive(Intent intent, int resultCode, String data,
18904                        Bundle extras, boolean ordered, boolean sticky,
18905                        int sendingUser) throws RemoteException {
18906                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18907                            reportStatus ? 1 : 0, 1, keys);
18908                    mHandler.sendMessage(msg);
18909                }
18910            });
18911        } else {
18912            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18913                    keys);
18914            mHandler.sendMessage(msg);
18915        }
18916    }
18917
18918    private void loadPrivatePackages(final VolumeInfo vol) {
18919        mHandler.post(new Runnable() {
18920            @Override
18921            public void run() {
18922                loadPrivatePackagesInner(vol);
18923            }
18924        });
18925    }
18926
18927    private void loadPrivatePackagesInner(VolumeInfo vol) {
18928        final String volumeUuid = vol.fsUuid;
18929        if (TextUtils.isEmpty(volumeUuid)) {
18930            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18931            return;
18932        }
18933
18934        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18935        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18936        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18937
18938        final VersionInfo ver;
18939        final List<PackageSetting> packages;
18940        synchronized (mPackages) {
18941            ver = mSettings.findOrCreateVersion(volumeUuid);
18942            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18943        }
18944
18945        for (PackageSetting ps : packages) {
18946            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18947            synchronized (mInstallLock) {
18948                final PackageParser.Package pkg;
18949                try {
18950                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18951                    loaded.add(pkg.applicationInfo);
18952
18953                } catch (PackageManagerException e) {
18954                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18955                }
18956
18957                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18958                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18959                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18960                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18961                }
18962            }
18963        }
18964
18965        // Reconcile app data for all started/unlocked users
18966        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18967        final UserManager um = mContext.getSystemService(UserManager.class);
18968        for (UserInfo user : um.getUsers()) {
18969            final int flags;
18970            if (um.isUserUnlockingOrUnlocked(user.id)) {
18971                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18972            } else if (um.isUserRunning(user.id)) {
18973                flags = StorageManager.FLAG_STORAGE_DE;
18974            } else {
18975                continue;
18976            }
18977
18978            try {
18979                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18980                synchronized (mInstallLock) {
18981                    reconcileAppsDataLI(volumeUuid, user.id, flags);
18982                }
18983            } catch (IllegalStateException e) {
18984                // Device was probably ejected, and we'll process that event momentarily
18985                Slog.w(TAG, "Failed to prepare storage: " + e);
18986            }
18987        }
18988
18989        synchronized (mPackages) {
18990            int updateFlags = UPDATE_PERMISSIONS_ALL;
18991            if (ver.sdkVersion != mSdkVersion) {
18992                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18993                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18994                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18995            }
18996            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18997
18998            // Yay, everything is now upgraded
18999            ver.forceCurrent();
19000
19001            mSettings.writeLPr();
19002        }
19003
19004        for (PackageFreezer freezer : freezers) {
19005            freezer.close();
19006        }
19007
19008        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19009        sendResourcesChangedBroadcast(true, false, loaded, null);
19010    }
19011
19012    private void unloadPrivatePackages(final VolumeInfo vol) {
19013        mHandler.post(new Runnable() {
19014            @Override
19015            public void run() {
19016                unloadPrivatePackagesInner(vol);
19017            }
19018        });
19019    }
19020
19021    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19022        final String volumeUuid = vol.fsUuid;
19023        if (TextUtils.isEmpty(volumeUuid)) {
19024            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19025            return;
19026        }
19027
19028        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19029        synchronized (mInstallLock) {
19030        synchronized (mPackages) {
19031            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19032            for (PackageSetting ps : packages) {
19033                if (ps.pkg == null) continue;
19034
19035                final ApplicationInfo info = ps.pkg.applicationInfo;
19036                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19037                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19038
19039                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19040                        "unloadPrivatePackagesInner")) {
19041                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19042                            false, null)) {
19043                        unloaded.add(info);
19044                    } else {
19045                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19046                    }
19047                }
19048            }
19049
19050            mSettings.writeLPr();
19051        }
19052        }
19053
19054        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19055        sendResourcesChangedBroadcast(false, false, unloaded, null);
19056    }
19057
19058    /**
19059     * Prepare storage areas for given user on all mounted devices.
19060     */
19061    void prepareUserData(int userId, int userSerial, int flags) {
19062        synchronized (mInstallLock) {
19063            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19064            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19065                final String volumeUuid = vol.getFsUuid();
19066                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19067            }
19068        }
19069    }
19070
19071    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19072            boolean allowRecover) {
19073        // Prepare storage and verify that serial numbers are consistent; if
19074        // there's a mismatch we need to destroy to avoid leaking data
19075        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19076        try {
19077            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19078
19079            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19080                UserManagerService.enforceSerialNumber(
19081                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19082            }
19083            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19084                UserManagerService.enforceSerialNumber(
19085                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19086            }
19087
19088            synchronized (mInstallLock) {
19089                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19090            }
19091        } catch (Exception e) {
19092            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19093                    + " because we failed to prepare: " + e);
19094            destroyUserDataLI(volumeUuid, userId,
19095                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19096
19097            if (allowRecover) {
19098                // Try one last time; if we fail again we're really in trouble
19099                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19100            }
19101        }
19102    }
19103
19104    /**
19105     * Destroy storage areas for given user on all mounted devices.
19106     */
19107    void destroyUserData(int userId, int flags) {
19108        synchronized (mInstallLock) {
19109            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19110            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19111                final String volumeUuid = vol.getFsUuid();
19112                destroyUserDataLI(volumeUuid, userId, flags);
19113            }
19114        }
19115    }
19116
19117    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19118        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19119        try {
19120            // Clean up app data, profile data, and media data
19121            mInstaller.destroyUserData(volumeUuid, userId, flags);
19122
19123            // Clean up system data
19124            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19125                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19126                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19127                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19128                }
19129                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19130                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19131                }
19132            }
19133
19134            // Data with special labels is now gone, so finish the job
19135            storage.destroyUserStorage(volumeUuid, userId, flags);
19136
19137        } catch (Exception e) {
19138            logCriticalInfo(Log.WARN,
19139                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19140        }
19141    }
19142
19143    /**
19144     * Examine all users present on given mounted volume, and destroy data
19145     * belonging to users that are no longer valid, or whose user ID has been
19146     * recycled.
19147     */
19148    private void reconcileUsers(String volumeUuid) {
19149        final List<File> files = new ArrayList<>();
19150        Collections.addAll(files, FileUtils
19151                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19152        Collections.addAll(files, FileUtils
19153                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19154        for (File file : files) {
19155            if (!file.isDirectory()) continue;
19156
19157            final int userId;
19158            final UserInfo info;
19159            try {
19160                userId = Integer.parseInt(file.getName());
19161                info = sUserManager.getUserInfo(userId);
19162            } catch (NumberFormatException e) {
19163                Slog.w(TAG, "Invalid user directory " + file);
19164                continue;
19165            }
19166
19167            boolean destroyUser = false;
19168            if (info == null) {
19169                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19170                        + " because no matching user was found");
19171                destroyUser = true;
19172            } else if (!mOnlyCore) {
19173                try {
19174                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19175                } catch (IOException e) {
19176                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19177                            + " because we failed to enforce serial number: " + e);
19178                    destroyUser = true;
19179                }
19180            }
19181
19182            if (destroyUser) {
19183                synchronized (mInstallLock) {
19184                    destroyUserDataLI(volumeUuid, userId,
19185                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19186                }
19187            }
19188        }
19189    }
19190
19191    private void assertPackageKnown(String volumeUuid, String packageName)
19192            throws PackageManagerException {
19193        synchronized (mPackages) {
19194            final PackageSetting ps = mSettings.mPackages.get(packageName);
19195            if (ps == null) {
19196                throw new PackageManagerException("Package " + packageName + " is unknown");
19197            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19198                throw new PackageManagerException(
19199                        "Package " + packageName + " found on unknown volume " + volumeUuid
19200                                + "; expected volume " + ps.volumeUuid);
19201            }
19202        }
19203    }
19204
19205    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19206            throws PackageManagerException {
19207        synchronized (mPackages) {
19208            final PackageSetting ps = mSettings.mPackages.get(packageName);
19209            if (ps == null) {
19210                throw new PackageManagerException("Package " + packageName + " is unknown");
19211            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19212                throw new PackageManagerException(
19213                        "Package " + packageName + " found on unknown volume " + volumeUuid
19214                                + "; expected volume " + ps.volumeUuid);
19215            } else if (!ps.getInstalled(userId)) {
19216                throw new PackageManagerException(
19217                        "Package " + packageName + " not installed for user " + userId);
19218            }
19219        }
19220    }
19221
19222    /**
19223     * Examine all apps present on given mounted volume, and destroy apps that
19224     * aren't expected, either due to uninstallation or reinstallation on
19225     * another volume.
19226     */
19227    private void reconcileApps(String volumeUuid) {
19228        final File[] files = FileUtils
19229                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19230        for (File file : files) {
19231            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19232                    && !PackageInstallerService.isStageName(file.getName());
19233            if (!isPackage) {
19234                // Ignore entries which are not packages
19235                continue;
19236            }
19237
19238            try {
19239                final PackageLite pkg = PackageParser.parsePackageLite(file,
19240                        PackageParser.PARSE_MUST_BE_APK);
19241                assertPackageKnown(volumeUuid, pkg.packageName);
19242
19243            } catch (PackageParserException | PackageManagerException e) {
19244                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19245                synchronized (mInstallLock) {
19246                    removeCodePathLI(file);
19247                }
19248            }
19249        }
19250    }
19251
19252    /**
19253     * Reconcile all app data for the given user.
19254     * <p>
19255     * Verifies that directories exist and that ownership and labeling is
19256     * correct for all installed apps on all mounted volumes.
19257     */
19258    void reconcileAppsData(int userId, int flags) {
19259        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19260        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19261            final String volumeUuid = vol.getFsUuid();
19262            synchronized (mInstallLock) {
19263                reconcileAppsDataLI(volumeUuid, userId, flags);
19264            }
19265        }
19266    }
19267
19268    /**
19269     * Reconcile all app data on given mounted volume.
19270     * <p>
19271     * Destroys app data that isn't expected, either due to uninstallation or
19272     * reinstallation on another volume.
19273     * <p>
19274     * Verifies that directories exist and that ownership and labeling is
19275     * correct for all installed apps.
19276     */
19277    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19278        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19279                + Integer.toHexString(flags));
19280
19281        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19282        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19283
19284        boolean restoreconNeeded = false;
19285
19286        // First look for stale data that doesn't belong, and check if things
19287        // have changed since we did our last restorecon
19288        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19289            if (StorageManager.isFileEncryptedNativeOrEmulated()
19290                    && !StorageManager.isUserKeyUnlocked(userId)) {
19291                throw new RuntimeException(
19292                        "Yikes, someone asked us to reconcile CE storage while " + userId
19293                                + " was still locked; this would have caused massive data loss!");
19294            }
19295
19296            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19297
19298            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19299            for (File file : files) {
19300                final String packageName = file.getName();
19301                try {
19302                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19303                } catch (PackageManagerException e) {
19304                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19305                    try {
19306                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19307                                StorageManager.FLAG_STORAGE_CE, 0);
19308                    } catch (InstallerException e2) {
19309                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19310                    }
19311                }
19312            }
19313        }
19314        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19315            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19316
19317            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19318            for (File file : files) {
19319                final String packageName = file.getName();
19320                try {
19321                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19322                } catch (PackageManagerException e) {
19323                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19324                    try {
19325                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19326                                StorageManager.FLAG_STORAGE_DE, 0);
19327                    } catch (InstallerException e2) {
19328                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19329                    }
19330                }
19331            }
19332        }
19333
19334        // Ensure that data directories are ready to roll for all packages
19335        // installed for this volume and user
19336        final List<PackageSetting> packages;
19337        synchronized (mPackages) {
19338            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19339        }
19340        int preparedCount = 0;
19341        for (PackageSetting ps : packages) {
19342            final String packageName = ps.name;
19343            if (ps.pkg == null) {
19344                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19345                // TODO: might be due to legacy ASEC apps; we should circle back
19346                // and reconcile again once they're scanned
19347                continue;
19348            }
19349
19350            if (ps.getInstalled(userId)) {
19351                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19352
19353                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19354                    // We may have just shuffled around app data directories, so
19355                    // prepare them one more time
19356                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19357                }
19358
19359                preparedCount++;
19360            }
19361        }
19362
19363        if (restoreconNeeded) {
19364            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19365                SELinuxMMAC.setRestoreconDone(ceDir);
19366            }
19367            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19368                SELinuxMMAC.setRestoreconDone(deDir);
19369            }
19370        }
19371
19372        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19373                + " packages; restoreconNeeded was " + restoreconNeeded);
19374    }
19375
19376    /**
19377     * Prepare app data for the given app just after it was installed or
19378     * upgraded. This method carefully only touches users that it's installed
19379     * for, and it forces a restorecon to handle any seinfo changes.
19380     * <p>
19381     * Verifies that directories exist and that ownership and labeling is
19382     * correct for all installed apps. If there is an ownership mismatch, it
19383     * will try recovering system apps by wiping data; third-party app data is
19384     * left intact.
19385     * <p>
19386     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19387     */
19388    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19389        final PackageSetting ps;
19390        synchronized (mPackages) {
19391            ps = mSettings.mPackages.get(pkg.packageName);
19392            mSettings.writeKernelMappingLPr(ps);
19393        }
19394
19395        final UserManager um = mContext.getSystemService(UserManager.class);
19396        for (UserInfo user : um.getUsers()) {
19397            final int flags;
19398            if (um.isUserUnlockingOrUnlocked(user.id)) {
19399                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19400            } else if (um.isUserRunning(user.id)) {
19401                flags = StorageManager.FLAG_STORAGE_DE;
19402            } else {
19403                continue;
19404            }
19405
19406            if (ps.getInstalled(user.id)) {
19407                // Whenever an app changes, force a restorecon of its data
19408                // TODO: when user data is locked, mark that we're still dirty
19409                prepareAppDataLIF(pkg, user.id, flags, true);
19410            }
19411        }
19412    }
19413
19414    /**
19415     * Prepare app data for the given app.
19416     * <p>
19417     * Verifies that directories exist and that ownership and labeling is
19418     * correct for all installed apps. If there is an ownership mismatch, this
19419     * will try recovering system apps by wiping data; third-party app data is
19420     * left intact.
19421     */
19422    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19423            boolean restoreconNeeded) {
19424        if (pkg == null) {
19425            Slog.wtf(TAG, "Package was null!", new Throwable());
19426            return;
19427        }
19428        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19429        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19430        for (int i = 0; i < childCount; i++) {
19431            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19432        }
19433    }
19434
19435    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19436            boolean restoreconNeeded) {
19437        if (DEBUG_APP_DATA) {
19438            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19439                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19440        }
19441
19442        final String volumeUuid = pkg.volumeUuid;
19443        final String packageName = pkg.packageName;
19444        final ApplicationInfo app = pkg.applicationInfo;
19445        final int appId = UserHandle.getAppId(app.uid);
19446
19447        Preconditions.checkNotNull(app.seinfo);
19448
19449        try {
19450            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19451                    appId, app.seinfo, app.targetSdkVersion);
19452        } catch (InstallerException e) {
19453            if (app.isSystemApp()) {
19454                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19455                        + ", but trying to recover: " + e);
19456                destroyAppDataLeafLIF(pkg, userId, flags);
19457                try {
19458                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19459                            appId, app.seinfo, app.targetSdkVersion);
19460                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19461                } catch (InstallerException e2) {
19462                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19463                }
19464            } else {
19465                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19466            }
19467        }
19468
19469        if (restoreconNeeded) {
19470            try {
19471                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19472                        app.seinfo);
19473            } catch (InstallerException e) {
19474                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19475            }
19476        }
19477
19478        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19479            try {
19480                // CE storage is unlocked right now, so read out the inode and
19481                // remember for use later when it's locked
19482                // TODO: mark this structure as dirty so we persist it!
19483                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19484                        StorageManager.FLAG_STORAGE_CE);
19485                synchronized (mPackages) {
19486                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19487                    if (ps != null) {
19488                        ps.setCeDataInode(ceDataInode, userId);
19489                    }
19490                }
19491            } catch (InstallerException e) {
19492                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19493            }
19494        }
19495
19496        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19497    }
19498
19499    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19500        if (pkg == null) {
19501            Slog.wtf(TAG, "Package was null!", new Throwable());
19502            return;
19503        }
19504        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19506        for (int i = 0; i < childCount; i++) {
19507            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19508        }
19509    }
19510
19511    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19512        final String volumeUuid = pkg.volumeUuid;
19513        final String packageName = pkg.packageName;
19514        final ApplicationInfo app = pkg.applicationInfo;
19515
19516        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19517            // Create a native library symlink only if we have native libraries
19518            // and if the native libraries are 32 bit libraries. We do not provide
19519            // this symlink for 64 bit libraries.
19520            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19521                final String nativeLibPath = app.nativeLibraryDir;
19522                try {
19523                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19524                            nativeLibPath, userId);
19525                } catch (InstallerException e) {
19526                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19527                }
19528            }
19529        }
19530    }
19531
19532    /**
19533     * For system apps on non-FBE devices, this method migrates any existing
19534     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19535     * requested by the app.
19536     */
19537    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19538        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19539                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19540            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19541                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19542            try {
19543                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19544                        storageTarget);
19545            } catch (InstallerException e) {
19546                logCriticalInfo(Log.WARN,
19547                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19548            }
19549            return true;
19550        } else {
19551            return false;
19552        }
19553    }
19554
19555    public PackageFreezer freezePackage(String packageName, String killReason) {
19556        return new PackageFreezer(packageName, killReason);
19557    }
19558
19559    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19560            String killReason) {
19561        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19562            return new PackageFreezer();
19563        } else {
19564            return freezePackage(packageName, killReason);
19565        }
19566    }
19567
19568    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19569            String killReason) {
19570        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19571            return new PackageFreezer();
19572        } else {
19573            return freezePackage(packageName, killReason);
19574        }
19575    }
19576
19577    /**
19578     * Class that freezes and kills the given package upon creation, and
19579     * unfreezes it upon closing. This is typically used when doing surgery on
19580     * app code/data to prevent the app from running while you're working.
19581     */
19582    private class PackageFreezer implements AutoCloseable {
19583        private final String mPackageName;
19584        private final PackageFreezer[] mChildren;
19585
19586        private final boolean mWeFroze;
19587
19588        private final AtomicBoolean mClosed = new AtomicBoolean();
19589        private final CloseGuard mCloseGuard = CloseGuard.get();
19590
19591        /**
19592         * Create and return a stub freezer that doesn't actually do anything,
19593         * typically used when someone requested
19594         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19595         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19596         */
19597        public PackageFreezer() {
19598            mPackageName = null;
19599            mChildren = null;
19600            mWeFroze = false;
19601            mCloseGuard.open("close");
19602        }
19603
19604        public PackageFreezer(String packageName, String killReason) {
19605            synchronized (mPackages) {
19606                mPackageName = packageName;
19607                mWeFroze = mFrozenPackages.add(mPackageName);
19608
19609                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19610                if (ps != null) {
19611                    killApplication(ps.name, ps.appId, killReason);
19612                }
19613
19614                final PackageParser.Package p = mPackages.get(packageName);
19615                if (p != null && p.childPackages != null) {
19616                    final int N = p.childPackages.size();
19617                    mChildren = new PackageFreezer[N];
19618                    for (int i = 0; i < N; i++) {
19619                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19620                                killReason);
19621                    }
19622                } else {
19623                    mChildren = null;
19624                }
19625            }
19626            mCloseGuard.open("close");
19627        }
19628
19629        @Override
19630        protected void finalize() throws Throwable {
19631            try {
19632                mCloseGuard.warnIfOpen();
19633                close();
19634            } finally {
19635                super.finalize();
19636            }
19637        }
19638
19639        @Override
19640        public void close() {
19641            mCloseGuard.close();
19642            if (mClosed.compareAndSet(false, true)) {
19643                synchronized (mPackages) {
19644                    if (mWeFroze) {
19645                        mFrozenPackages.remove(mPackageName);
19646                    }
19647
19648                    if (mChildren != null) {
19649                        for (PackageFreezer freezer : mChildren) {
19650                            freezer.close();
19651                        }
19652                    }
19653                }
19654            }
19655        }
19656    }
19657
19658    /**
19659     * Verify that given package is currently frozen.
19660     */
19661    private void checkPackageFrozen(String packageName) {
19662        synchronized (mPackages) {
19663            if (!mFrozenPackages.contains(packageName)) {
19664                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19665            }
19666        }
19667    }
19668
19669    @Override
19670    public int movePackage(final String packageName, final String volumeUuid) {
19671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19672
19673        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19674        final int moveId = mNextMoveId.getAndIncrement();
19675        mHandler.post(new Runnable() {
19676            @Override
19677            public void run() {
19678                try {
19679                    movePackageInternal(packageName, volumeUuid, moveId, user);
19680                } catch (PackageManagerException e) {
19681                    Slog.w(TAG, "Failed to move " + packageName, e);
19682                    mMoveCallbacks.notifyStatusChanged(moveId,
19683                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19684                }
19685            }
19686        });
19687        return moveId;
19688    }
19689
19690    private void movePackageInternal(final String packageName, final String volumeUuid,
19691            final int moveId, UserHandle user) throws PackageManagerException {
19692        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19693        final PackageManager pm = mContext.getPackageManager();
19694
19695        final boolean currentAsec;
19696        final String currentVolumeUuid;
19697        final File codeFile;
19698        final String installerPackageName;
19699        final String packageAbiOverride;
19700        final int appId;
19701        final String seinfo;
19702        final String label;
19703        final int targetSdkVersion;
19704        final PackageFreezer freezer;
19705        final int[] installedUserIds;
19706
19707        // reader
19708        synchronized (mPackages) {
19709            final PackageParser.Package pkg = mPackages.get(packageName);
19710            final PackageSetting ps = mSettings.mPackages.get(packageName);
19711            if (pkg == null || ps == null) {
19712                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19713            }
19714
19715            if (pkg.applicationInfo.isSystemApp()) {
19716                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19717                        "Cannot move system application");
19718            }
19719
19720            if (pkg.applicationInfo.isExternalAsec()) {
19721                currentAsec = true;
19722                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19723            } else if (pkg.applicationInfo.isForwardLocked()) {
19724                currentAsec = true;
19725                currentVolumeUuid = "forward_locked";
19726            } else {
19727                currentAsec = false;
19728                currentVolumeUuid = ps.volumeUuid;
19729
19730                final File probe = new File(pkg.codePath);
19731                final File probeOat = new File(probe, "oat");
19732                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19733                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19734                            "Move only supported for modern cluster style installs");
19735                }
19736            }
19737
19738            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19739                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19740                        "Package already moved to " + volumeUuid);
19741            }
19742            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19743                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19744                        "Device admin cannot be moved");
19745            }
19746
19747            if (mFrozenPackages.contains(packageName)) {
19748                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19749                        "Failed to move already frozen package");
19750            }
19751
19752            codeFile = new File(pkg.codePath);
19753            installerPackageName = ps.installerPackageName;
19754            packageAbiOverride = ps.cpuAbiOverrideString;
19755            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19756            seinfo = pkg.applicationInfo.seinfo;
19757            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19758            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19759            freezer = new PackageFreezer(packageName, "movePackageInternal");
19760            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
19761        }
19762
19763        final Bundle extras = new Bundle();
19764        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19765        extras.putString(Intent.EXTRA_TITLE, label);
19766        mMoveCallbacks.notifyCreated(moveId, extras);
19767
19768        int installFlags;
19769        final boolean moveCompleteApp;
19770        final File measurePath;
19771
19772        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19773            installFlags = INSTALL_INTERNAL;
19774            moveCompleteApp = !currentAsec;
19775            measurePath = Environment.getDataAppDirectory(volumeUuid);
19776        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19777            installFlags = INSTALL_EXTERNAL;
19778            moveCompleteApp = false;
19779            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19780        } else {
19781            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19782            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19783                    || !volume.isMountedWritable()) {
19784                freezer.close();
19785                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19786                        "Move location not mounted private volume");
19787            }
19788
19789            Preconditions.checkState(!currentAsec);
19790
19791            installFlags = INSTALL_INTERNAL;
19792            moveCompleteApp = true;
19793            measurePath = Environment.getDataAppDirectory(volumeUuid);
19794        }
19795
19796        final PackageStats stats = new PackageStats(null, -1);
19797        synchronized (mInstaller) {
19798            for (int userId : installedUserIds) {
19799                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
19800                    freezer.close();
19801                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19802                            "Failed to measure package size");
19803                }
19804            }
19805        }
19806
19807        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19808                + stats.dataSize);
19809
19810        final long startFreeBytes = measurePath.getFreeSpace();
19811        final long sizeBytes;
19812        if (moveCompleteApp) {
19813            sizeBytes = stats.codeSize + stats.dataSize;
19814        } else {
19815            sizeBytes = stats.codeSize;
19816        }
19817
19818        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19819            freezer.close();
19820            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19821                    "Not enough free space to move");
19822        }
19823
19824        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19825
19826        final CountDownLatch installedLatch = new CountDownLatch(1);
19827        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19828            @Override
19829            public void onUserActionRequired(Intent intent) throws RemoteException {
19830                throw new IllegalStateException();
19831            }
19832
19833            @Override
19834            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19835                    Bundle extras) throws RemoteException {
19836                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19837                        + PackageManager.installStatusToString(returnCode, msg));
19838
19839                installedLatch.countDown();
19840                freezer.close();
19841
19842                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19843                switch (status) {
19844                    case PackageInstaller.STATUS_SUCCESS:
19845                        mMoveCallbacks.notifyStatusChanged(moveId,
19846                                PackageManager.MOVE_SUCCEEDED);
19847                        break;
19848                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19849                        mMoveCallbacks.notifyStatusChanged(moveId,
19850                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19851                        break;
19852                    default:
19853                        mMoveCallbacks.notifyStatusChanged(moveId,
19854                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19855                        break;
19856                }
19857            }
19858        };
19859
19860        final MoveInfo move;
19861        if (moveCompleteApp) {
19862            // Kick off a thread to report progress estimates
19863            new Thread() {
19864                @Override
19865                public void run() {
19866                    while (true) {
19867                        try {
19868                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19869                                break;
19870                            }
19871                        } catch (InterruptedException ignored) {
19872                        }
19873
19874                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19875                        final int progress = 10 + (int) MathUtils.constrain(
19876                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19877                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19878                    }
19879                }
19880            }.start();
19881
19882            final String dataAppName = codeFile.getName();
19883            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19884                    dataAppName, appId, seinfo, targetSdkVersion);
19885        } else {
19886            move = null;
19887        }
19888
19889        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19890
19891        final Message msg = mHandler.obtainMessage(INIT_COPY);
19892        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19893        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19894                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19895                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19896        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19897        msg.obj = params;
19898
19899        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19900                System.identityHashCode(msg.obj));
19901        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19902                System.identityHashCode(msg.obj));
19903
19904        mHandler.sendMessage(msg);
19905    }
19906
19907    @Override
19908    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19909        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19910
19911        final int realMoveId = mNextMoveId.getAndIncrement();
19912        final Bundle extras = new Bundle();
19913        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19914        mMoveCallbacks.notifyCreated(realMoveId, extras);
19915
19916        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19917            @Override
19918            public void onCreated(int moveId, Bundle extras) {
19919                // Ignored
19920            }
19921
19922            @Override
19923            public void onStatusChanged(int moveId, int status, long estMillis) {
19924                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19925            }
19926        };
19927
19928        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19929        storage.setPrimaryStorageUuid(volumeUuid, callback);
19930        return realMoveId;
19931    }
19932
19933    @Override
19934    public int getMoveStatus(int moveId) {
19935        mContext.enforceCallingOrSelfPermission(
19936                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19937        return mMoveCallbacks.mLastStatus.get(moveId);
19938    }
19939
19940    @Override
19941    public void registerMoveCallback(IPackageMoveObserver callback) {
19942        mContext.enforceCallingOrSelfPermission(
19943                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19944        mMoveCallbacks.register(callback);
19945    }
19946
19947    @Override
19948    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19949        mContext.enforceCallingOrSelfPermission(
19950                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19951        mMoveCallbacks.unregister(callback);
19952    }
19953
19954    @Override
19955    public boolean setInstallLocation(int loc) {
19956        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19957                null);
19958        if (getInstallLocation() == loc) {
19959            return true;
19960        }
19961        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19962                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19963            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19964                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19965            return true;
19966        }
19967        return false;
19968   }
19969
19970    @Override
19971    public int getInstallLocation() {
19972        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19973                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19974                PackageHelper.APP_INSTALL_AUTO);
19975    }
19976
19977    /** Called by UserManagerService */
19978    void cleanUpUser(UserManagerService userManager, int userHandle) {
19979        synchronized (mPackages) {
19980            mDirtyUsers.remove(userHandle);
19981            mUserNeedsBadging.delete(userHandle);
19982            mSettings.removeUserLPw(userHandle);
19983            mPendingBroadcasts.remove(userHandle);
19984            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19985            removeUnusedPackagesLPw(userManager, userHandle);
19986        }
19987    }
19988
19989    /**
19990     * We're removing userHandle and would like to remove any downloaded packages
19991     * that are no longer in use by any other user.
19992     * @param userHandle the user being removed
19993     */
19994    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19995        final boolean DEBUG_CLEAN_APKS = false;
19996        int [] users = userManager.getUserIds();
19997        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19998        while (psit.hasNext()) {
19999            PackageSetting ps = psit.next();
20000            if (ps.pkg == null) {
20001                continue;
20002            }
20003            final String packageName = ps.pkg.packageName;
20004            // Skip over if system app
20005            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20006                continue;
20007            }
20008            if (DEBUG_CLEAN_APKS) {
20009                Slog.i(TAG, "Checking package " + packageName);
20010            }
20011            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20012            if (keep) {
20013                if (DEBUG_CLEAN_APKS) {
20014                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20015                }
20016            } else {
20017                for (int i = 0; i < users.length; i++) {
20018                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20019                        keep = true;
20020                        if (DEBUG_CLEAN_APKS) {
20021                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20022                                    + users[i]);
20023                        }
20024                        break;
20025                    }
20026                }
20027            }
20028            if (!keep) {
20029                if (DEBUG_CLEAN_APKS) {
20030                    Slog.i(TAG, "  Removing package " + packageName);
20031                }
20032                mHandler.post(new Runnable() {
20033                    public void run() {
20034                        deletePackageX(packageName, userHandle, 0);
20035                    } //end run
20036                });
20037            }
20038        }
20039    }
20040
20041    /** Called by UserManagerService */
20042    void createNewUser(int userHandle) {
20043        synchronized (mInstallLock) {
20044            mSettings.createNewUserLI(this, mInstaller, userHandle);
20045        }
20046        synchronized (mPackages) {
20047            applyFactoryDefaultBrowserLPw(userHandle);
20048            primeDomainVerificationsLPw(userHandle);
20049        }
20050    }
20051
20052    void onBeforeUserStartUninitialized(final int userId) {
20053        synchronized (mPackages) {
20054            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20055                return;
20056            }
20057        }
20058        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20059        // If permission review for legacy apps is required, we represent
20060        // dagerous permissions for such apps as always granted runtime
20061        // permissions to keep per user flag state whether review is needed.
20062        // Hence, if a new user is added we have to propagate dangerous
20063        // permission grants for these legacy apps.
20064        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20065            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20066                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20067        }
20068    }
20069
20070    @Override
20071    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20072        mContext.enforceCallingOrSelfPermission(
20073                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20074                "Only package verification agents can read the verifier device identity");
20075
20076        synchronized (mPackages) {
20077            return mSettings.getVerifierDeviceIdentityLPw();
20078        }
20079    }
20080
20081    @Override
20082    public void setPermissionEnforced(String permission, boolean enforced) {
20083        // TODO: Now that we no longer change GID for storage, this should to away.
20084        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20085                "setPermissionEnforced");
20086        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20087            synchronized (mPackages) {
20088                if (mSettings.mReadExternalStorageEnforced == null
20089                        || mSettings.mReadExternalStorageEnforced != enforced) {
20090                    mSettings.mReadExternalStorageEnforced = enforced;
20091                    mSettings.writeLPr();
20092                }
20093            }
20094            // kill any non-foreground processes so we restart them and
20095            // grant/revoke the GID.
20096            final IActivityManager am = ActivityManagerNative.getDefault();
20097            if (am != null) {
20098                final long token = Binder.clearCallingIdentity();
20099                try {
20100                    am.killProcessesBelowForeground("setPermissionEnforcement");
20101                } catch (RemoteException e) {
20102                } finally {
20103                    Binder.restoreCallingIdentity(token);
20104                }
20105            }
20106        } else {
20107            throw new IllegalArgumentException("No selective enforcement for " + permission);
20108        }
20109    }
20110
20111    @Override
20112    @Deprecated
20113    public boolean isPermissionEnforced(String permission) {
20114        return true;
20115    }
20116
20117    @Override
20118    public boolean isStorageLow() {
20119        final long token = Binder.clearCallingIdentity();
20120        try {
20121            final DeviceStorageMonitorInternal
20122                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20123            if (dsm != null) {
20124                return dsm.isMemoryLow();
20125            } else {
20126                return false;
20127            }
20128        } finally {
20129            Binder.restoreCallingIdentity(token);
20130        }
20131    }
20132
20133    @Override
20134    public IPackageInstaller getPackageInstaller() {
20135        return mInstallerService;
20136    }
20137
20138    private boolean userNeedsBadging(int userId) {
20139        int index = mUserNeedsBadging.indexOfKey(userId);
20140        if (index < 0) {
20141            final UserInfo userInfo;
20142            final long token = Binder.clearCallingIdentity();
20143            try {
20144                userInfo = sUserManager.getUserInfo(userId);
20145            } finally {
20146                Binder.restoreCallingIdentity(token);
20147            }
20148            final boolean b;
20149            if (userInfo != null && userInfo.isManagedProfile()) {
20150                b = true;
20151            } else {
20152                b = false;
20153            }
20154            mUserNeedsBadging.put(userId, b);
20155            return b;
20156        }
20157        return mUserNeedsBadging.valueAt(index);
20158    }
20159
20160    @Override
20161    public KeySet getKeySetByAlias(String packageName, String alias) {
20162        if (packageName == null || alias == null) {
20163            return null;
20164        }
20165        synchronized(mPackages) {
20166            final PackageParser.Package pkg = mPackages.get(packageName);
20167            if (pkg == null) {
20168                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20169                throw new IllegalArgumentException("Unknown package: " + packageName);
20170            }
20171            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20172            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20173        }
20174    }
20175
20176    @Override
20177    public KeySet getSigningKeySet(String packageName) {
20178        if (packageName == null) {
20179            return null;
20180        }
20181        synchronized(mPackages) {
20182            final PackageParser.Package pkg = mPackages.get(packageName);
20183            if (pkg == null) {
20184                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20185                throw new IllegalArgumentException("Unknown package: " + packageName);
20186            }
20187            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20188                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20189                throw new SecurityException("May not access signing KeySet of other apps.");
20190            }
20191            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20192            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20193        }
20194    }
20195
20196    @Override
20197    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20198        if (packageName == null || ks == null) {
20199            return false;
20200        }
20201        synchronized(mPackages) {
20202            final PackageParser.Package pkg = mPackages.get(packageName);
20203            if (pkg == null) {
20204                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20205                throw new IllegalArgumentException("Unknown package: " + packageName);
20206            }
20207            IBinder ksh = ks.getToken();
20208            if (ksh instanceof KeySetHandle) {
20209                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20210                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20211            }
20212            return false;
20213        }
20214    }
20215
20216    @Override
20217    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20218        if (packageName == null || ks == null) {
20219            return false;
20220        }
20221        synchronized(mPackages) {
20222            final PackageParser.Package pkg = mPackages.get(packageName);
20223            if (pkg == null) {
20224                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20225                throw new IllegalArgumentException("Unknown package: " + packageName);
20226            }
20227            IBinder ksh = ks.getToken();
20228            if (ksh instanceof KeySetHandle) {
20229                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20230                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20231            }
20232            return false;
20233        }
20234    }
20235
20236    private void deletePackageIfUnusedLPr(final String packageName) {
20237        PackageSetting ps = mSettings.mPackages.get(packageName);
20238        if (ps == null) {
20239            return;
20240        }
20241        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20242            // TODO Implement atomic delete if package is unused
20243            // It is currently possible that the package will be deleted even if it is installed
20244            // after this method returns.
20245            mHandler.post(new Runnable() {
20246                public void run() {
20247                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20248                }
20249            });
20250        }
20251    }
20252
20253    /**
20254     * Check and throw if the given before/after packages would be considered a
20255     * downgrade.
20256     */
20257    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20258            throws PackageManagerException {
20259        if (after.versionCode < before.mVersionCode) {
20260            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20261                    "Update version code " + after.versionCode + " is older than current "
20262                    + before.mVersionCode);
20263        } else if (after.versionCode == before.mVersionCode) {
20264            if (after.baseRevisionCode < before.baseRevisionCode) {
20265                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20266                        "Update base revision code " + after.baseRevisionCode
20267                        + " is older than current " + before.baseRevisionCode);
20268            }
20269
20270            if (!ArrayUtils.isEmpty(after.splitNames)) {
20271                for (int i = 0; i < after.splitNames.length; i++) {
20272                    final String splitName = after.splitNames[i];
20273                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20274                    if (j != -1) {
20275                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20276                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20277                                    "Update split " + splitName + " revision code "
20278                                    + after.splitRevisionCodes[i] + " is older than current "
20279                                    + before.splitRevisionCodes[j]);
20280                        }
20281                    }
20282                }
20283            }
20284        }
20285    }
20286
20287    private static class MoveCallbacks extends Handler {
20288        private static final int MSG_CREATED = 1;
20289        private static final int MSG_STATUS_CHANGED = 2;
20290
20291        private final RemoteCallbackList<IPackageMoveObserver>
20292                mCallbacks = new RemoteCallbackList<>();
20293
20294        private final SparseIntArray mLastStatus = new SparseIntArray();
20295
20296        public MoveCallbacks(Looper looper) {
20297            super(looper);
20298        }
20299
20300        public void register(IPackageMoveObserver callback) {
20301            mCallbacks.register(callback);
20302        }
20303
20304        public void unregister(IPackageMoveObserver callback) {
20305            mCallbacks.unregister(callback);
20306        }
20307
20308        @Override
20309        public void handleMessage(Message msg) {
20310            final SomeArgs args = (SomeArgs) msg.obj;
20311            final int n = mCallbacks.beginBroadcast();
20312            for (int i = 0; i < n; i++) {
20313                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20314                try {
20315                    invokeCallback(callback, msg.what, args);
20316                } catch (RemoteException ignored) {
20317                }
20318            }
20319            mCallbacks.finishBroadcast();
20320            args.recycle();
20321        }
20322
20323        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20324                throws RemoteException {
20325            switch (what) {
20326                case MSG_CREATED: {
20327                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20328                    break;
20329                }
20330                case MSG_STATUS_CHANGED: {
20331                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20332                    break;
20333                }
20334            }
20335        }
20336
20337        private void notifyCreated(int moveId, Bundle extras) {
20338            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20339
20340            final SomeArgs args = SomeArgs.obtain();
20341            args.argi1 = moveId;
20342            args.arg2 = extras;
20343            obtainMessage(MSG_CREATED, args).sendToTarget();
20344        }
20345
20346        private void notifyStatusChanged(int moveId, int status) {
20347            notifyStatusChanged(moveId, status, -1);
20348        }
20349
20350        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20351            Slog.v(TAG, "Move " + moveId + " status " + status);
20352
20353            final SomeArgs args = SomeArgs.obtain();
20354            args.argi1 = moveId;
20355            args.argi2 = status;
20356            args.arg3 = estMillis;
20357            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20358
20359            synchronized (mLastStatus) {
20360                mLastStatus.put(moveId, status);
20361            }
20362        }
20363    }
20364
20365    private final static class OnPermissionChangeListeners extends Handler {
20366        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20367
20368        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20369                new RemoteCallbackList<>();
20370
20371        public OnPermissionChangeListeners(Looper looper) {
20372            super(looper);
20373        }
20374
20375        @Override
20376        public void handleMessage(Message msg) {
20377            switch (msg.what) {
20378                case MSG_ON_PERMISSIONS_CHANGED: {
20379                    final int uid = msg.arg1;
20380                    handleOnPermissionsChanged(uid);
20381                } break;
20382            }
20383        }
20384
20385        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20386            mPermissionListeners.register(listener);
20387
20388        }
20389
20390        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20391            mPermissionListeners.unregister(listener);
20392        }
20393
20394        public void onPermissionsChanged(int uid) {
20395            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20396                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20397            }
20398        }
20399
20400        private void handleOnPermissionsChanged(int uid) {
20401            final int count = mPermissionListeners.beginBroadcast();
20402            try {
20403                for (int i = 0; i < count; i++) {
20404                    IOnPermissionsChangeListener callback = mPermissionListeners
20405                            .getBroadcastItem(i);
20406                    try {
20407                        callback.onPermissionsChanged(uid);
20408                    } catch (RemoteException e) {
20409                        Log.e(TAG, "Permission listener is dead", e);
20410                    }
20411                }
20412            } finally {
20413                mPermissionListeners.finishBroadcast();
20414            }
20415        }
20416    }
20417
20418    private class PackageManagerInternalImpl extends PackageManagerInternal {
20419        @Override
20420        public void setLocationPackagesProvider(PackagesProvider provider) {
20421            synchronized (mPackages) {
20422                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20423            }
20424        }
20425
20426        @Override
20427        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20428            synchronized (mPackages) {
20429                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20430            }
20431        }
20432
20433        @Override
20434        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20435            synchronized (mPackages) {
20436                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20437            }
20438        }
20439
20440        @Override
20441        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20442            synchronized (mPackages) {
20443                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20444            }
20445        }
20446
20447        @Override
20448        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20449            synchronized (mPackages) {
20450                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20451            }
20452        }
20453
20454        @Override
20455        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20456            synchronized (mPackages) {
20457                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20458            }
20459        }
20460
20461        @Override
20462        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20463            synchronized (mPackages) {
20464                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20465                        packageName, userId);
20466            }
20467        }
20468
20469        @Override
20470        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20471            synchronized (mPackages) {
20472                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20473                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20474                        packageName, userId);
20475            }
20476        }
20477
20478        @Override
20479        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20480            synchronized (mPackages) {
20481                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20482                        packageName, userId);
20483            }
20484        }
20485
20486        @Override
20487        public void setKeepUninstalledPackages(final List<String> packageList) {
20488            Preconditions.checkNotNull(packageList);
20489            List<String> removedFromList = null;
20490            synchronized (mPackages) {
20491                if (mKeepUninstalledPackages != null) {
20492                    final int packagesCount = mKeepUninstalledPackages.size();
20493                    for (int i = 0; i < packagesCount; i++) {
20494                        String oldPackage = mKeepUninstalledPackages.get(i);
20495                        if (packageList != null && packageList.contains(oldPackage)) {
20496                            continue;
20497                        }
20498                        if (removedFromList == null) {
20499                            removedFromList = new ArrayList<>();
20500                        }
20501                        removedFromList.add(oldPackage);
20502                    }
20503                }
20504                mKeepUninstalledPackages = new ArrayList<>(packageList);
20505                if (removedFromList != null) {
20506                    final int removedCount = removedFromList.size();
20507                    for (int i = 0; i < removedCount; i++) {
20508                        deletePackageIfUnusedLPr(removedFromList.get(i));
20509                    }
20510                }
20511            }
20512        }
20513
20514        @Override
20515        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20516            synchronized (mPackages) {
20517                // If we do not support permission review, done.
20518                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20519                    return false;
20520                }
20521
20522                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20523                if (packageSetting == null) {
20524                    return false;
20525                }
20526
20527                // Permission review applies only to apps not supporting the new permission model.
20528                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20529                    return false;
20530                }
20531
20532                // Legacy apps have the permission and get user consent on launch.
20533                PermissionsState permissionsState = packageSetting.getPermissionsState();
20534                return permissionsState.isPermissionReviewRequired(userId);
20535            }
20536        }
20537
20538        @Override
20539        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20540            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20541        }
20542
20543        @Override
20544        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20545                int userId) {
20546            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20547        }
20548    }
20549
20550    @Override
20551    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20552        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20553        synchronized (mPackages) {
20554            final long identity = Binder.clearCallingIdentity();
20555            try {
20556                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20557                        packageNames, userId);
20558            } finally {
20559                Binder.restoreCallingIdentity(identity);
20560            }
20561        }
20562    }
20563
20564    private static void enforceSystemOrPhoneCaller(String tag) {
20565        int callingUid = Binder.getCallingUid();
20566        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20567            throw new SecurityException(
20568                    "Cannot call " + tag + " from UID " + callingUid);
20569        }
20570    }
20571
20572    boolean isHistoricalPackageUsageAvailable() {
20573        return mPackageUsage.isHistoricalPackageUsageAvailable();
20574    }
20575
20576    /**
20577     * Return a <b>copy</b> of the collection of packages known to the package manager.
20578     * @return A copy of the values of mPackages.
20579     */
20580    Collection<PackageParser.Package> getPackages() {
20581        synchronized (mPackages) {
20582            return new ArrayList<>(mPackages.values());
20583        }
20584    }
20585
20586    /**
20587     * Logs process start information (including base APK hash) to the security log.
20588     * @hide
20589     */
20590    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20591            String apkFile, int pid) {
20592        if (!SecurityLog.isLoggingEnabled()) {
20593            return;
20594        }
20595        Bundle data = new Bundle();
20596        data.putLong("startTimestamp", System.currentTimeMillis());
20597        data.putString("processName", processName);
20598        data.putInt("uid", uid);
20599        data.putString("seinfo", seinfo);
20600        data.putString("apkFile", apkFile);
20601        data.putInt("pid", pid);
20602        Message msg = mProcessLoggingHandler.obtainMessage(
20603                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20604        msg.setData(data);
20605        mProcessLoggingHandler.sendMessage(msg);
20606    }
20607}
20608