PackageManagerService.java revision ce18c8167766f92856f94a8e88e19de4698960e6
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.storage.IMountService;
193import android.os.storage.MountServiceInternal;
194import android.os.storage.StorageEventListener;
195import android.os.storage.StorageManager;
196import android.os.storage.VolumeInfo;
197import android.os.storage.VolumeRecord;
198import android.security.KeyStore;
199import android.security.SystemKeyStore;
200import android.system.ErrnoException;
201import android.system.Os;
202import android.text.TextUtils;
203import android.text.format.DateUtils;
204import android.util.ArrayMap;
205import android.util.ArraySet;
206import android.util.AtomicFile;
207import android.util.DisplayMetrics;
208import android.util.EventLog;
209import android.util.ExceptionUtils;
210import android.util.Log;
211import android.util.LogPrinter;
212import android.util.MathUtils;
213import android.util.PrintStreamPrinter;
214import android.util.Slog;
215import android.util.SparseArray;
216import android.util.SparseBooleanArray;
217import android.util.SparseIntArray;
218import android.util.Xml;
219import android.util.jar.StrictJarFile;
220import android.view.Display;
221
222import com.android.internal.R;
223import com.android.internal.annotations.GuardedBy;
224import com.android.internal.app.IMediaContainerService;
225import com.android.internal.app.ResolverActivity;
226import com.android.internal.content.NativeLibraryHelper;
227import com.android.internal.content.PackageHelper;
228import com.android.internal.os.IParcelFileDescriptorFactory;
229import com.android.internal.os.InstallerConnection.InstallerException;
230import com.android.internal.os.SomeArgs;
231import com.android.internal.os.Zygote;
232import com.android.internal.telephony.CarrierAppUtils;
233import com.android.internal.util.ArrayUtils;
234import com.android.internal.util.FastPrintWriter;
235import com.android.internal.util.FastXmlSerializer;
236import com.android.internal.util.IndentingPrintWriter;
237import com.android.internal.util.Preconditions;
238import com.android.internal.util.XmlUtils;
239import com.android.server.EventLogTags;
240import com.android.server.FgThread;
241import com.android.server.IntentResolver;
242import com.android.server.LocalServices;
243import com.android.server.ServiceThread;
244import com.android.server.SystemConfig;
245import com.android.server.Watchdog;
246import com.android.server.pm.PermissionsState.PermissionState;
247import com.android.server.pm.Settings.DatabaseVersion;
248import com.android.server.pm.Settings.VersionInfo;
249import com.android.server.storage.DeviceStorageMonitorInternal;
250
251import dalvik.system.CloseGuard;
252import dalvik.system.DexFile;
253import dalvik.system.VMRuntime;
254
255import libcore.io.IoUtils;
256import libcore.util.EmptyArray;
257
258import org.xmlpull.v1.XmlPullParser;
259import org.xmlpull.v1.XmlPullParserException;
260import org.xmlpull.v1.XmlSerializer;
261
262import java.io.BufferedInputStream;
263import java.io.BufferedOutputStream;
264import java.io.BufferedReader;
265import java.io.ByteArrayInputStream;
266import java.io.ByteArrayOutputStream;
267import java.io.File;
268import java.io.FileDescriptor;
269import java.io.FileNotFoundException;
270import java.io.FileOutputStream;
271import java.io.FileReader;
272import java.io.FilenameFilter;
273import java.io.IOException;
274import java.io.InputStream;
275import java.io.PrintWriter;
276import java.nio.charset.StandardCharsets;
277import java.security.MessageDigest;
278import java.security.NoSuchAlgorithmException;
279import java.security.PublicKey;
280import java.security.cert.Certificate;
281import java.security.cert.CertificateEncodingException;
282import java.security.cert.CertificateException;
283import java.text.SimpleDateFormat;
284import java.util.ArrayList;
285import java.util.Arrays;
286import java.util.Collection;
287import java.util.Collections;
288import java.util.Comparator;
289import java.util.Date;
290import java.util.HashSet;
291import java.util.Iterator;
292import java.util.List;
293import java.util.Map;
294import java.util.Objects;
295import java.util.Set;
296import java.util.concurrent.CountDownLatch;
297import java.util.concurrent.TimeUnit;
298import java.util.concurrent.atomic.AtomicBoolean;
299import java.util.concurrent.atomic.AtomicInteger;
300import java.util.concurrent.atomic.AtomicLong;
301
302/**
303 * Keep track of all those APKs everywhere.
304 * <p>
305 * Internally there are two important locks:
306 * <ul>
307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
308 * and other related state. It is a fine-grained lock that should only be held
309 * momentarily, as it's one of the most contended locks in the system.
310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
311 * operations typically involve heavy lifting of application data on disk. Since
312 * {@code installd} is single-threaded, and it's operations can often be slow,
313 * this lock should never be acquired while already holding {@link #mPackages}.
314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
315 * holding {@link #mInstallLock}.
316 * </ul>
317 * Many internal methods rely on the caller to hold the appropriate locks, and
318 * this contract is expressed through method name suffixes:
319 * <ul>
320 * <li>fooLI(): the caller must hold {@link #mInstallLock}
321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
322 * being modified must be frozen
323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
325 * </ul>
326 * <p>
327 * Because this class is very central to the platform's security; please run all
328 * CTS and unit tests whenever making modifications:
329 *
330 * <pre>
331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
333 * </pre>
334 */
335public class PackageManagerService extends IPackageManager.Stub {
336    static final String TAG = "PackageManager";
337    static final boolean DEBUG_SETTINGS = false;
338    static final boolean DEBUG_PREFERRED = false;
339    static final boolean DEBUG_UPGRADE = false;
340    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
341    private static final boolean DEBUG_BACKUP = false;
342    private static final boolean DEBUG_INSTALL = false;
343    private static final boolean DEBUG_REMOVE = false;
344    private static final boolean DEBUG_BROADCASTS = false;
345    private static final boolean DEBUG_SHOW_INFO = false;
346    private static final boolean DEBUG_PACKAGE_INFO = false;
347    private static final boolean DEBUG_INTENT_MATCHING = false;
348    private static final boolean DEBUG_PACKAGE_SCANNING = false;
349    private static final boolean DEBUG_VERIFY = false;
350    private static final boolean DEBUG_FILTERS = false;
351
352    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
353    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
354    // user, but by default initialize to this.
355    static final boolean DEBUG_DEXOPT = false;
356
357    private static final boolean DEBUG_ABI_SELECTION = false;
358    private static final boolean DEBUG_EPHEMERAL = false;
359    private static final boolean DEBUG_TRIAGED_MISSING = false;
360    private static final boolean DEBUG_APP_DATA = false;
361
362    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
363
364    private static final boolean DISABLE_EPHEMERAL_APPS = true;
365
366    private static final int RADIO_UID = Process.PHONE_UID;
367    private static final int LOG_UID = Process.LOG_UID;
368    private static final int NFC_UID = Process.NFC_UID;
369    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
370    private static final int SHELL_UID = Process.SHELL_UID;
371
372    // Cap the size of permission trees that 3rd party apps can define
373    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
374
375    // Suffix used during package installation when copying/moving
376    // package apks to install directory.
377    private static final String INSTALL_PACKAGE_SUFFIX = "-";
378
379    static final int SCAN_NO_DEX = 1<<1;
380    static final int SCAN_FORCE_DEX = 1<<2;
381    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
382    static final int SCAN_NEW_INSTALL = 1<<4;
383    static final int SCAN_NO_PATHS = 1<<5;
384    static final int SCAN_UPDATE_TIME = 1<<6;
385    static final int SCAN_DEFER_DEX = 1<<7;
386    static final int SCAN_BOOTING = 1<<8;
387    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
388    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
389    static final int SCAN_REPLACING = 1<<11;
390    static final int SCAN_REQUIRE_KNOWN = 1<<12;
391    static final int SCAN_MOVE = 1<<13;
392    static final int SCAN_INITIAL = 1<<14;
393    static final int SCAN_CHECK_ONLY = 1<<15;
394    static final int SCAN_DONT_KILL_APP = 1<<17;
395    static final int SCAN_IGNORE_FROZEN = 1<<18;
396
397    static final int REMOVE_CHATTY = 1<<16;
398
399    private static final int[] EMPTY_INT_ARRAY = new int[0];
400
401    /**
402     * Timeout (in milliseconds) after which the watchdog should declare that
403     * our handler thread is wedged.  The usual default for such things is one
404     * minute but we sometimes do very lengthy I/O operations on this thread,
405     * such as installing multi-gigabyte applications, so ours needs to be longer.
406     */
407    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
408
409    /**
410     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
411     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
412     * settings entry if available, otherwise we use the hardcoded default.  If it's been
413     * more than this long since the last fstrim, we force one during the boot sequence.
414     *
415     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
416     * one gets run at the next available charging+idle time.  This final mandatory
417     * no-fstrim check kicks in only of the other scheduling criteria is never met.
418     */
419    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
420
421    /**
422     * Whether verification is enabled by default.
423     */
424    private static final boolean DEFAULT_VERIFY_ENABLE = true;
425
426    /**
427     * The default maximum time to wait for the verification agent to return in
428     * milliseconds.
429     */
430    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
431
432    /**
433     * The default response for package verification timeout.
434     *
435     * This can be either PackageManager.VERIFICATION_ALLOW or
436     * PackageManager.VERIFICATION_REJECT.
437     */
438    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
439
440    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
441
442    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
443            DEFAULT_CONTAINER_PACKAGE,
444            "com.android.defcontainer.DefaultContainerService");
445
446    private static final String KILL_APP_REASON_GIDS_CHANGED =
447            "permission grant or revoke changed gids";
448
449    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
450            "permissions revoked";
451
452    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
453
454    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
455
456    /** Permission grant: not grant the permission. */
457    private static final int GRANT_DENIED = 1;
458
459    /** Permission grant: grant the permission as an install permission. */
460    private static final int GRANT_INSTALL = 2;
461
462    /** Permission grant: grant the permission as a runtime one. */
463    private static final int GRANT_RUNTIME = 3;
464
465    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
466    private static final int GRANT_UPGRADE = 4;
467
468    /** Canonical intent used to identify what counts as a "web browser" app */
469    private static final Intent sBrowserIntent;
470    static {
471        sBrowserIntent = new Intent();
472        sBrowserIntent.setAction(Intent.ACTION_VIEW);
473        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
474        sBrowserIntent.setData(Uri.parse("http:"));
475    }
476
477    /**
478     * The set of all protected actions [i.e. those actions for which a high priority
479     * intent filter is disallowed].
480     */
481    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
482    static {
483        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
484        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
485        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
486        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
487    }
488
489    // Compilation reasons.
490    public static final int REASON_FIRST_BOOT = 0;
491    public static final int REASON_BOOT = 1;
492    public static final int REASON_INSTALL = 2;
493    public static final int REASON_BACKGROUND_DEXOPT = 3;
494    public static final int REASON_AB_OTA = 4;
495    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
496    public static final int REASON_SHARED_APK = 6;
497    public static final int REASON_FORCED_DEXOPT = 7;
498
499    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
500
501    // Special String to skip shared libraries check during compilation.
502    private static final String SPECIAL_SHARED_LIBRARY = "&";
503
504    final ServiceThread mHandlerThread;
505
506    final PackageHandler mHandler;
507
508    private final ProcessLoggingHandler mProcessLoggingHandler;
509
510    /**
511     * Messages for {@link #mHandler} that need to wait for system ready before
512     * being dispatched.
513     */
514    private ArrayList<Message> mPostSystemReadyMessages;
515
516    final int mSdkVersion = Build.VERSION.SDK_INT;
517
518    final Context mContext;
519    final boolean mFactoryTest;
520    final boolean mOnlyCore;
521    final DisplayMetrics mMetrics;
522    final int mDefParseFlags;
523    final String[] mSeparateProcesses;
524    final boolean mIsUpgrade;
525    final boolean mIsPreNUpgrade;
526
527    /** The location for ASEC container files on internal storage. */
528    final String mAsecInternalPath;
529
530    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
531    // LOCK HELD.  Can be called with mInstallLock held.
532    @GuardedBy("mInstallLock")
533    final Installer mInstaller;
534
535    /** Directory where installed third-party apps stored */
536    final File mAppInstallDir;
537    final File mEphemeralInstallDir;
538
539    /**
540     * Directory to which applications installed internally have their
541     * 32 bit native libraries copied.
542     */
543    private File mAppLib32InstallDir;
544
545    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
546    // apps.
547    final File mDrmAppPrivateInstallDir;
548
549    // ----------------------------------------------------------------
550
551    // Lock for state used when installing and doing other long running
552    // operations.  Methods that must be called with this lock held have
553    // the suffix "LI".
554    final Object mInstallLock = new Object();
555
556    // ----------------------------------------------------------------
557
558    // Keys are String (package name), values are Package.  This also serves
559    // as the lock for the global state.  Methods that must be called with
560    // this lock held have the prefix "LP".
561    @GuardedBy("mPackages")
562    final ArrayMap<String, PackageParser.Package> mPackages =
563            new ArrayMap<String, PackageParser.Package>();
564
565    final ArrayMap<String, Set<String>> mKnownCodebase =
566            new ArrayMap<String, Set<String>>();
567
568    // Tracks available target package names -> overlay package paths.
569    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
570        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
571
572    /**
573     * Tracks new system packages [received in an OTA] that we expect to
574     * find updated user-installed versions. Keys are package name, values
575     * are package location.
576     */
577    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
578    /**
579     * Tracks high priority intent filters for protected actions. During boot, certain
580     * filter actions are protected and should never be allowed to have a high priority
581     * intent filter for them. However, there is one, and only one exception -- the
582     * setup wizard. It must be able to define a high priority intent filter for these
583     * actions to ensure there are no escapes from the wizard. We need to delay processing
584     * of these during boot as we need to look at all of the system packages in order
585     * to know which component is the setup wizard.
586     */
587    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
588    /**
589     * Whether or not processing protected filters should be deferred.
590     */
591    private boolean mDeferProtectedFilters = true;
592
593    /**
594     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
595     */
596    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
597    /**
598     * Whether or not system app permissions should be promoted from install to runtime.
599     */
600    boolean mPromoteSystemApps;
601
602    @GuardedBy("mPackages")
603    final Settings mSettings;
604
605    /**
606     * Set of package names that are currently "frozen", which means active
607     * surgery is being done on the code/data for that package. The platform
608     * will refuse to launch frozen packages to avoid race conditions.
609     *
610     * @see PackageFreezer
611     */
612    @GuardedBy("mPackages")
613    final ArraySet<String> mFrozenPackages = new ArraySet<>();
614
615    boolean mRestoredSettings;
616
617    // System configuration read by SystemConfig.
618    final int[] mGlobalGids;
619    final SparseArray<ArraySet<String>> mSystemPermissions;
620    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
621
622    // If mac_permissions.xml was found for seinfo labeling.
623    boolean mFoundPolicyFile;
624
625    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
626
627    public static final class SharedLibraryEntry {
628        public final String path;
629        public final String apk;
630
631        SharedLibraryEntry(String _path, String _apk) {
632            path = _path;
633            apk = _apk;
634        }
635    }
636
637    // Currently known shared libraries.
638    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
639            new ArrayMap<String, SharedLibraryEntry>();
640
641    // All available activities, for your resolving pleasure.
642    final ActivityIntentResolver mActivities =
643            new ActivityIntentResolver();
644
645    // All available receivers, for your resolving pleasure.
646    final ActivityIntentResolver mReceivers =
647            new ActivityIntentResolver();
648
649    // All available services, for your resolving pleasure.
650    final ServiceIntentResolver mServices = new ServiceIntentResolver();
651
652    // All available providers, for your resolving pleasure.
653    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
654
655    // Mapping from provider base names (first directory in content URI codePath)
656    // to the provider information.
657    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
658            new ArrayMap<String, PackageParser.Provider>();
659
660    // Mapping from instrumentation class names to info about them.
661    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
662            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
663
664    // Mapping from permission names to info about them.
665    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
666            new ArrayMap<String, PackageParser.PermissionGroup>();
667
668    // Packages whose data we have transfered into another package, thus
669    // should no longer exist.
670    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
671
672    // Broadcast actions that are only available to the system.
673    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
674
675    /** List of packages waiting for verification. */
676    final SparseArray<PackageVerificationState> mPendingVerification
677            = new SparseArray<PackageVerificationState>();
678
679    /** Set of packages associated with each app op permission. */
680    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
681
682    final PackageInstallerService mInstallerService;
683
684    private final PackageDexOptimizer mPackageDexOptimizer;
685
686    private AtomicInteger mNextMoveId = new AtomicInteger();
687    private final MoveCallbacks mMoveCallbacks;
688
689    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
690
691    // Cache of users who need badging.
692    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
693
694    /** Token for keys in mPendingVerification. */
695    private int mPendingVerificationToken = 0;
696
697    volatile boolean mSystemReady;
698    volatile boolean mSafeMode;
699    volatile boolean mHasSystemUidErrors;
700
701    ApplicationInfo mAndroidApplication;
702    final ActivityInfo mResolveActivity = new ActivityInfo();
703    final ResolveInfo mResolveInfo = new ResolveInfo();
704    ComponentName mResolveComponentName;
705    PackageParser.Package mPlatformPackage;
706    ComponentName mCustomResolverComponentName;
707
708    boolean mResolverReplaced = false;
709
710    private final @Nullable ComponentName mIntentFilterVerifierComponent;
711    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
712
713    private int mIntentFilterVerificationToken = 0;
714
715    /** Component that knows whether or not an ephemeral application exists */
716    final ComponentName mEphemeralResolverComponent;
717    /** The service connection to the ephemeral resolver */
718    final EphemeralResolverConnection mEphemeralResolverConnection;
719
720    /** Component used to install ephemeral applications */
721    final ComponentName mEphemeralInstallerComponent;
722    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
723    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
724
725    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
726            = new SparseArray<IntentFilterVerificationState>();
727
728    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
729            new DefaultPermissionGrantPolicy(this);
730
731    // List of packages names to keep cached, even if they are uninstalled for all users
732    private List<String> mKeepUninstalledPackages;
733
734    private static class IFVerificationParams {
735        PackageParser.Package pkg;
736        boolean replacing;
737        int userId;
738        int verifierUid;
739
740        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
741                int _userId, int _verifierUid) {
742            pkg = _pkg;
743            replacing = _replacing;
744            userId = _userId;
745            replacing = _replacing;
746            verifierUid = _verifierUid;
747        }
748    }
749
750    private interface IntentFilterVerifier<T extends IntentFilter> {
751        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
752                                               T filter, String packageName);
753        void startVerifications(int userId);
754        void receiveVerificationResponse(int verificationId);
755    }
756
757    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
758        private Context mContext;
759        private ComponentName mIntentFilterVerifierComponent;
760        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
761
762        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
763            mContext = context;
764            mIntentFilterVerifierComponent = verifierComponent;
765        }
766
767        private String getDefaultScheme() {
768            return IntentFilter.SCHEME_HTTPS;
769        }
770
771        @Override
772        public void startVerifications(int userId) {
773            // Launch verifications requests
774            int count = mCurrentIntentFilterVerifications.size();
775            for (int n=0; n<count; n++) {
776                int verificationId = mCurrentIntentFilterVerifications.get(n);
777                final IntentFilterVerificationState ivs =
778                        mIntentFilterVerificationStates.get(verificationId);
779
780                String packageName = ivs.getPackageName();
781
782                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
783                final int filterCount = filters.size();
784                ArraySet<String> domainsSet = new ArraySet<>();
785                for (int m=0; m<filterCount; m++) {
786                    PackageParser.ActivityIntentInfo filter = filters.get(m);
787                    domainsSet.addAll(filter.getHostsList());
788                }
789                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
790                synchronized (mPackages) {
791                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
792                            packageName, domainsList) != null) {
793                        scheduleWriteSettingsLocked();
794                    }
795                }
796                sendVerificationRequest(userId, verificationId, ivs);
797            }
798            mCurrentIntentFilterVerifications.clear();
799        }
800
801        private void sendVerificationRequest(int userId, int verificationId,
802                IntentFilterVerificationState ivs) {
803
804            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
805            verificationIntent.putExtra(
806                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
807                    verificationId);
808            verificationIntent.putExtra(
809                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
810                    getDefaultScheme());
811            verificationIntent.putExtra(
812                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
813                    ivs.getHostsString());
814            verificationIntent.putExtra(
815                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
816                    ivs.getPackageName());
817            verificationIntent.setComponent(mIntentFilterVerifierComponent);
818            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
819
820            UserHandle user = new UserHandle(userId);
821            mContext.sendBroadcastAsUser(verificationIntent, user);
822            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
823                    "Sending IntentFilter verification broadcast");
824        }
825
826        public void receiveVerificationResponse(int verificationId) {
827            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
828
829            final boolean verified = ivs.isVerified();
830
831            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
832            final int count = filters.size();
833            if (DEBUG_DOMAIN_VERIFICATION) {
834                Slog.i(TAG, "Received verification response " + verificationId
835                        + " for " + count + " filters, verified=" + verified);
836            }
837            for (int n=0; n<count; n++) {
838                PackageParser.ActivityIntentInfo filter = filters.get(n);
839                filter.setVerified(verified);
840
841                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
842                        + " verified with result:" + verified + " and hosts:"
843                        + ivs.getHostsString());
844            }
845
846            mIntentFilterVerificationStates.remove(verificationId);
847
848            final String packageName = ivs.getPackageName();
849            IntentFilterVerificationInfo ivi = null;
850
851            synchronized (mPackages) {
852                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
853            }
854            if (ivi == null) {
855                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
856                        + verificationId + " packageName:" + packageName);
857                return;
858            }
859            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
860                    "Updating IntentFilterVerificationInfo for package " + packageName
861                            +" verificationId:" + verificationId);
862
863            synchronized (mPackages) {
864                if (verified) {
865                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
866                } else {
867                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
868                }
869                scheduleWriteSettingsLocked();
870
871                final int userId = ivs.getUserId();
872                if (userId != UserHandle.USER_ALL) {
873                    final int userStatus =
874                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
875
876                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
877                    boolean needUpdate = false;
878
879                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
880                    // already been set by the User thru the Disambiguation dialog
881                    switch (userStatus) {
882                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
883                            if (verified) {
884                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
885                            } else {
886                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
887                            }
888                            needUpdate = true;
889                            break;
890
891                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
892                            if (verified) {
893                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
894                                needUpdate = true;
895                            }
896                            break;
897
898                        default:
899                            // Nothing to do
900                    }
901
902                    if (needUpdate) {
903                        mSettings.updateIntentFilterVerificationStatusLPw(
904                                packageName, updatedStatus, userId);
905                        scheduleWritePackageRestrictionsLocked(userId);
906                    }
907                }
908            }
909        }
910
911        @Override
912        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
913                    ActivityIntentInfo filter, String packageName) {
914            if (!hasValidDomains(filter)) {
915                return false;
916            }
917            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
918            if (ivs == null) {
919                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
920                        packageName);
921            }
922            if (DEBUG_DOMAIN_VERIFICATION) {
923                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
924            }
925            ivs.addFilter(filter);
926            return true;
927        }
928
929        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
930                int userId, int verificationId, String packageName) {
931            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
932                    verifierUid, userId, packageName);
933            ivs.setPendingState();
934            synchronized (mPackages) {
935                mIntentFilterVerificationStates.append(verificationId, ivs);
936                mCurrentIntentFilterVerifications.add(verificationId);
937            }
938            return ivs;
939        }
940    }
941
942    private static boolean hasValidDomains(ActivityIntentInfo filter) {
943        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
944                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
945                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
946    }
947
948    // Set of pending broadcasts for aggregating enable/disable of components.
949    static class PendingPackageBroadcasts {
950        // for each user id, a map of <package name -> components within that package>
951        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
952
953        public PendingPackageBroadcasts() {
954            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
955        }
956
957        public ArrayList<String> get(int userId, String packageName) {
958            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
959            return packages.get(packageName);
960        }
961
962        public void put(int userId, String packageName, ArrayList<String> components) {
963            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
964            packages.put(packageName, components);
965        }
966
967        public void remove(int userId, String packageName) {
968            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
969            if (packages != null) {
970                packages.remove(packageName);
971            }
972        }
973
974        public void remove(int userId) {
975            mUidMap.remove(userId);
976        }
977
978        public int userIdCount() {
979            return mUidMap.size();
980        }
981
982        public int userIdAt(int n) {
983            return mUidMap.keyAt(n);
984        }
985
986        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
987            return mUidMap.get(userId);
988        }
989
990        public int size() {
991            // total number of pending broadcast entries across all userIds
992            int num = 0;
993            for (int i = 0; i< mUidMap.size(); i++) {
994                num += mUidMap.valueAt(i).size();
995            }
996            return num;
997        }
998
999        public void clear() {
1000            mUidMap.clear();
1001        }
1002
1003        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1004            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1005            if (map == null) {
1006                map = new ArrayMap<String, ArrayList<String>>();
1007                mUidMap.put(userId, map);
1008            }
1009            return map;
1010        }
1011    }
1012    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1013
1014    // Service Connection to remote media container service to copy
1015    // package uri's from external media onto secure containers
1016    // or internal storage.
1017    private IMediaContainerService mContainerService = null;
1018
1019    static final int SEND_PENDING_BROADCAST = 1;
1020    static final int MCS_BOUND = 3;
1021    static final int END_COPY = 4;
1022    static final int INIT_COPY = 5;
1023    static final int MCS_UNBIND = 6;
1024    static final int START_CLEANING_PACKAGE = 7;
1025    static final int FIND_INSTALL_LOC = 8;
1026    static final int POST_INSTALL = 9;
1027    static final int MCS_RECONNECT = 10;
1028    static final int MCS_GIVE_UP = 11;
1029    static final int UPDATED_MEDIA_STATUS = 12;
1030    static final int WRITE_SETTINGS = 13;
1031    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1032    static final int PACKAGE_VERIFIED = 15;
1033    static final int CHECK_PENDING_VERIFICATION = 16;
1034    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1035    static final int INTENT_FILTER_VERIFIED = 18;
1036
1037    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1038
1039    // Delay time in millisecs
1040    static final int BROADCAST_DELAY = 10 * 1000;
1041
1042    static UserManagerService sUserManager;
1043
1044    // Stores a list of users whose package restrictions file needs to be updated
1045    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1046
1047    final private DefaultContainerConnection mDefContainerConn =
1048            new DefaultContainerConnection();
1049    class DefaultContainerConnection implements ServiceConnection {
1050        public void onServiceConnected(ComponentName name, IBinder service) {
1051            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1052            IMediaContainerService imcs =
1053                IMediaContainerService.Stub.asInterface(service);
1054            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1055        }
1056
1057        public void onServiceDisconnected(ComponentName name) {
1058            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1059        }
1060    }
1061
1062    // Recordkeeping of restore-after-install operations that are currently in flight
1063    // between the Package Manager and the Backup Manager
1064    static class PostInstallData {
1065        public InstallArgs args;
1066        public PackageInstalledInfo res;
1067
1068        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1069            args = _a;
1070            res = _r;
1071        }
1072    }
1073
1074    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1075    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1076
1077    // XML tags for backup/restore of various bits of state
1078    private static final String TAG_PREFERRED_BACKUP = "pa";
1079    private static final String TAG_DEFAULT_APPS = "da";
1080    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1081
1082    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1083    private static final String TAG_ALL_GRANTS = "rt-grants";
1084    private static final String TAG_GRANT = "grant";
1085    private static final String ATTR_PACKAGE_NAME = "pkg";
1086
1087    private static final String TAG_PERMISSION = "perm";
1088    private static final String ATTR_PERMISSION_NAME = "name";
1089    private static final String ATTR_IS_GRANTED = "g";
1090    private static final String ATTR_USER_SET = "set";
1091    private static final String ATTR_USER_FIXED = "fixed";
1092    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1093
1094    // System/policy permission grants are not backed up
1095    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1096            FLAG_PERMISSION_POLICY_FIXED
1097            | FLAG_PERMISSION_SYSTEM_FIXED
1098            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1099
1100    // And we back up these user-adjusted states
1101    private static final int USER_RUNTIME_GRANT_MASK =
1102            FLAG_PERMISSION_USER_SET
1103            | FLAG_PERMISSION_USER_FIXED
1104            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1105
1106    final @Nullable String mRequiredVerifierPackage;
1107    final @NonNull String mRequiredInstallerPackage;
1108    final @Nullable String mSetupWizardPackage;
1109    final @NonNull String mServicesSystemSharedLibraryPackageName;
1110    final @NonNull String mSharedSystemSharedLibraryPackageName;
1111
1112    private final PackageUsage mPackageUsage = new PackageUsage();
1113
1114    private class PackageUsage {
1115        private static final int WRITE_INTERVAL
1116            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1117
1118        private final Object mFileLock = new Object();
1119        private final AtomicLong mLastWritten = new AtomicLong(0);
1120        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1121
1122        private boolean mIsHistoricalPackageUsageAvailable = true;
1123
1124        boolean isHistoricalPackageUsageAvailable() {
1125            return mIsHistoricalPackageUsageAvailable;
1126        }
1127
1128        void write(boolean force) {
1129            if (force) {
1130                writeInternal();
1131                return;
1132            }
1133            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1134                && !DEBUG_DEXOPT) {
1135                return;
1136            }
1137            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1138                new Thread("PackageUsage_DiskWriter") {
1139                    @Override
1140                    public void run() {
1141                        try {
1142                            writeInternal();
1143                        } finally {
1144                            mBackgroundWriteRunning.set(false);
1145                        }
1146                    }
1147                }.start();
1148            }
1149        }
1150
1151        private void writeInternal() {
1152            synchronized (mPackages) {
1153                synchronized (mFileLock) {
1154                    AtomicFile file = getFile();
1155                    FileOutputStream f = null;
1156                    try {
1157                        f = file.startWrite();
1158                        BufferedOutputStream out = new BufferedOutputStream(f);
1159                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1160                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1161                        StringBuilder sb = new StringBuilder();
1162
1163                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1164                        sb.append('\n');
1165                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1166
1167                        for (PackageParser.Package pkg : mPackages.values()) {
1168                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1169                                continue;
1170                            }
1171                            sb.setLength(0);
1172                            sb.append(pkg.packageName);
1173                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1174                                sb.append(' ');
1175                                sb.append(usageTimeInMillis);
1176                            }
1177                            sb.append('\n');
1178                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1179                        }
1180                        out.flush();
1181                        file.finishWrite(f);
1182                    } catch (IOException e) {
1183                        if (f != null) {
1184                            file.failWrite(f);
1185                        }
1186                        Log.e(TAG, "Failed to write package usage times", e);
1187                    }
1188                }
1189            }
1190            mLastWritten.set(SystemClock.elapsedRealtime());
1191        }
1192
1193        void readLP() {
1194            synchronized (mFileLock) {
1195                AtomicFile file = getFile();
1196                BufferedInputStream in = null;
1197                try {
1198                    in = new BufferedInputStream(file.openRead());
1199                    StringBuffer sb = new StringBuffer();
1200
1201                    String firstLine = readLine(in, sb);
1202                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1203                        readVersion1LP(in, sb);
1204                    } else {
1205                        readVersion0LP(in, sb, firstLine);
1206                    }
1207                } catch (FileNotFoundException expected) {
1208                    mIsHistoricalPackageUsageAvailable = false;
1209                } catch (IOException e) {
1210                    Log.w(TAG, "Failed to read package usage times", e);
1211                } finally {
1212                    IoUtils.closeQuietly(in);
1213                }
1214            }
1215            mLastWritten.set(SystemClock.elapsedRealtime());
1216        }
1217
1218        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1219                throws IOException {
1220            // Initial version of the file had no version number and stored one
1221            // package-timestamp pair per line.
1222            // Note that the first line has already been read from the InputStream.
1223            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1224                String[] tokens = line.split(" ");
1225                if (tokens.length != 2) {
1226                    throw new IOException("Failed to parse " + line +
1227                            " as package-timestamp pair.");
1228                }
1229
1230                String packageName = tokens[0];
1231                PackageParser.Package pkg = mPackages.get(packageName);
1232                if (pkg == null) {
1233                    continue;
1234                }
1235
1236                long timestamp = parseAsLong(tokens[1]);
1237                for (int reason = 0;
1238                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1239                        reason++) {
1240                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1241                }
1242            }
1243        }
1244
1245        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1246            // Version 1 of the file started with the corresponding version
1247            // number and then stored a package name and eight timestamps per line.
1248            String line;
1249            while ((line = readLine(in, sb)) != null) {
1250                String[] tokens = line.split(" ");
1251                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1252                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1253                }
1254
1255                String packageName = tokens[0];
1256                PackageParser.Package pkg = mPackages.get(packageName);
1257                if (pkg == null) {
1258                    continue;
1259                }
1260
1261                for (int reason = 0;
1262                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1263                        reason++) {
1264                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1265                }
1266            }
1267        }
1268
1269        private long parseAsLong(String token) throws IOException {
1270            try {
1271                return Long.parseLong(token);
1272            } catch (NumberFormatException e) {
1273                throw new IOException("Failed to parse " + token + " as a long.", e);
1274            }
1275        }
1276
1277        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1278            return readToken(in, sb, '\n');
1279        }
1280
1281        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1282                throws IOException {
1283            sb.setLength(0);
1284            while (true) {
1285                int ch = in.read();
1286                if (ch == -1) {
1287                    if (sb.length() == 0) {
1288                        return null;
1289                    }
1290                    throw new IOException("Unexpected EOF");
1291                }
1292                if (ch == endOfToken) {
1293                    return sb.toString();
1294                }
1295                sb.append((char)ch);
1296            }
1297        }
1298
1299        private AtomicFile getFile() {
1300            File dataDir = Environment.getDataDirectory();
1301            File systemDir = new File(dataDir, "system");
1302            File fname = new File(systemDir, "package-usage.list");
1303            return new AtomicFile(fname);
1304        }
1305
1306        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1307        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1308    }
1309
1310    class PackageHandler extends Handler {
1311        private boolean mBound = false;
1312        final ArrayList<HandlerParams> mPendingInstalls =
1313            new ArrayList<HandlerParams>();
1314
1315        private boolean connectToService() {
1316            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1317                    " DefaultContainerService");
1318            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1319            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1320            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1321                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1322                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1323                mBound = true;
1324                return true;
1325            }
1326            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1327            return false;
1328        }
1329
1330        private void disconnectService() {
1331            mContainerService = null;
1332            mBound = false;
1333            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1334            mContext.unbindService(mDefContainerConn);
1335            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1336        }
1337
1338        PackageHandler(Looper looper) {
1339            super(looper);
1340        }
1341
1342        public void handleMessage(Message msg) {
1343            try {
1344                doHandleMessage(msg);
1345            } finally {
1346                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1347            }
1348        }
1349
1350        void doHandleMessage(Message msg) {
1351            switch (msg.what) {
1352                case INIT_COPY: {
1353                    HandlerParams params = (HandlerParams) msg.obj;
1354                    int idx = mPendingInstalls.size();
1355                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1356                    // If a bind was already initiated we dont really
1357                    // need to do anything. The pending install
1358                    // will be processed later on.
1359                    if (!mBound) {
1360                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1361                                System.identityHashCode(mHandler));
1362                        // If this is the only one pending we might
1363                        // have to bind to the service again.
1364                        if (!connectToService()) {
1365                            Slog.e(TAG, "Failed to bind to media container service");
1366                            params.serviceError();
1367                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1368                                    System.identityHashCode(mHandler));
1369                            if (params.traceMethod != null) {
1370                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1371                                        params.traceCookie);
1372                            }
1373                            return;
1374                        } else {
1375                            // Once we bind to the service, the first
1376                            // pending request will be processed.
1377                            mPendingInstalls.add(idx, params);
1378                        }
1379                    } else {
1380                        mPendingInstalls.add(idx, params);
1381                        // Already bound to the service. Just make
1382                        // sure we trigger off processing the first request.
1383                        if (idx == 0) {
1384                            mHandler.sendEmptyMessage(MCS_BOUND);
1385                        }
1386                    }
1387                    break;
1388                }
1389                case MCS_BOUND: {
1390                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1391                    if (msg.obj != null) {
1392                        mContainerService = (IMediaContainerService) msg.obj;
1393                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1394                                System.identityHashCode(mHandler));
1395                    }
1396                    if (mContainerService == null) {
1397                        if (!mBound) {
1398                            // Something seriously wrong since we are not bound and we are not
1399                            // waiting for connection. Bail out.
1400                            Slog.e(TAG, "Cannot bind to media container service");
1401                            for (HandlerParams params : mPendingInstalls) {
1402                                // Indicate service bind error
1403                                params.serviceError();
1404                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1405                                        System.identityHashCode(params));
1406                                if (params.traceMethod != null) {
1407                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1408                                            params.traceMethod, params.traceCookie);
1409                                }
1410                                return;
1411                            }
1412                            mPendingInstalls.clear();
1413                        } else {
1414                            Slog.w(TAG, "Waiting to connect to media container service");
1415                        }
1416                    } else if (mPendingInstalls.size() > 0) {
1417                        HandlerParams params = mPendingInstalls.get(0);
1418                        if (params != null) {
1419                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1420                                    System.identityHashCode(params));
1421                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1422                            if (params.startCopy()) {
1423                                // We are done...  look for more work or to
1424                                // go idle.
1425                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1426                                        "Checking for more work or unbind...");
1427                                // Delete pending install
1428                                if (mPendingInstalls.size() > 0) {
1429                                    mPendingInstalls.remove(0);
1430                                }
1431                                if (mPendingInstalls.size() == 0) {
1432                                    if (mBound) {
1433                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1434                                                "Posting delayed MCS_UNBIND");
1435                                        removeMessages(MCS_UNBIND);
1436                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1437                                        // Unbind after a little delay, to avoid
1438                                        // continual thrashing.
1439                                        sendMessageDelayed(ubmsg, 10000);
1440                                    }
1441                                } else {
1442                                    // There are more pending requests in queue.
1443                                    // Just post MCS_BOUND message to trigger processing
1444                                    // of next pending install.
1445                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1446                                            "Posting MCS_BOUND for next work");
1447                                    mHandler.sendEmptyMessage(MCS_BOUND);
1448                                }
1449                            }
1450                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1451                        }
1452                    } else {
1453                        // Should never happen ideally.
1454                        Slog.w(TAG, "Empty queue");
1455                    }
1456                    break;
1457                }
1458                case MCS_RECONNECT: {
1459                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1460                    if (mPendingInstalls.size() > 0) {
1461                        if (mBound) {
1462                            disconnectService();
1463                        }
1464                        if (!connectToService()) {
1465                            Slog.e(TAG, "Failed to bind to media container service");
1466                            for (HandlerParams params : mPendingInstalls) {
1467                                // Indicate service bind error
1468                                params.serviceError();
1469                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1470                                        System.identityHashCode(params));
1471                            }
1472                            mPendingInstalls.clear();
1473                        }
1474                    }
1475                    break;
1476                }
1477                case MCS_UNBIND: {
1478                    // If there is no actual work left, then time to unbind.
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1480
1481                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1482                        if (mBound) {
1483                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1484
1485                            disconnectService();
1486                        }
1487                    } else if (mPendingInstalls.size() > 0) {
1488                        // There are more pending requests in queue.
1489                        // Just post MCS_BOUND message to trigger processing
1490                        // of next pending install.
1491                        mHandler.sendEmptyMessage(MCS_BOUND);
1492                    }
1493
1494                    break;
1495                }
1496                case MCS_GIVE_UP: {
1497                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1498                    HandlerParams params = mPendingInstalls.remove(0);
1499                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1500                            System.identityHashCode(params));
1501                    break;
1502                }
1503                case SEND_PENDING_BROADCAST: {
1504                    String packages[];
1505                    ArrayList<String> components[];
1506                    int size = 0;
1507                    int uids[];
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1509                    synchronized (mPackages) {
1510                        if (mPendingBroadcasts == null) {
1511                            return;
1512                        }
1513                        size = mPendingBroadcasts.size();
1514                        if (size <= 0) {
1515                            // Nothing to be done. Just return
1516                            return;
1517                        }
1518                        packages = new String[size];
1519                        components = new ArrayList[size];
1520                        uids = new int[size];
1521                        int i = 0;  // filling out the above arrays
1522
1523                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1524                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1525                            Iterator<Map.Entry<String, ArrayList<String>>> it
1526                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1527                                            .entrySet().iterator();
1528                            while (it.hasNext() && i < size) {
1529                                Map.Entry<String, ArrayList<String>> ent = it.next();
1530                                packages[i] = ent.getKey();
1531                                components[i] = ent.getValue();
1532                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1533                                uids[i] = (ps != null)
1534                                        ? UserHandle.getUid(packageUserId, ps.appId)
1535                                        : -1;
1536                                i++;
1537                            }
1538                        }
1539                        size = i;
1540                        mPendingBroadcasts.clear();
1541                    }
1542                    // Send broadcasts
1543                    for (int i = 0; i < size; i++) {
1544                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1545                    }
1546                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1547                    break;
1548                }
1549                case START_CLEANING_PACKAGE: {
1550                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1551                    final String packageName = (String)msg.obj;
1552                    final int userId = msg.arg1;
1553                    final boolean andCode = msg.arg2 != 0;
1554                    synchronized (mPackages) {
1555                        if (userId == UserHandle.USER_ALL) {
1556                            int[] users = sUserManager.getUserIds();
1557                            for (int user : users) {
1558                                mSettings.addPackageToCleanLPw(
1559                                        new PackageCleanItem(user, packageName, andCode));
1560                            }
1561                        } else {
1562                            mSettings.addPackageToCleanLPw(
1563                                    new PackageCleanItem(userId, packageName, andCode));
1564                        }
1565                    }
1566                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1567                    startCleaningPackages();
1568                } break;
1569                case POST_INSTALL: {
1570                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1571
1572                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1573                    mRunningInstalls.delete(msg.arg1);
1574
1575                    if (data != null) {
1576                        InstallArgs args = data.args;
1577                        PackageInstalledInfo parentRes = data.res;
1578
1579                        final boolean grantPermissions = (args.installFlags
1580                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1581                        final boolean killApp = (args.installFlags
1582                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1583                        final String[] grantedPermissions = args.installGrantPermissions;
1584
1585                        // Handle the parent package
1586                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1587                                grantedPermissions, args.observer);
1588
1589                        // Handle the child packages
1590                        final int childCount = (parentRes.addedChildPackages != null)
1591                                ? parentRes.addedChildPackages.size() : 0;
1592                        for (int i = 0; i < childCount; i++) {
1593                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1594                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1595                                    grantedPermissions, args.observer);
1596                        }
1597
1598                        // Log tracing if needed
1599                        if (args.traceMethod != null) {
1600                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1601                                    args.traceCookie);
1602                        }
1603                    } else {
1604                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1605                    }
1606
1607                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1608                } break;
1609                case UPDATED_MEDIA_STATUS: {
1610                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1611                    boolean reportStatus = msg.arg1 == 1;
1612                    boolean doGc = msg.arg2 == 1;
1613                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1614                    if (doGc) {
1615                        // Force a gc to clear up stale containers.
1616                        Runtime.getRuntime().gc();
1617                    }
1618                    if (msg.obj != null) {
1619                        @SuppressWarnings("unchecked")
1620                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1621                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1622                        // Unload containers
1623                        unloadAllContainers(args);
1624                    }
1625                    if (reportStatus) {
1626                        try {
1627                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1628                            PackageHelper.getMountService().finishMediaUpdate();
1629                        } catch (RemoteException e) {
1630                            Log.e(TAG, "MountService not running?");
1631                        }
1632                    }
1633                } break;
1634                case WRITE_SETTINGS: {
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1636                    synchronized (mPackages) {
1637                        removeMessages(WRITE_SETTINGS);
1638                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1639                        mSettings.writeLPr();
1640                        mDirtyUsers.clear();
1641                    }
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1643                } break;
1644                case WRITE_PACKAGE_RESTRICTIONS: {
1645                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1646                    synchronized (mPackages) {
1647                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1648                        for (int userId : mDirtyUsers) {
1649                            mSettings.writePackageRestrictionsLPr(userId);
1650                        }
1651                        mDirtyUsers.clear();
1652                    }
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1654                } break;
1655                case CHECK_PENDING_VERIFICATION: {
1656                    final int verificationId = msg.arg1;
1657                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1658
1659                    if ((state != null) && !state.timeoutExtended()) {
1660                        final InstallArgs args = state.getInstallArgs();
1661                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1662
1663                        Slog.i(TAG, "Verification timed out for " + originUri);
1664                        mPendingVerification.remove(verificationId);
1665
1666                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1667
1668                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1669                            Slog.i(TAG, "Continuing with installation of " + originUri);
1670                            state.setVerifierResponse(Binder.getCallingUid(),
1671                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1672                            broadcastPackageVerified(verificationId, originUri,
1673                                    PackageManager.VERIFICATION_ALLOW,
1674                                    state.getInstallArgs().getUser());
1675                            try {
1676                                ret = args.copyApk(mContainerService, true);
1677                            } catch (RemoteException e) {
1678                                Slog.e(TAG, "Could not contact the ContainerService");
1679                            }
1680                        } else {
1681                            broadcastPackageVerified(verificationId, originUri,
1682                                    PackageManager.VERIFICATION_REJECT,
1683                                    state.getInstallArgs().getUser());
1684                        }
1685
1686                        Trace.asyncTraceEnd(
1687                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1688
1689                        processPendingInstall(args, ret);
1690                        mHandler.sendEmptyMessage(MCS_UNBIND);
1691                    }
1692                    break;
1693                }
1694                case PACKAGE_VERIFIED: {
1695                    final int verificationId = msg.arg1;
1696
1697                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1698                    if (state == null) {
1699                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1700                        break;
1701                    }
1702
1703                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1704
1705                    state.setVerifierResponse(response.callerUid, response.code);
1706
1707                    if (state.isVerificationComplete()) {
1708                        mPendingVerification.remove(verificationId);
1709
1710                        final InstallArgs args = state.getInstallArgs();
1711                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1712
1713                        int ret;
1714                        if (state.isInstallAllowed()) {
1715                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1716                            broadcastPackageVerified(verificationId, originUri,
1717                                    response.code, state.getInstallArgs().getUser());
1718                            try {
1719                                ret = args.copyApk(mContainerService, true);
1720                            } catch (RemoteException e) {
1721                                Slog.e(TAG, "Could not contact the ContainerService");
1722                            }
1723                        } else {
1724                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1725                        }
1726
1727                        Trace.asyncTraceEnd(
1728                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1729
1730                        processPendingInstall(args, ret);
1731                        mHandler.sendEmptyMessage(MCS_UNBIND);
1732                    }
1733
1734                    break;
1735                }
1736                case START_INTENT_FILTER_VERIFICATIONS: {
1737                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1738                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1739                            params.replacing, params.pkg);
1740                    break;
1741                }
1742                case INTENT_FILTER_VERIFIED: {
1743                    final int verificationId = msg.arg1;
1744
1745                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1746                            verificationId);
1747                    if (state == null) {
1748                        Slog.w(TAG, "Invalid IntentFilter verification token "
1749                                + verificationId + " received");
1750                        break;
1751                    }
1752
1753                    final int userId = state.getUserId();
1754
1755                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1756                            "Processing IntentFilter verification with token:"
1757                            + verificationId + " and userId:" + userId);
1758
1759                    final IntentFilterVerificationResponse response =
1760                            (IntentFilterVerificationResponse) msg.obj;
1761
1762                    state.setVerifierResponse(response.callerUid, response.code);
1763
1764                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1765                            "IntentFilter verification with token:" + verificationId
1766                            + " and userId:" + userId
1767                            + " is settings verifier response with response code:"
1768                            + response.code);
1769
1770                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1771                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1772                                + response.getFailedDomainsString());
1773                    }
1774
1775                    if (state.isVerificationComplete()) {
1776                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1777                    } else {
1778                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1779                                "IntentFilter verification with token:" + verificationId
1780                                + " was not said to be complete");
1781                    }
1782
1783                    break;
1784                }
1785            }
1786        }
1787    }
1788
1789    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1790            boolean killApp, String[] grantedPermissions,
1791            IPackageInstallObserver2 installObserver) {
1792        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1793            // Send the removed broadcasts
1794            if (res.removedInfo != null) {
1795                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1796            }
1797
1798            // Now that we successfully installed the package, grant runtime
1799            // permissions if requested before broadcasting the install.
1800            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1801                    >= Build.VERSION_CODES.M) {
1802                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1803            }
1804
1805            final boolean update = res.removedInfo != null
1806                    && res.removedInfo.removedPackage != null;
1807
1808            // If this is the first time we have child packages for a disabled privileged
1809            // app that had no children, we grant requested runtime permissions to the new
1810            // children if the parent on the system image had them already granted.
1811            if (res.pkg.parentPackage != null) {
1812                synchronized (mPackages) {
1813                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1814                }
1815            }
1816
1817            synchronized (mPackages) {
1818                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1819            }
1820
1821            final String packageName = res.pkg.applicationInfo.packageName;
1822            Bundle extras = new Bundle(1);
1823            extras.putInt(Intent.EXTRA_UID, res.uid);
1824
1825            // Determine the set of users who are adding this package for
1826            // the first time vs. those who are seeing an update.
1827            int[] firstUsers = EMPTY_INT_ARRAY;
1828            int[] updateUsers = EMPTY_INT_ARRAY;
1829            if (res.origUsers == null || res.origUsers.length == 0) {
1830                firstUsers = res.newUsers;
1831            } else {
1832                for (int newUser : res.newUsers) {
1833                    boolean isNew = true;
1834                    for (int origUser : res.origUsers) {
1835                        if (origUser == newUser) {
1836                            isNew = false;
1837                            break;
1838                        }
1839                    }
1840                    if (isNew) {
1841                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1842                    } else {
1843                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1844                    }
1845                }
1846            }
1847
1848            // Send installed broadcasts if the install/update is not ephemeral
1849            if (!isEphemeral(res.pkg)) {
1850                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1851
1852                // Send added for users that see the package for the first time
1853                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1854                        extras, 0 /*flags*/, null /*targetPackage*/,
1855                        null /*finishedReceiver*/, firstUsers);
1856
1857                // Send added for users that don't see the package for the first time
1858                if (update) {
1859                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1860                }
1861                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1862                        extras, 0 /*flags*/, null /*targetPackage*/,
1863                        null /*finishedReceiver*/, updateUsers);
1864
1865                // Send replaced for users that don't see the package for the first time
1866                if (update) {
1867                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1868                            packageName, extras, 0 /*flags*/,
1869                            null /*targetPackage*/, null /*finishedReceiver*/,
1870                            updateUsers);
1871                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1872                            null /*package*/, null /*extras*/, 0 /*flags*/,
1873                            packageName /*targetPackage*/,
1874                            null /*finishedReceiver*/, updateUsers);
1875                }
1876
1877                // Send broadcast package appeared if forward locked/external for all users
1878                // treat asec-hosted packages like removable media on upgrade
1879                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1880                    if (DEBUG_INSTALL) {
1881                        Slog.i(TAG, "upgrading pkg " + res.pkg
1882                                + " is ASEC-hosted -> AVAILABLE");
1883                    }
1884                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1885                    ArrayList<String> pkgList = new ArrayList<>(1);
1886                    pkgList.add(packageName);
1887                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1888                }
1889            }
1890
1891            // Work that needs to happen on first install within each user
1892            if (firstUsers != null && firstUsers.length > 0) {
1893                synchronized (mPackages) {
1894                    for (int userId : firstUsers) {
1895                        // If this app is a browser and it's newly-installed for some
1896                        // users, clear any default-browser state in those users. The
1897                        // app's nature doesn't depend on the user, so we can just check
1898                        // its browser nature in any user and generalize.
1899                        if (packageIsBrowser(packageName, userId)) {
1900                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1901                        }
1902
1903                        // We may also need to apply pending (restored) runtime
1904                        // permission grants within these users.
1905                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1906                    }
1907                }
1908            }
1909
1910            // Log current value of "unknown sources" setting
1911            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1912                    getUnknownSourcesSettings());
1913
1914            // Force a gc to clear up things
1915            Runtime.getRuntime().gc();
1916
1917            // Remove the replaced package's older resources safely now
1918            // We delete after a gc for applications  on sdcard.
1919            if (res.removedInfo != null && res.removedInfo.args != null) {
1920                synchronized (mInstallLock) {
1921                    res.removedInfo.args.doPostDeleteLI(true);
1922                }
1923            }
1924        }
1925
1926        // If someone is watching installs - notify them
1927        if (installObserver != null) {
1928            try {
1929                Bundle extras = extrasForInstallResult(res);
1930                installObserver.onPackageInstalled(res.name, res.returnCode,
1931                        res.returnMsg, extras);
1932            } catch (RemoteException e) {
1933                Slog.i(TAG, "Observer no longer exists.");
1934            }
1935        }
1936    }
1937
1938    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1939            PackageParser.Package pkg) {
1940        if (pkg.parentPackage == null) {
1941            return;
1942        }
1943        if (pkg.requestedPermissions == null) {
1944            return;
1945        }
1946        final PackageSetting disabledSysParentPs = mSettings
1947                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1948        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1949                || !disabledSysParentPs.isPrivileged()
1950                || (disabledSysParentPs.childPackageNames != null
1951                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1952            return;
1953        }
1954        final int[] allUserIds = sUserManager.getUserIds();
1955        final int permCount = pkg.requestedPermissions.size();
1956        for (int i = 0; i < permCount; i++) {
1957            String permission = pkg.requestedPermissions.get(i);
1958            BasePermission bp = mSettings.mPermissions.get(permission);
1959            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1960                continue;
1961            }
1962            for (int userId : allUserIds) {
1963                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1964                        permission, userId)) {
1965                    grantRuntimePermission(pkg.packageName, permission, userId);
1966                }
1967            }
1968        }
1969    }
1970
1971    private StorageEventListener mStorageListener = new StorageEventListener() {
1972        @Override
1973        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1974            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1975                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1976                    final String volumeUuid = vol.getFsUuid();
1977
1978                    // Clean up any users or apps that were removed or recreated
1979                    // while this volume was missing
1980                    reconcileUsers(volumeUuid);
1981                    reconcileApps(volumeUuid);
1982
1983                    // Clean up any install sessions that expired or were
1984                    // cancelled while this volume was missing
1985                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1986
1987                    loadPrivatePackages(vol);
1988
1989                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1990                    unloadPrivatePackages(vol);
1991                }
1992            }
1993
1994            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1995                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1996                    updateExternalMediaStatus(true, false);
1997                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1998                    updateExternalMediaStatus(false, false);
1999                }
2000            }
2001        }
2002
2003        @Override
2004        public void onVolumeForgotten(String fsUuid) {
2005            if (TextUtils.isEmpty(fsUuid)) {
2006                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2007                return;
2008            }
2009
2010            // Remove any apps installed on the forgotten volume
2011            synchronized (mPackages) {
2012                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2013                for (PackageSetting ps : packages) {
2014                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2015                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2016                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2017                }
2018
2019                mSettings.onVolumeForgotten(fsUuid);
2020                mSettings.writeLPr();
2021            }
2022        }
2023    };
2024
2025    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2026            String[] grantedPermissions) {
2027        for (int userId : userIds) {
2028            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2029        }
2030
2031        // We could have touched GID membership, so flush out packages.list
2032        synchronized (mPackages) {
2033            mSettings.writePackageListLPr();
2034        }
2035    }
2036
2037    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2038            String[] grantedPermissions) {
2039        SettingBase sb = (SettingBase) pkg.mExtras;
2040        if (sb == null) {
2041            return;
2042        }
2043
2044        PermissionsState permissionsState = sb.getPermissionsState();
2045
2046        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2047                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2048
2049        for (String permission : pkg.requestedPermissions) {
2050            final BasePermission bp;
2051            synchronized (mPackages) {
2052                bp = mSettings.mPermissions.get(permission);
2053            }
2054            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2055                    && (grantedPermissions == null
2056                           || ArrayUtils.contains(grantedPermissions, permission))) {
2057                final int flags = permissionsState.getPermissionFlags(permission, userId);
2058                // Installer cannot change immutable permissions.
2059                if ((flags & immutableFlags) == 0) {
2060                    grantRuntimePermission(pkg.packageName, permission, userId);
2061                }
2062            }
2063        }
2064    }
2065
2066    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2067        Bundle extras = null;
2068        switch (res.returnCode) {
2069            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2070                extras = new Bundle();
2071                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2072                        res.origPermission);
2073                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2074                        res.origPackage);
2075                break;
2076            }
2077            case PackageManager.INSTALL_SUCCEEDED: {
2078                extras = new Bundle();
2079                extras.putBoolean(Intent.EXTRA_REPLACING,
2080                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2081                break;
2082            }
2083        }
2084        return extras;
2085    }
2086
2087    void scheduleWriteSettingsLocked() {
2088        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2089            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2090        }
2091    }
2092
2093    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2094        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2095        scheduleWritePackageRestrictionsLocked(userId);
2096    }
2097
2098    void scheduleWritePackageRestrictionsLocked(int userId) {
2099        final int[] userIds = (userId == UserHandle.USER_ALL)
2100                ? sUserManager.getUserIds() : new int[]{userId};
2101        for (int nextUserId : userIds) {
2102            if (!sUserManager.exists(nextUserId)) return;
2103            mDirtyUsers.add(nextUserId);
2104            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2105                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2106            }
2107        }
2108    }
2109
2110    public static PackageManagerService main(Context context, Installer installer,
2111            boolean factoryTest, boolean onlyCore) {
2112        // Self-check for initial settings.
2113        PackageManagerServiceCompilerMapping.checkProperties();
2114
2115        PackageManagerService m = new PackageManagerService(context, installer,
2116                factoryTest, onlyCore);
2117        m.enableSystemUserPackages();
2118        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2119        // disabled after already being started.
2120        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2121                UserHandle.USER_SYSTEM);
2122        ServiceManager.addService("package", m);
2123        return m;
2124    }
2125
2126    private void enableSystemUserPackages() {
2127        if (!UserManager.isSplitSystemUser()) {
2128            return;
2129        }
2130        // For system user, enable apps based on the following conditions:
2131        // - app is whitelisted or belong to one of these groups:
2132        //   -- system app which has no launcher icons
2133        //   -- system app which has INTERACT_ACROSS_USERS permission
2134        //   -- system IME app
2135        // - app is not in the blacklist
2136        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2137        Set<String> enableApps = new ArraySet<>();
2138        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2139                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2140                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2141        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2142        enableApps.addAll(wlApps);
2143        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2144                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2145        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2146        enableApps.removeAll(blApps);
2147        Log.i(TAG, "Applications installed for system user: " + enableApps);
2148        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2149                UserHandle.SYSTEM);
2150        final int allAppsSize = allAps.size();
2151        synchronized (mPackages) {
2152            for (int i = 0; i < allAppsSize; i++) {
2153                String pName = allAps.get(i);
2154                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2155                // Should not happen, but we shouldn't be failing if it does
2156                if (pkgSetting == null) {
2157                    continue;
2158                }
2159                boolean install = enableApps.contains(pName);
2160                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2161                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2162                            + " for system user");
2163                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2164                }
2165            }
2166        }
2167    }
2168
2169    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2170        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2171                Context.DISPLAY_SERVICE);
2172        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2173    }
2174
2175    public PackageManagerService(Context context, Installer installer,
2176            boolean factoryTest, boolean onlyCore) {
2177        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2178                SystemClock.uptimeMillis());
2179
2180        if (mSdkVersion <= 0) {
2181            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2182        }
2183
2184        mContext = context;
2185        mFactoryTest = factoryTest;
2186        mOnlyCore = onlyCore;
2187        mMetrics = new DisplayMetrics();
2188        mSettings = new Settings(mPackages);
2189        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2190                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2191        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2192                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2193        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2194                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2195        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2196                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2197        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2198                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2199        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2200                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2201
2202        String separateProcesses = SystemProperties.get("debug.separate_processes");
2203        if (separateProcesses != null && separateProcesses.length() > 0) {
2204            if ("*".equals(separateProcesses)) {
2205                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2206                mSeparateProcesses = null;
2207                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2208            } else {
2209                mDefParseFlags = 0;
2210                mSeparateProcesses = separateProcesses.split(",");
2211                Slog.w(TAG, "Running with debug.separate_processes: "
2212                        + separateProcesses);
2213            }
2214        } else {
2215            mDefParseFlags = 0;
2216            mSeparateProcesses = null;
2217        }
2218
2219        mInstaller = installer;
2220        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2221                "*dexopt*");
2222        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2223
2224        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2225                FgThread.get().getLooper());
2226
2227        getDefaultDisplayMetrics(context, mMetrics);
2228
2229        SystemConfig systemConfig = SystemConfig.getInstance();
2230        mGlobalGids = systemConfig.getGlobalGids();
2231        mSystemPermissions = systemConfig.getSystemPermissions();
2232        mAvailableFeatures = systemConfig.getAvailableFeatures();
2233
2234        synchronized (mInstallLock) {
2235        // writer
2236        synchronized (mPackages) {
2237            mHandlerThread = new ServiceThread(TAG,
2238                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2239            mHandlerThread.start();
2240            mHandler = new PackageHandler(mHandlerThread.getLooper());
2241            mProcessLoggingHandler = new ProcessLoggingHandler();
2242            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2243
2244            File dataDir = Environment.getDataDirectory();
2245            mAppInstallDir = new File(dataDir, "app");
2246            mAppLib32InstallDir = new File(dataDir, "app-lib");
2247            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2248            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2249            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2250
2251            sUserManager = new UserManagerService(context, this, mPackages);
2252
2253            // Propagate permission configuration in to package manager.
2254            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2255                    = systemConfig.getPermissions();
2256            for (int i=0; i<permConfig.size(); i++) {
2257                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2258                BasePermission bp = mSettings.mPermissions.get(perm.name);
2259                if (bp == null) {
2260                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2261                    mSettings.mPermissions.put(perm.name, bp);
2262                }
2263                if (perm.gids != null) {
2264                    bp.setGids(perm.gids, perm.perUser);
2265                }
2266            }
2267
2268            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2269            for (int i=0; i<libConfig.size(); i++) {
2270                mSharedLibraries.put(libConfig.keyAt(i),
2271                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2272            }
2273
2274            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2275
2276            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2277
2278            String customResolverActivity = Resources.getSystem().getString(
2279                    R.string.config_customResolverActivity);
2280            if (TextUtils.isEmpty(customResolverActivity)) {
2281                customResolverActivity = null;
2282            } else {
2283                mCustomResolverComponentName = ComponentName.unflattenFromString(
2284                        customResolverActivity);
2285            }
2286
2287            long startTime = SystemClock.uptimeMillis();
2288
2289            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2290                    startTime);
2291
2292            // Set flag to monitor and not change apk file paths when
2293            // scanning install directories.
2294            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2295
2296            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2297            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2298
2299            if (bootClassPath == null) {
2300                Slog.w(TAG, "No BOOTCLASSPATH found!");
2301            }
2302
2303            if (systemServerClassPath == null) {
2304                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2305            }
2306
2307            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2308            final String[] dexCodeInstructionSets =
2309                    getDexCodeInstructionSets(
2310                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2311
2312            /**
2313             * Ensure all external libraries have had dexopt run on them.
2314             */
2315            if (mSharedLibraries.size() > 0) {
2316                // NOTE: For now, we're compiling these system "shared libraries"
2317                // (and framework jars) into all available architectures. It's possible
2318                // to compile them only when we come across an app that uses them (there's
2319                // already logic for that in scanPackageLI) but that adds some complexity.
2320                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2321                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2322                        final String lib = libEntry.path;
2323                        if (lib == null) {
2324                            continue;
2325                        }
2326
2327                        try {
2328                            // Shared libraries do not have profiles so we perform a full
2329                            // AOT compilation (if needed).
2330                            int dexoptNeeded = DexFile.getDexOptNeeded(
2331                                    lib, dexCodeInstructionSet,
2332                                    getCompilerFilterForReason(REASON_SHARED_APK),
2333                                    false /* newProfile */);
2334                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2335                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2336                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2337                                        getCompilerFilterForReason(REASON_SHARED_APK),
2338                                        StorageManager.UUID_PRIVATE_INTERNAL,
2339                                        SPECIAL_SHARED_LIBRARY);
2340                            }
2341                        } catch (FileNotFoundException e) {
2342                            Slog.w(TAG, "Library not found: " + lib);
2343                        } catch (IOException | InstallerException e) {
2344                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2345                                    + e.getMessage());
2346                        }
2347                    }
2348                }
2349            }
2350
2351            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2352
2353            final VersionInfo ver = mSettings.getInternalVersion();
2354            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2355
2356            // when upgrading from pre-M, promote system app permissions from install to runtime
2357            mPromoteSystemApps =
2358                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2359
2360            // save off the names of pre-existing system packages prior to scanning; we don't
2361            // want to automatically grant runtime permissions for new system apps
2362            if (mPromoteSystemApps) {
2363                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2364                while (pkgSettingIter.hasNext()) {
2365                    PackageSetting ps = pkgSettingIter.next();
2366                    if (isSystemApp(ps)) {
2367                        mExistingSystemPackages.add(ps.name);
2368                    }
2369                }
2370            }
2371
2372            // When upgrading from pre-N, we need to handle package extraction like first boot,
2373            // as there is no profiling data available.
2374            mIsPreNUpgrade = !mSettings.isNWorkDone();
2375            mSettings.setNWorkDone();
2376
2377            // Collect vendor overlay packages.
2378            // (Do this before scanning any apps.)
2379            // For security and version matching reason, only consider
2380            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2381            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2382            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2383                    | PackageParser.PARSE_IS_SYSTEM
2384                    | PackageParser.PARSE_IS_SYSTEM_DIR
2385                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2386
2387            // Find base frameworks (resource packages without code).
2388            scanDirTracedLI(frameworkDir, mDefParseFlags
2389                    | PackageParser.PARSE_IS_SYSTEM
2390                    | PackageParser.PARSE_IS_SYSTEM_DIR
2391                    | PackageParser.PARSE_IS_PRIVILEGED,
2392                    scanFlags | SCAN_NO_DEX, 0);
2393
2394            // Collected privileged system packages.
2395            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2396            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2397                    | PackageParser.PARSE_IS_SYSTEM
2398                    | PackageParser.PARSE_IS_SYSTEM_DIR
2399                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2400
2401            // Collect ordinary system packages.
2402            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2403            scanDirTracedLI(systemAppDir, mDefParseFlags
2404                    | PackageParser.PARSE_IS_SYSTEM
2405                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2406
2407            // Collect all vendor packages.
2408            File vendorAppDir = new File("/vendor/app");
2409            try {
2410                vendorAppDir = vendorAppDir.getCanonicalFile();
2411            } catch (IOException e) {
2412                // failed to look up canonical path, continue with original one
2413            }
2414            scanDirTracedLI(vendorAppDir, mDefParseFlags
2415                    | PackageParser.PARSE_IS_SYSTEM
2416                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2417
2418            // Collect all OEM packages.
2419            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2420            scanDirTracedLI(oemAppDir, mDefParseFlags
2421                    | PackageParser.PARSE_IS_SYSTEM
2422                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2423
2424            // Prune any system packages that no longer exist.
2425            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2426            if (!mOnlyCore) {
2427                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2428                while (psit.hasNext()) {
2429                    PackageSetting ps = psit.next();
2430
2431                    /*
2432                     * If this is not a system app, it can't be a
2433                     * disable system app.
2434                     */
2435                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2436                        continue;
2437                    }
2438
2439                    /*
2440                     * If the package is scanned, it's not erased.
2441                     */
2442                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2443                    if (scannedPkg != null) {
2444                        /*
2445                         * If the system app is both scanned and in the
2446                         * disabled packages list, then it must have been
2447                         * added via OTA. Remove it from the currently
2448                         * scanned package so the previously user-installed
2449                         * application can be scanned.
2450                         */
2451                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2452                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2453                                    + ps.name + "; removing system app.  Last known codePath="
2454                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2455                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2456                                    + scannedPkg.mVersionCode);
2457                            removePackageLI(scannedPkg, true);
2458                            mExpectingBetter.put(ps.name, ps.codePath);
2459                        }
2460
2461                        continue;
2462                    }
2463
2464                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2465                        psit.remove();
2466                        logCriticalInfo(Log.WARN, "System package " + ps.name
2467                                + " no longer exists; it's data will be wiped");
2468                        // Actual deletion of code and data will be handled by later
2469                        // reconciliation step
2470                    } else {
2471                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2472                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2473                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2474                        }
2475                    }
2476                }
2477            }
2478
2479            //look for any incomplete package installations
2480            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2481            for (int i = 0; i < deletePkgsList.size(); i++) {
2482                // Actual deletion of code and data will be handled by later
2483                // reconciliation step
2484                final String packageName = deletePkgsList.get(i).name;
2485                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2486                synchronized (mPackages) {
2487                    mSettings.removePackageLPw(packageName);
2488                }
2489            }
2490
2491            //delete tmp files
2492            deleteTempPackageFiles();
2493
2494            // Remove any shared userIDs that have no associated packages
2495            mSettings.pruneSharedUsersLPw();
2496
2497            if (!mOnlyCore) {
2498                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2499                        SystemClock.uptimeMillis());
2500                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2501
2502                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2503                        | PackageParser.PARSE_FORWARD_LOCK,
2504                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2505
2506                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2507                        | PackageParser.PARSE_IS_EPHEMERAL,
2508                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2509
2510                /**
2511                 * Remove disable package settings for any updated system
2512                 * apps that were removed via an OTA. If they're not a
2513                 * previously-updated app, remove them completely.
2514                 * Otherwise, just revoke their system-level permissions.
2515                 */
2516                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2517                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2518                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2519
2520                    String msg;
2521                    if (deletedPkg == null) {
2522                        msg = "Updated system package " + deletedAppName
2523                                + " no longer exists; it's data will be wiped";
2524                        // Actual deletion of code and data will be handled by later
2525                        // reconciliation step
2526                    } else {
2527                        msg = "Updated system app + " + deletedAppName
2528                                + " no longer present; removing system privileges for "
2529                                + deletedAppName;
2530
2531                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2532
2533                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2534                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2535                    }
2536                    logCriticalInfo(Log.WARN, msg);
2537                }
2538
2539                /**
2540                 * Make sure all system apps that we expected to appear on
2541                 * the userdata partition actually showed up. If they never
2542                 * appeared, crawl back and revive the system version.
2543                 */
2544                for (int i = 0; i < mExpectingBetter.size(); i++) {
2545                    final String packageName = mExpectingBetter.keyAt(i);
2546                    if (!mPackages.containsKey(packageName)) {
2547                        final File scanFile = mExpectingBetter.valueAt(i);
2548
2549                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2550                                + " but never showed up; reverting to system");
2551
2552                        int reparseFlags = mDefParseFlags;
2553                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2554                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2555                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2556                                    | PackageParser.PARSE_IS_PRIVILEGED;
2557                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2558                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2559                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2560                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2561                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2562                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2563                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2564                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2565                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2566                        } else {
2567                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2568                            continue;
2569                        }
2570
2571                        mSettings.enableSystemPackageLPw(packageName);
2572
2573                        try {
2574                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2575                        } catch (PackageManagerException e) {
2576                            Slog.e(TAG, "Failed to parse original system package: "
2577                                    + e.getMessage());
2578                        }
2579                    }
2580                }
2581            }
2582            mExpectingBetter.clear();
2583
2584            // Resolve protected action filters. Only the setup wizard is allowed to
2585            // have a high priority filter for these actions.
2586            mSetupWizardPackage = getSetupWizardPackageName();
2587            if (mProtectedFilters.size() > 0) {
2588                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2589                    Slog.i(TAG, "No setup wizard;"
2590                        + " All protected intents capped to priority 0");
2591                }
2592                for (ActivityIntentInfo filter : mProtectedFilters) {
2593                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2594                        if (DEBUG_FILTERS) {
2595                            Slog.i(TAG, "Found setup wizard;"
2596                                + " allow priority " + filter.getPriority() + ";"
2597                                + " package: " + filter.activity.info.packageName
2598                                + " activity: " + filter.activity.className
2599                                + " priority: " + filter.getPriority());
2600                        }
2601                        // skip setup wizard; allow it to keep the high priority filter
2602                        continue;
2603                    }
2604                    Slog.w(TAG, "Protected action; cap priority to 0;"
2605                            + " package: " + filter.activity.info.packageName
2606                            + " activity: " + filter.activity.className
2607                            + " origPrio: " + filter.getPriority());
2608                    filter.setPriority(0);
2609                }
2610            }
2611            mDeferProtectedFilters = false;
2612            mProtectedFilters.clear();
2613
2614            // Now that we know all of the shared libraries, update all clients to have
2615            // the correct library paths.
2616            updateAllSharedLibrariesLPw();
2617
2618            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2619                // NOTE: We ignore potential failures here during a system scan (like
2620                // the rest of the commands above) because there's precious little we
2621                // can do about it. A settings error is reported, though.
2622                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2623                        false /* boot complete */);
2624            }
2625
2626            // Now that we know all the packages we are keeping,
2627            // read and update their last usage times.
2628            mPackageUsage.readLP();
2629
2630            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2631                    SystemClock.uptimeMillis());
2632            Slog.i(TAG, "Time to scan packages: "
2633                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2634                    + " seconds");
2635
2636            // If the platform SDK has changed since the last time we booted,
2637            // we need to re-grant app permission to catch any new ones that
2638            // appear.  This is really a hack, and means that apps can in some
2639            // cases get permissions that the user didn't initially explicitly
2640            // allow...  it would be nice to have some better way to handle
2641            // this situation.
2642            int updateFlags = UPDATE_PERMISSIONS_ALL;
2643            if (ver.sdkVersion != mSdkVersion) {
2644                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2645                        + mSdkVersion + "; regranting permissions for internal storage");
2646                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2647            }
2648            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2649            ver.sdkVersion = mSdkVersion;
2650
2651            // If this is the first boot or an update from pre-M, and it is a normal
2652            // boot, then we need to initialize the default preferred apps across
2653            // all defined users.
2654            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2655                for (UserInfo user : sUserManager.getUsers(true)) {
2656                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2657                    applyFactoryDefaultBrowserLPw(user.id);
2658                    primeDomainVerificationsLPw(user.id);
2659                }
2660            }
2661
2662            // Prepare storage for system user really early during boot,
2663            // since core system apps like SettingsProvider and SystemUI
2664            // can't wait for user to start
2665            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2666                    StorageManager.FLAG_STORAGE_DE);
2667
2668            // If this is first boot after an OTA, and a normal boot, then
2669            // we need to clear code cache directories.
2670            if (mIsUpgrade && !onlyCore) {
2671                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2672                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2673                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2674                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2675                        // No apps are running this early, so no need to freeze
2676                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2677                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2678                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2679                    }
2680                    clearAppProfilesLIF(ps.pkg);
2681                }
2682                ver.fingerprint = Build.FINGERPRINT;
2683            }
2684
2685            checkDefaultBrowser();
2686
2687            // clear only after permissions and other defaults have been updated
2688            mExistingSystemPackages.clear();
2689            mPromoteSystemApps = false;
2690
2691            // All the changes are done during package scanning.
2692            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2693
2694            // can downgrade to reader
2695            mSettings.writeLPr();
2696
2697            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2698                    SystemClock.uptimeMillis());
2699
2700            if (!mOnlyCore) {
2701                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2702                mRequiredInstallerPackage = getRequiredInstallerLPr();
2703                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2704                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2705                        mIntentFilterVerifierComponent);
2706                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2707                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2708                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2709                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2710            } else {
2711                mRequiredVerifierPackage = null;
2712                mRequiredInstallerPackage = null;
2713                mIntentFilterVerifierComponent = null;
2714                mIntentFilterVerifier = null;
2715                mServicesSystemSharedLibraryPackageName = null;
2716                mSharedSystemSharedLibraryPackageName = null;
2717            }
2718
2719            mInstallerService = new PackageInstallerService(context, this);
2720
2721            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2722            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2723            // both the installer and resolver must be present to enable ephemeral
2724            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2725                if (DEBUG_EPHEMERAL) {
2726                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2727                            + " installer:" + ephemeralInstallerComponent);
2728                }
2729                mEphemeralResolverComponent = ephemeralResolverComponent;
2730                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2731                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2732                mEphemeralResolverConnection =
2733                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2734            } else {
2735                if (DEBUG_EPHEMERAL) {
2736                    final String missingComponent =
2737                            (ephemeralResolverComponent == null)
2738                            ? (ephemeralInstallerComponent == null)
2739                                    ? "resolver and installer"
2740                                    : "resolver"
2741                            : "installer";
2742                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2743                }
2744                mEphemeralResolverComponent = null;
2745                mEphemeralInstallerComponent = null;
2746                mEphemeralResolverConnection = null;
2747            }
2748
2749            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2750        } // synchronized (mPackages)
2751        } // synchronized (mInstallLock)
2752
2753        // Now after opening every single application zip, make sure they
2754        // are all flushed.  Not really needed, but keeps things nice and
2755        // tidy.
2756        Runtime.getRuntime().gc();
2757
2758        // The initial scanning above does many calls into installd while
2759        // holding the mPackages lock, but we're mostly interested in yelling
2760        // once we have a booted system.
2761        mInstaller.setWarnIfHeld(mPackages);
2762
2763        // Expose private service for system components to use.
2764        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2765    }
2766
2767    @Override
2768    public boolean isFirstBoot() {
2769        return !mRestoredSettings;
2770    }
2771
2772    @Override
2773    public boolean isOnlyCoreApps() {
2774        return mOnlyCore;
2775    }
2776
2777    @Override
2778    public boolean isUpgrade() {
2779        return mIsUpgrade;
2780    }
2781
2782    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2783        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2784
2785        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2786                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2787                UserHandle.USER_SYSTEM);
2788        if (matches.size() == 1) {
2789            return matches.get(0).getComponentInfo().packageName;
2790        } else {
2791            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2792            return null;
2793        }
2794    }
2795
2796    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2797        synchronized (mPackages) {
2798            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2799            if (libraryEntry == null) {
2800                throw new IllegalStateException("Missing required shared library:" + libraryName);
2801            }
2802            return libraryEntry.apk;
2803        }
2804    }
2805
2806    private @NonNull String getRequiredInstallerLPr() {
2807        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2808        intent.addCategory(Intent.CATEGORY_DEFAULT);
2809        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2810
2811        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2812                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2813                UserHandle.USER_SYSTEM);
2814        if (matches.size() == 1) {
2815            ResolveInfo resolveInfo = matches.get(0);
2816            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2817                throw new RuntimeException("The installer must be a privileged app");
2818            }
2819            return matches.get(0).getComponentInfo().packageName;
2820        } else {
2821            throw new RuntimeException("There must be exactly one installer; found " + matches);
2822        }
2823    }
2824
2825    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2826        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2827
2828        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2829                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2830                UserHandle.USER_SYSTEM);
2831        ResolveInfo best = null;
2832        final int N = matches.size();
2833        for (int i = 0; i < N; i++) {
2834            final ResolveInfo cur = matches.get(i);
2835            final String packageName = cur.getComponentInfo().packageName;
2836            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2837                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2838                continue;
2839            }
2840
2841            if (best == null || cur.priority > best.priority) {
2842                best = cur;
2843            }
2844        }
2845
2846        if (best != null) {
2847            return best.getComponentInfo().getComponentName();
2848        } else {
2849            throw new RuntimeException("There must be at least one intent filter verifier");
2850        }
2851    }
2852
2853    private @Nullable ComponentName getEphemeralResolverLPr() {
2854        final String[] packageArray =
2855                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2856        if (packageArray.length == 0) {
2857            if (DEBUG_EPHEMERAL) {
2858                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2859            }
2860            return null;
2861        }
2862
2863        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2864        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2865                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2866                UserHandle.USER_SYSTEM);
2867
2868        final int N = resolvers.size();
2869        if (N == 0) {
2870            if (DEBUG_EPHEMERAL) {
2871                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2872            }
2873            return null;
2874        }
2875
2876        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2877        for (int i = 0; i < N; i++) {
2878            final ResolveInfo info = resolvers.get(i);
2879
2880            if (info.serviceInfo == null) {
2881                continue;
2882            }
2883
2884            final String packageName = info.serviceInfo.packageName;
2885            if (!possiblePackages.contains(packageName)) {
2886                if (DEBUG_EPHEMERAL) {
2887                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2888                            + " pkg: " + packageName + ", info:" + info);
2889                }
2890                continue;
2891            }
2892
2893            if (DEBUG_EPHEMERAL) {
2894                Slog.v(TAG, "Ephemeral resolver found;"
2895                        + " pkg: " + packageName + ", info:" + info);
2896            }
2897            return new ComponentName(packageName, info.serviceInfo.name);
2898        }
2899        if (DEBUG_EPHEMERAL) {
2900            Slog.v(TAG, "Ephemeral resolver NOT found");
2901        }
2902        return null;
2903    }
2904
2905    private @Nullable ComponentName getEphemeralInstallerLPr() {
2906        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2907        intent.addCategory(Intent.CATEGORY_DEFAULT);
2908        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2909
2910        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2911                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2912                UserHandle.USER_SYSTEM);
2913        if (matches.size() == 0) {
2914            return null;
2915        } else if (matches.size() == 1) {
2916            return matches.get(0).getComponentInfo().getComponentName();
2917        } else {
2918            throw new RuntimeException(
2919                    "There must be at most one ephemeral installer; found " + matches);
2920        }
2921    }
2922
2923    private void primeDomainVerificationsLPw(int userId) {
2924        if (DEBUG_DOMAIN_VERIFICATION) {
2925            Slog.d(TAG, "Priming domain verifications in user " + userId);
2926        }
2927
2928        SystemConfig systemConfig = SystemConfig.getInstance();
2929        ArraySet<String> packages = systemConfig.getLinkedApps();
2930        ArraySet<String> domains = new ArraySet<String>();
2931
2932        for (String packageName : packages) {
2933            PackageParser.Package pkg = mPackages.get(packageName);
2934            if (pkg != null) {
2935                if (!pkg.isSystemApp()) {
2936                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2937                    continue;
2938                }
2939
2940                domains.clear();
2941                for (PackageParser.Activity a : pkg.activities) {
2942                    for (ActivityIntentInfo filter : a.intents) {
2943                        if (hasValidDomains(filter)) {
2944                            domains.addAll(filter.getHostsList());
2945                        }
2946                    }
2947                }
2948
2949                if (domains.size() > 0) {
2950                    if (DEBUG_DOMAIN_VERIFICATION) {
2951                        Slog.v(TAG, "      + " + packageName);
2952                    }
2953                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2954                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2955                    // and then 'always' in the per-user state actually used for intent resolution.
2956                    final IntentFilterVerificationInfo ivi;
2957                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2958                            new ArrayList<String>(domains));
2959                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2960                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2961                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2962                } else {
2963                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2964                            + "' does not handle web links");
2965                }
2966            } else {
2967                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2968            }
2969        }
2970
2971        scheduleWritePackageRestrictionsLocked(userId);
2972        scheduleWriteSettingsLocked();
2973    }
2974
2975    private void applyFactoryDefaultBrowserLPw(int userId) {
2976        // The default browser app's package name is stored in a string resource,
2977        // with a product-specific overlay used for vendor customization.
2978        String browserPkg = mContext.getResources().getString(
2979                com.android.internal.R.string.default_browser);
2980        if (!TextUtils.isEmpty(browserPkg)) {
2981            // non-empty string => required to be a known package
2982            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2983            if (ps == null) {
2984                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2985                browserPkg = null;
2986            } else {
2987                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2988            }
2989        }
2990
2991        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2992        // default.  If there's more than one, just leave everything alone.
2993        if (browserPkg == null) {
2994            calculateDefaultBrowserLPw(userId);
2995        }
2996    }
2997
2998    private void calculateDefaultBrowserLPw(int userId) {
2999        List<String> allBrowsers = resolveAllBrowserApps(userId);
3000        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3001        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3002    }
3003
3004    private List<String> resolveAllBrowserApps(int userId) {
3005        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3006        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3007                PackageManager.MATCH_ALL, userId);
3008
3009        final int count = list.size();
3010        List<String> result = new ArrayList<String>(count);
3011        for (int i=0; i<count; i++) {
3012            ResolveInfo info = list.get(i);
3013            if (info.activityInfo == null
3014                    || !info.handleAllWebDataURI
3015                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3016                    || result.contains(info.activityInfo.packageName)) {
3017                continue;
3018            }
3019            result.add(info.activityInfo.packageName);
3020        }
3021
3022        return result;
3023    }
3024
3025    private boolean packageIsBrowser(String packageName, int userId) {
3026        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3027                PackageManager.MATCH_ALL, userId);
3028        final int N = list.size();
3029        for (int i = 0; i < N; i++) {
3030            ResolveInfo info = list.get(i);
3031            if (packageName.equals(info.activityInfo.packageName)) {
3032                return true;
3033            }
3034        }
3035        return false;
3036    }
3037
3038    private void checkDefaultBrowser() {
3039        final int myUserId = UserHandle.myUserId();
3040        final String packageName = getDefaultBrowserPackageName(myUserId);
3041        if (packageName != null) {
3042            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3043            if (info == null) {
3044                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3045                synchronized (mPackages) {
3046                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3047                }
3048            }
3049        }
3050    }
3051
3052    @Override
3053    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3054            throws RemoteException {
3055        try {
3056            return super.onTransact(code, data, reply, flags);
3057        } catch (RuntimeException e) {
3058            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3059                Slog.wtf(TAG, "Package Manager Crash", e);
3060            }
3061            throw e;
3062        }
3063    }
3064
3065    static int[] appendInts(int[] cur, int[] add) {
3066        if (add == null) return cur;
3067        if (cur == null) return add;
3068        final int N = add.length;
3069        for (int i=0; i<N; i++) {
3070            cur = appendInt(cur, add[i]);
3071        }
3072        return cur;
3073    }
3074
3075    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3076        if (!sUserManager.exists(userId)) return null;
3077        if (ps == null) {
3078            return null;
3079        }
3080        final PackageParser.Package p = ps.pkg;
3081        if (p == null) {
3082            return null;
3083        }
3084
3085        final PermissionsState permissionsState = ps.getPermissionsState();
3086
3087        final int[] gids = permissionsState.computeGids(userId);
3088        final Set<String> permissions = permissionsState.getPermissions(userId);
3089        final PackageUserState state = ps.readUserState(userId);
3090
3091        return PackageParser.generatePackageInfo(p, gids, flags,
3092                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3093    }
3094
3095    @Override
3096    public void checkPackageStartable(String packageName, int userId) {
3097        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3098
3099        synchronized (mPackages) {
3100            final PackageSetting ps = mSettings.mPackages.get(packageName);
3101            if (ps == null) {
3102                throw new SecurityException("Package " + packageName + " was not found!");
3103            }
3104
3105            if (!ps.getInstalled(userId)) {
3106                throw new SecurityException(
3107                        "Package " + packageName + " was not installed for user " + userId + "!");
3108            }
3109
3110            if (mSafeMode && !ps.isSystem()) {
3111                throw new SecurityException("Package " + packageName + " not a system app!");
3112            }
3113
3114            if (mFrozenPackages.contains(packageName)) {
3115                throw new SecurityException("Package " + packageName + " is currently frozen!");
3116            }
3117
3118            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3119                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3120                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3121            }
3122        }
3123    }
3124
3125    @Override
3126    public boolean isPackageAvailable(String packageName, int userId) {
3127        if (!sUserManager.exists(userId)) return false;
3128        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3129                false /* requireFullPermission */, false /* checkShell */, "is package available");
3130        synchronized (mPackages) {
3131            PackageParser.Package p = mPackages.get(packageName);
3132            if (p != null) {
3133                final PackageSetting ps = (PackageSetting) p.mExtras;
3134                if (ps != null) {
3135                    final PackageUserState state = ps.readUserState(userId);
3136                    if (state != null) {
3137                        return PackageParser.isAvailable(state);
3138                    }
3139                }
3140            }
3141        }
3142        return false;
3143    }
3144
3145    @Override
3146    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3147        if (!sUserManager.exists(userId)) return null;
3148        flags = updateFlagsForPackage(flags, userId, packageName);
3149        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3150                false /* requireFullPermission */, false /* checkShell */, "get package info");
3151        // reader
3152        synchronized (mPackages) {
3153            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3154            PackageParser.Package p = null;
3155            if (matchFactoryOnly) {
3156                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3157                if (ps != null) {
3158                    return generatePackageInfo(ps, flags, userId);
3159                }
3160            }
3161            if (p == null) {
3162                p = mPackages.get(packageName);
3163                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3164                    return null;
3165                }
3166            }
3167            if (DEBUG_PACKAGE_INFO)
3168                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3169            if (p != null) {
3170                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3171            }
3172            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3173                final PackageSetting ps = mSettings.mPackages.get(packageName);
3174                return generatePackageInfo(ps, flags, userId);
3175            }
3176        }
3177        return null;
3178    }
3179
3180    @Override
3181    public String[] currentToCanonicalPackageNames(String[] names) {
3182        String[] out = new String[names.length];
3183        // reader
3184        synchronized (mPackages) {
3185            for (int i=names.length-1; i>=0; i--) {
3186                PackageSetting ps = mSettings.mPackages.get(names[i]);
3187                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3188            }
3189        }
3190        return out;
3191    }
3192
3193    @Override
3194    public String[] canonicalToCurrentPackageNames(String[] names) {
3195        String[] out = new String[names.length];
3196        // reader
3197        synchronized (mPackages) {
3198            for (int i=names.length-1; i>=0; i--) {
3199                String cur = mSettings.mRenamedPackages.get(names[i]);
3200                out[i] = cur != null ? cur : names[i];
3201            }
3202        }
3203        return out;
3204    }
3205
3206    @Override
3207    public int getPackageUid(String packageName, int flags, int userId) {
3208        if (!sUserManager.exists(userId)) return -1;
3209        flags = updateFlagsForPackage(flags, userId, packageName);
3210        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3211                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3212
3213        // reader
3214        synchronized (mPackages) {
3215            final PackageParser.Package p = mPackages.get(packageName);
3216            if (p != null && p.isMatch(flags)) {
3217                return UserHandle.getUid(userId, p.applicationInfo.uid);
3218            }
3219            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3220                final PackageSetting ps = mSettings.mPackages.get(packageName);
3221                if (ps != null && ps.isMatch(flags)) {
3222                    return UserHandle.getUid(userId, ps.appId);
3223                }
3224            }
3225        }
3226
3227        return -1;
3228    }
3229
3230    @Override
3231    public int[] getPackageGids(String packageName, int flags, int userId) {
3232        if (!sUserManager.exists(userId)) return null;
3233        flags = updateFlagsForPackage(flags, userId, packageName);
3234        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3235                false /* requireFullPermission */, false /* checkShell */,
3236                "getPackageGids");
3237
3238        // reader
3239        synchronized (mPackages) {
3240            final PackageParser.Package p = mPackages.get(packageName);
3241            if (p != null && p.isMatch(flags)) {
3242                PackageSetting ps = (PackageSetting) p.mExtras;
3243                return ps.getPermissionsState().computeGids(userId);
3244            }
3245            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3246                final PackageSetting ps = mSettings.mPackages.get(packageName);
3247                if (ps != null && ps.isMatch(flags)) {
3248                    return ps.getPermissionsState().computeGids(userId);
3249                }
3250            }
3251        }
3252
3253        return null;
3254    }
3255
3256    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3257        if (bp.perm != null) {
3258            return PackageParser.generatePermissionInfo(bp.perm, flags);
3259        }
3260        PermissionInfo pi = new PermissionInfo();
3261        pi.name = bp.name;
3262        pi.packageName = bp.sourcePackage;
3263        pi.nonLocalizedLabel = bp.name;
3264        pi.protectionLevel = bp.protectionLevel;
3265        return pi;
3266    }
3267
3268    @Override
3269    public PermissionInfo getPermissionInfo(String name, int flags) {
3270        // reader
3271        synchronized (mPackages) {
3272            final BasePermission p = mSettings.mPermissions.get(name);
3273            if (p != null) {
3274                return generatePermissionInfo(p, flags);
3275            }
3276            return null;
3277        }
3278    }
3279
3280    @Override
3281    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3282            int flags) {
3283        // reader
3284        synchronized (mPackages) {
3285            if (group != null && !mPermissionGroups.containsKey(group)) {
3286                // This is thrown as NameNotFoundException
3287                return null;
3288            }
3289
3290            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3291            for (BasePermission p : mSettings.mPermissions.values()) {
3292                if (group == null) {
3293                    if (p.perm == null || p.perm.info.group == null) {
3294                        out.add(generatePermissionInfo(p, flags));
3295                    }
3296                } else {
3297                    if (p.perm != null && group.equals(p.perm.info.group)) {
3298                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3299                    }
3300                }
3301            }
3302            return new ParceledListSlice<>(out);
3303        }
3304    }
3305
3306    @Override
3307    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3308        // reader
3309        synchronized (mPackages) {
3310            return PackageParser.generatePermissionGroupInfo(
3311                    mPermissionGroups.get(name), flags);
3312        }
3313    }
3314
3315    @Override
3316    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3317        // reader
3318        synchronized (mPackages) {
3319            final int N = mPermissionGroups.size();
3320            ArrayList<PermissionGroupInfo> out
3321                    = new ArrayList<PermissionGroupInfo>(N);
3322            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3323                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3324            }
3325            return new ParceledListSlice<>(out);
3326        }
3327    }
3328
3329    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3330            int userId) {
3331        if (!sUserManager.exists(userId)) return null;
3332        PackageSetting ps = mSettings.mPackages.get(packageName);
3333        if (ps != null) {
3334            if (ps.pkg == null) {
3335                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3336                if (pInfo != null) {
3337                    return pInfo.applicationInfo;
3338                }
3339                return null;
3340            }
3341            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3342                    ps.readUserState(userId), userId);
3343        }
3344        return null;
3345    }
3346
3347    @Override
3348    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3349        if (!sUserManager.exists(userId)) return null;
3350        flags = updateFlagsForApplication(flags, userId, packageName);
3351        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3352                false /* requireFullPermission */, false /* checkShell */, "get application info");
3353        // writer
3354        synchronized (mPackages) {
3355            PackageParser.Package p = mPackages.get(packageName);
3356            if (DEBUG_PACKAGE_INFO) Log.v(
3357                    TAG, "getApplicationInfo " + packageName
3358                    + ": " + p);
3359            if (p != null) {
3360                PackageSetting ps = mSettings.mPackages.get(packageName);
3361                if (ps == null) return null;
3362                // Note: isEnabledLP() does not apply here - always return info
3363                return PackageParser.generateApplicationInfo(
3364                        p, flags, ps.readUserState(userId), userId);
3365            }
3366            if ("android".equals(packageName)||"system".equals(packageName)) {
3367                return mAndroidApplication;
3368            }
3369            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3370                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3371            }
3372        }
3373        return null;
3374    }
3375
3376    @Override
3377    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3378            final IPackageDataObserver observer) {
3379        mContext.enforceCallingOrSelfPermission(
3380                android.Manifest.permission.CLEAR_APP_CACHE, null);
3381        // Queue up an async operation since clearing cache may take a little while.
3382        mHandler.post(new Runnable() {
3383            public void run() {
3384                mHandler.removeCallbacks(this);
3385                boolean success = true;
3386                synchronized (mInstallLock) {
3387                    try {
3388                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3389                    } catch (InstallerException e) {
3390                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3391                        success = false;
3392                    }
3393                }
3394                if (observer != null) {
3395                    try {
3396                        observer.onRemoveCompleted(null, success);
3397                    } catch (RemoteException e) {
3398                        Slog.w(TAG, "RemoveException when invoking call back");
3399                    }
3400                }
3401            }
3402        });
3403    }
3404
3405    @Override
3406    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3407            final IntentSender pi) {
3408        mContext.enforceCallingOrSelfPermission(
3409                android.Manifest.permission.CLEAR_APP_CACHE, null);
3410        // Queue up an async operation since clearing cache may take a little while.
3411        mHandler.post(new Runnable() {
3412            public void run() {
3413                mHandler.removeCallbacks(this);
3414                boolean success = true;
3415                synchronized (mInstallLock) {
3416                    try {
3417                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3418                    } catch (InstallerException e) {
3419                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3420                        success = false;
3421                    }
3422                }
3423                if(pi != null) {
3424                    try {
3425                        // Callback via pending intent
3426                        int code = success ? 1 : 0;
3427                        pi.sendIntent(null, code, null,
3428                                null, null);
3429                    } catch (SendIntentException e1) {
3430                        Slog.i(TAG, "Failed to send pending intent");
3431                    }
3432                }
3433            }
3434        });
3435    }
3436
3437    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3438        synchronized (mInstallLock) {
3439            try {
3440                mInstaller.freeCache(volumeUuid, freeStorageSize);
3441            } catch (InstallerException e) {
3442                throw new IOException("Failed to free enough space", e);
3443            }
3444        }
3445    }
3446
3447    /**
3448     * Update given flags based on encryption status of current user.
3449     */
3450    private int updateFlags(int flags, int userId) {
3451        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3452                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3453            // Caller expressed an explicit opinion about what encryption
3454            // aware/unaware components they want to see, so fall through and
3455            // give them what they want
3456        } else {
3457            // Caller expressed no opinion, so match based on user state
3458            if (StorageManager.isUserKeyUnlocked(userId)) {
3459                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3460            } else {
3461                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3462            }
3463        }
3464        return flags;
3465    }
3466
3467    /**
3468     * Update given flags when being used to request {@link PackageInfo}.
3469     */
3470    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3471        boolean triaged = true;
3472        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3473                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3474            // Caller is asking for component details, so they'd better be
3475            // asking for specific encryption matching behavior, or be triaged
3476            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3477                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3478                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3479                triaged = false;
3480            }
3481        }
3482        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3483                | PackageManager.MATCH_SYSTEM_ONLY
3484                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3485            triaged = false;
3486        }
3487        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3488            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3489                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3490        }
3491        return updateFlags(flags, userId);
3492    }
3493
3494    /**
3495     * Update given flags when being used to request {@link ApplicationInfo}.
3496     */
3497    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3498        return updateFlagsForPackage(flags, userId, cookie);
3499    }
3500
3501    /**
3502     * Update given flags when being used to request {@link ComponentInfo}.
3503     */
3504    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3505        if (cookie instanceof Intent) {
3506            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3507                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3508            }
3509        }
3510
3511        boolean triaged = true;
3512        // Caller is asking for component details, so they'd better be
3513        // asking for specific encryption matching behavior, or be triaged
3514        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3515                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3516                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3517            triaged = false;
3518        }
3519        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3520            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3521                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3522        }
3523
3524        return updateFlags(flags, userId);
3525    }
3526
3527    /**
3528     * Update given flags when being used to request {@link ResolveInfo}.
3529     */
3530    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3531        // Safe mode means we shouldn't match any third-party components
3532        if (mSafeMode) {
3533            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3534        }
3535
3536        return updateFlagsForComponent(flags, userId, cookie);
3537    }
3538
3539    @Override
3540    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3541        if (!sUserManager.exists(userId)) return null;
3542        flags = updateFlagsForComponent(flags, userId, component);
3543        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3544                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3545        synchronized (mPackages) {
3546            PackageParser.Activity a = mActivities.mActivities.get(component);
3547
3548            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3549            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3550                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3551                if (ps == null) return null;
3552                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3553                        userId);
3554            }
3555            if (mResolveComponentName.equals(component)) {
3556                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3557                        new PackageUserState(), userId);
3558            }
3559        }
3560        return null;
3561    }
3562
3563    @Override
3564    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3565            String resolvedType) {
3566        synchronized (mPackages) {
3567            if (component.equals(mResolveComponentName)) {
3568                // The resolver supports EVERYTHING!
3569                return true;
3570            }
3571            PackageParser.Activity a = mActivities.mActivities.get(component);
3572            if (a == null) {
3573                return false;
3574            }
3575            for (int i=0; i<a.intents.size(); i++) {
3576                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3577                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3578                    return true;
3579                }
3580            }
3581            return false;
3582        }
3583    }
3584
3585    @Override
3586    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3587        if (!sUserManager.exists(userId)) return null;
3588        flags = updateFlagsForComponent(flags, userId, component);
3589        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3590                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3591        synchronized (mPackages) {
3592            PackageParser.Activity a = mReceivers.mActivities.get(component);
3593            if (DEBUG_PACKAGE_INFO) Log.v(
3594                TAG, "getReceiverInfo " + component + ": " + a);
3595            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3596                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3597                if (ps == null) return null;
3598                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3599                        userId);
3600            }
3601        }
3602        return null;
3603    }
3604
3605    @Override
3606    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3607        if (!sUserManager.exists(userId)) return null;
3608        flags = updateFlagsForComponent(flags, userId, component);
3609        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3610                false /* requireFullPermission */, false /* checkShell */, "get service info");
3611        synchronized (mPackages) {
3612            PackageParser.Service s = mServices.mServices.get(component);
3613            if (DEBUG_PACKAGE_INFO) Log.v(
3614                TAG, "getServiceInfo " + component + ": " + s);
3615            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3616                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3617                if (ps == null) return null;
3618                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3619                        userId);
3620            }
3621        }
3622        return null;
3623    }
3624
3625    @Override
3626    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3627        if (!sUserManager.exists(userId)) return null;
3628        flags = updateFlagsForComponent(flags, userId, component);
3629        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3630                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3631        synchronized (mPackages) {
3632            PackageParser.Provider p = mProviders.mProviders.get(component);
3633            if (DEBUG_PACKAGE_INFO) Log.v(
3634                TAG, "getProviderInfo " + component + ": " + p);
3635            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3636                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3637                if (ps == null) return null;
3638                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3639                        userId);
3640            }
3641        }
3642        return null;
3643    }
3644
3645    @Override
3646    public String[] getSystemSharedLibraryNames() {
3647        Set<String> libSet;
3648        synchronized (mPackages) {
3649            libSet = mSharedLibraries.keySet();
3650            int size = libSet.size();
3651            if (size > 0) {
3652                String[] libs = new String[size];
3653                libSet.toArray(libs);
3654                return libs;
3655            }
3656        }
3657        return null;
3658    }
3659
3660    @Override
3661    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3662        synchronized (mPackages) {
3663            return mServicesSystemSharedLibraryPackageName;
3664        }
3665    }
3666
3667    @Override
3668    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3669        synchronized (mPackages) {
3670            return mSharedSystemSharedLibraryPackageName;
3671        }
3672    }
3673
3674    @Override
3675    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3676        synchronized (mPackages) {
3677            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3678
3679            final FeatureInfo fi = new FeatureInfo();
3680            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3681                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3682            res.add(fi);
3683
3684            return new ParceledListSlice<>(res);
3685        }
3686    }
3687
3688    @Override
3689    public boolean hasSystemFeature(String name, int version) {
3690        synchronized (mPackages) {
3691            final FeatureInfo feat = mAvailableFeatures.get(name);
3692            if (feat == null) {
3693                return false;
3694            } else {
3695                return feat.version >= version;
3696            }
3697        }
3698    }
3699
3700    @Override
3701    public int checkPermission(String permName, String pkgName, int userId) {
3702        if (!sUserManager.exists(userId)) {
3703            return PackageManager.PERMISSION_DENIED;
3704        }
3705
3706        synchronized (mPackages) {
3707            final PackageParser.Package p = mPackages.get(pkgName);
3708            if (p != null && p.mExtras != null) {
3709                final PackageSetting ps = (PackageSetting) p.mExtras;
3710                final PermissionsState permissionsState = ps.getPermissionsState();
3711                if (permissionsState.hasPermission(permName, userId)) {
3712                    return PackageManager.PERMISSION_GRANTED;
3713                }
3714                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3715                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3716                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3717                    return PackageManager.PERMISSION_GRANTED;
3718                }
3719            }
3720        }
3721
3722        return PackageManager.PERMISSION_DENIED;
3723    }
3724
3725    @Override
3726    public int checkUidPermission(String permName, int uid) {
3727        final int userId = UserHandle.getUserId(uid);
3728
3729        if (!sUserManager.exists(userId)) {
3730            return PackageManager.PERMISSION_DENIED;
3731        }
3732
3733        synchronized (mPackages) {
3734            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3735            if (obj != null) {
3736                final SettingBase ps = (SettingBase) obj;
3737                final PermissionsState permissionsState = ps.getPermissionsState();
3738                if (permissionsState.hasPermission(permName, userId)) {
3739                    return PackageManager.PERMISSION_GRANTED;
3740                }
3741                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3742                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3743                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3744                    return PackageManager.PERMISSION_GRANTED;
3745                }
3746            } else {
3747                ArraySet<String> perms = mSystemPermissions.get(uid);
3748                if (perms != null) {
3749                    if (perms.contains(permName)) {
3750                        return PackageManager.PERMISSION_GRANTED;
3751                    }
3752                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3753                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3754                        return PackageManager.PERMISSION_GRANTED;
3755                    }
3756                }
3757            }
3758        }
3759
3760        return PackageManager.PERMISSION_DENIED;
3761    }
3762
3763    @Override
3764    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3765        if (UserHandle.getCallingUserId() != userId) {
3766            mContext.enforceCallingPermission(
3767                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3768                    "isPermissionRevokedByPolicy for user " + userId);
3769        }
3770
3771        if (checkPermission(permission, packageName, userId)
3772                == PackageManager.PERMISSION_GRANTED) {
3773            return false;
3774        }
3775
3776        final long identity = Binder.clearCallingIdentity();
3777        try {
3778            final int flags = getPermissionFlags(permission, packageName, userId);
3779            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3780        } finally {
3781            Binder.restoreCallingIdentity(identity);
3782        }
3783    }
3784
3785    @Override
3786    public String getPermissionControllerPackageName() {
3787        synchronized (mPackages) {
3788            return mRequiredInstallerPackage;
3789        }
3790    }
3791
3792    /**
3793     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3794     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3795     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3796     * @param message the message to log on security exception
3797     */
3798    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3799            boolean checkShell, String message) {
3800        if (userId < 0) {
3801            throw new IllegalArgumentException("Invalid userId " + userId);
3802        }
3803        if (checkShell) {
3804            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3805        }
3806        if (userId == UserHandle.getUserId(callingUid)) return;
3807        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3808            if (requireFullPermission) {
3809                mContext.enforceCallingOrSelfPermission(
3810                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3811            } else {
3812                try {
3813                    mContext.enforceCallingOrSelfPermission(
3814                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3815                } catch (SecurityException se) {
3816                    mContext.enforceCallingOrSelfPermission(
3817                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3818                }
3819            }
3820        }
3821    }
3822
3823    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3824        if (callingUid == Process.SHELL_UID) {
3825            if (userHandle >= 0
3826                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3827                throw new SecurityException("Shell does not have permission to access user "
3828                        + userHandle);
3829            } else if (userHandle < 0) {
3830                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3831                        + Debug.getCallers(3));
3832            }
3833        }
3834    }
3835
3836    private BasePermission findPermissionTreeLP(String permName) {
3837        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3838            if (permName.startsWith(bp.name) &&
3839                    permName.length() > bp.name.length() &&
3840                    permName.charAt(bp.name.length()) == '.') {
3841                return bp;
3842            }
3843        }
3844        return null;
3845    }
3846
3847    private BasePermission checkPermissionTreeLP(String permName) {
3848        if (permName != null) {
3849            BasePermission bp = findPermissionTreeLP(permName);
3850            if (bp != null) {
3851                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3852                    return bp;
3853                }
3854                throw new SecurityException("Calling uid "
3855                        + Binder.getCallingUid()
3856                        + " is not allowed to add to permission tree "
3857                        + bp.name + " owned by uid " + bp.uid);
3858            }
3859        }
3860        throw new SecurityException("No permission tree found for " + permName);
3861    }
3862
3863    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3864        if (s1 == null) {
3865            return s2 == null;
3866        }
3867        if (s2 == null) {
3868            return false;
3869        }
3870        if (s1.getClass() != s2.getClass()) {
3871            return false;
3872        }
3873        return s1.equals(s2);
3874    }
3875
3876    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3877        if (pi1.icon != pi2.icon) return false;
3878        if (pi1.logo != pi2.logo) return false;
3879        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3880        if (!compareStrings(pi1.name, pi2.name)) return false;
3881        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3882        // We'll take care of setting this one.
3883        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3884        // These are not currently stored in settings.
3885        //if (!compareStrings(pi1.group, pi2.group)) return false;
3886        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3887        //if (pi1.labelRes != pi2.labelRes) return false;
3888        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3889        return true;
3890    }
3891
3892    int permissionInfoFootprint(PermissionInfo info) {
3893        int size = info.name.length();
3894        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3895        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3896        return size;
3897    }
3898
3899    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3900        int size = 0;
3901        for (BasePermission perm : mSettings.mPermissions.values()) {
3902            if (perm.uid == tree.uid) {
3903                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3904            }
3905        }
3906        return size;
3907    }
3908
3909    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3910        // We calculate the max size of permissions defined by this uid and throw
3911        // if that plus the size of 'info' would exceed our stated maximum.
3912        if (tree.uid != Process.SYSTEM_UID) {
3913            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3914            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3915                throw new SecurityException("Permission tree size cap exceeded");
3916            }
3917        }
3918    }
3919
3920    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3921        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3922            throw new SecurityException("Label must be specified in permission");
3923        }
3924        BasePermission tree = checkPermissionTreeLP(info.name);
3925        BasePermission bp = mSettings.mPermissions.get(info.name);
3926        boolean added = bp == null;
3927        boolean changed = true;
3928        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3929        if (added) {
3930            enforcePermissionCapLocked(info, tree);
3931            bp = new BasePermission(info.name, tree.sourcePackage,
3932                    BasePermission.TYPE_DYNAMIC);
3933        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3934            throw new SecurityException(
3935                    "Not allowed to modify non-dynamic permission "
3936                    + info.name);
3937        } else {
3938            if (bp.protectionLevel == fixedLevel
3939                    && bp.perm.owner.equals(tree.perm.owner)
3940                    && bp.uid == tree.uid
3941                    && comparePermissionInfos(bp.perm.info, info)) {
3942                changed = false;
3943            }
3944        }
3945        bp.protectionLevel = fixedLevel;
3946        info = new PermissionInfo(info);
3947        info.protectionLevel = fixedLevel;
3948        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3949        bp.perm.info.packageName = tree.perm.info.packageName;
3950        bp.uid = tree.uid;
3951        if (added) {
3952            mSettings.mPermissions.put(info.name, bp);
3953        }
3954        if (changed) {
3955            if (!async) {
3956                mSettings.writeLPr();
3957            } else {
3958                scheduleWriteSettingsLocked();
3959            }
3960        }
3961        return added;
3962    }
3963
3964    @Override
3965    public boolean addPermission(PermissionInfo info) {
3966        synchronized (mPackages) {
3967            return addPermissionLocked(info, false);
3968        }
3969    }
3970
3971    @Override
3972    public boolean addPermissionAsync(PermissionInfo info) {
3973        synchronized (mPackages) {
3974            return addPermissionLocked(info, true);
3975        }
3976    }
3977
3978    @Override
3979    public void removePermission(String name) {
3980        synchronized (mPackages) {
3981            checkPermissionTreeLP(name);
3982            BasePermission bp = mSettings.mPermissions.get(name);
3983            if (bp != null) {
3984                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3985                    throw new SecurityException(
3986                            "Not allowed to modify non-dynamic permission "
3987                            + name);
3988                }
3989                mSettings.mPermissions.remove(name);
3990                mSettings.writeLPr();
3991            }
3992        }
3993    }
3994
3995    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3996            BasePermission bp) {
3997        int index = pkg.requestedPermissions.indexOf(bp.name);
3998        if (index == -1) {
3999            throw new SecurityException("Package " + pkg.packageName
4000                    + " has not requested permission " + bp.name);
4001        }
4002        if (!bp.isRuntime() && !bp.isDevelopment()) {
4003            throw new SecurityException("Permission " + bp.name
4004                    + " is not a changeable permission type");
4005        }
4006    }
4007
4008    @Override
4009    public void grantRuntimePermission(String packageName, String name, final int userId) {
4010        if (!sUserManager.exists(userId)) {
4011            Log.e(TAG, "No such user:" + userId);
4012            return;
4013        }
4014
4015        mContext.enforceCallingOrSelfPermission(
4016                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4017                "grantRuntimePermission");
4018
4019        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4020                true /* requireFullPermission */, true /* checkShell */,
4021                "grantRuntimePermission");
4022
4023        final int uid;
4024        final SettingBase sb;
4025
4026        synchronized (mPackages) {
4027            final PackageParser.Package pkg = mPackages.get(packageName);
4028            if (pkg == null) {
4029                throw new IllegalArgumentException("Unknown package: " + packageName);
4030            }
4031
4032            final BasePermission bp = mSettings.mPermissions.get(name);
4033            if (bp == null) {
4034                throw new IllegalArgumentException("Unknown permission: " + name);
4035            }
4036
4037            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4038
4039            // If a permission review is required for legacy apps we represent
4040            // their permissions as always granted runtime ones since we need
4041            // to keep the review required permission flag per user while an
4042            // install permission's state is shared across all users.
4043            if (Build.PERMISSIONS_REVIEW_REQUIRED
4044                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4045                    && bp.isRuntime()) {
4046                return;
4047            }
4048
4049            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4050            sb = (SettingBase) pkg.mExtras;
4051            if (sb == null) {
4052                throw new IllegalArgumentException("Unknown package: " + packageName);
4053            }
4054
4055            final PermissionsState permissionsState = sb.getPermissionsState();
4056
4057            final int flags = permissionsState.getPermissionFlags(name, userId);
4058            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4059                throw new SecurityException("Cannot grant system fixed permission "
4060                        + name + " for package " + packageName);
4061            }
4062
4063            if (bp.isDevelopment()) {
4064                // Development permissions must be handled specially, since they are not
4065                // normal runtime permissions.  For now they apply to all users.
4066                if (permissionsState.grantInstallPermission(bp) !=
4067                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4068                    scheduleWriteSettingsLocked();
4069                }
4070                return;
4071            }
4072
4073            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4074                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4075                return;
4076            }
4077
4078            final int result = permissionsState.grantRuntimePermission(bp, userId);
4079            switch (result) {
4080                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4081                    return;
4082                }
4083
4084                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4085                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4086                    mHandler.post(new Runnable() {
4087                        @Override
4088                        public void run() {
4089                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4090                        }
4091                    });
4092                }
4093                break;
4094            }
4095
4096            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4097
4098            // Not critical if that is lost - app has to request again.
4099            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4100        }
4101
4102        // Only need to do this if user is initialized. Otherwise it's a new user
4103        // and there are no processes running as the user yet and there's no need
4104        // to make an expensive call to remount processes for the changed permissions.
4105        if (READ_EXTERNAL_STORAGE.equals(name)
4106                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4107            final long token = Binder.clearCallingIdentity();
4108            try {
4109                if (sUserManager.isInitialized(userId)) {
4110                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4111                            MountServiceInternal.class);
4112                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4113                }
4114            } finally {
4115                Binder.restoreCallingIdentity(token);
4116            }
4117        }
4118    }
4119
4120    @Override
4121    public void revokeRuntimePermission(String packageName, String name, int userId) {
4122        if (!sUserManager.exists(userId)) {
4123            Log.e(TAG, "No such user:" + userId);
4124            return;
4125        }
4126
4127        mContext.enforceCallingOrSelfPermission(
4128                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4129                "revokeRuntimePermission");
4130
4131        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4132                true /* requireFullPermission */, true /* checkShell */,
4133                "revokeRuntimePermission");
4134
4135        final int appId;
4136
4137        synchronized (mPackages) {
4138            final PackageParser.Package pkg = mPackages.get(packageName);
4139            if (pkg == null) {
4140                throw new IllegalArgumentException("Unknown package: " + packageName);
4141            }
4142
4143            final BasePermission bp = mSettings.mPermissions.get(name);
4144            if (bp == null) {
4145                throw new IllegalArgumentException("Unknown permission: " + name);
4146            }
4147
4148            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4149
4150            // If a permission review is required for legacy apps we represent
4151            // their permissions as always granted runtime ones since we need
4152            // to keep the review required permission flag per user while an
4153            // install permission's state is shared across all users.
4154            if (Build.PERMISSIONS_REVIEW_REQUIRED
4155                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4156                    && bp.isRuntime()) {
4157                return;
4158            }
4159
4160            SettingBase sb = (SettingBase) pkg.mExtras;
4161            if (sb == null) {
4162                throw new IllegalArgumentException("Unknown package: " + packageName);
4163            }
4164
4165            final PermissionsState permissionsState = sb.getPermissionsState();
4166
4167            final int flags = permissionsState.getPermissionFlags(name, userId);
4168            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4169                throw new SecurityException("Cannot revoke system fixed permission "
4170                        + name + " for package " + packageName);
4171            }
4172
4173            if (bp.isDevelopment()) {
4174                // Development permissions must be handled specially, since they are not
4175                // normal runtime permissions.  For now they apply to all users.
4176                if (permissionsState.revokeInstallPermission(bp) !=
4177                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4178                    scheduleWriteSettingsLocked();
4179                }
4180                return;
4181            }
4182
4183            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4184                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4185                return;
4186            }
4187
4188            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4189
4190            // Critical, after this call app should never have the permission.
4191            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4192
4193            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4194        }
4195
4196        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4197    }
4198
4199    @Override
4200    public void resetRuntimePermissions() {
4201        mContext.enforceCallingOrSelfPermission(
4202                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4203                "revokeRuntimePermission");
4204
4205        int callingUid = Binder.getCallingUid();
4206        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4207            mContext.enforceCallingOrSelfPermission(
4208                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4209                    "resetRuntimePermissions");
4210        }
4211
4212        synchronized (mPackages) {
4213            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4214            for (int userId : UserManagerService.getInstance().getUserIds()) {
4215                final int packageCount = mPackages.size();
4216                for (int i = 0; i < packageCount; i++) {
4217                    PackageParser.Package pkg = mPackages.valueAt(i);
4218                    if (!(pkg.mExtras instanceof PackageSetting)) {
4219                        continue;
4220                    }
4221                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4222                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4223                }
4224            }
4225        }
4226    }
4227
4228    @Override
4229    public int getPermissionFlags(String name, String packageName, int userId) {
4230        if (!sUserManager.exists(userId)) {
4231            return 0;
4232        }
4233
4234        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4235
4236        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4237                true /* requireFullPermission */, false /* checkShell */,
4238                "getPermissionFlags");
4239
4240        synchronized (mPackages) {
4241            final PackageParser.Package pkg = mPackages.get(packageName);
4242            if (pkg == null) {
4243                throw new IllegalArgumentException("Unknown package: " + packageName);
4244            }
4245
4246            final BasePermission bp = mSettings.mPermissions.get(name);
4247            if (bp == null) {
4248                throw new IllegalArgumentException("Unknown permission: " + name);
4249            }
4250
4251            SettingBase sb = (SettingBase) pkg.mExtras;
4252            if (sb == null) {
4253                throw new IllegalArgumentException("Unknown package: " + packageName);
4254            }
4255
4256            PermissionsState permissionsState = sb.getPermissionsState();
4257            return permissionsState.getPermissionFlags(name, userId);
4258        }
4259    }
4260
4261    @Override
4262    public void updatePermissionFlags(String name, String packageName, int flagMask,
4263            int flagValues, int userId) {
4264        if (!sUserManager.exists(userId)) {
4265            return;
4266        }
4267
4268        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4269
4270        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4271                true /* requireFullPermission */, true /* checkShell */,
4272                "updatePermissionFlags");
4273
4274        // Only the system can change these flags and nothing else.
4275        if (getCallingUid() != Process.SYSTEM_UID) {
4276            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4277            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4278            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4279            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4280            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4281        }
4282
4283        synchronized (mPackages) {
4284            final PackageParser.Package pkg = mPackages.get(packageName);
4285            if (pkg == null) {
4286                throw new IllegalArgumentException("Unknown package: " + packageName);
4287            }
4288
4289            final BasePermission bp = mSettings.mPermissions.get(name);
4290            if (bp == null) {
4291                throw new IllegalArgumentException("Unknown permission: " + name);
4292            }
4293
4294            SettingBase sb = (SettingBase) pkg.mExtras;
4295            if (sb == null) {
4296                throw new IllegalArgumentException("Unknown package: " + packageName);
4297            }
4298
4299            PermissionsState permissionsState = sb.getPermissionsState();
4300
4301            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4302
4303            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4304                // Install and runtime permissions are stored in different places,
4305                // so figure out what permission changed and persist the change.
4306                if (permissionsState.getInstallPermissionState(name) != null) {
4307                    scheduleWriteSettingsLocked();
4308                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4309                        || hadState) {
4310                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4311                }
4312            }
4313        }
4314    }
4315
4316    /**
4317     * Update the permission flags for all packages and runtime permissions of a user in order
4318     * to allow device or profile owner to remove POLICY_FIXED.
4319     */
4320    @Override
4321    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4322        if (!sUserManager.exists(userId)) {
4323            return;
4324        }
4325
4326        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4327
4328        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4329                true /* requireFullPermission */, true /* checkShell */,
4330                "updatePermissionFlagsForAllApps");
4331
4332        // Only the system can change system fixed flags.
4333        if (getCallingUid() != Process.SYSTEM_UID) {
4334            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4335            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4336        }
4337
4338        synchronized (mPackages) {
4339            boolean changed = false;
4340            final int packageCount = mPackages.size();
4341            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4342                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4343                SettingBase sb = (SettingBase) pkg.mExtras;
4344                if (sb == null) {
4345                    continue;
4346                }
4347                PermissionsState permissionsState = sb.getPermissionsState();
4348                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4349                        userId, flagMask, flagValues);
4350            }
4351            if (changed) {
4352                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4353            }
4354        }
4355    }
4356
4357    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4358        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4359                != PackageManager.PERMISSION_GRANTED
4360            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4361                != PackageManager.PERMISSION_GRANTED) {
4362            throw new SecurityException(message + " requires "
4363                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4364                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4365        }
4366    }
4367
4368    @Override
4369    public boolean shouldShowRequestPermissionRationale(String permissionName,
4370            String packageName, int userId) {
4371        if (UserHandle.getCallingUserId() != userId) {
4372            mContext.enforceCallingPermission(
4373                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4374                    "canShowRequestPermissionRationale for user " + userId);
4375        }
4376
4377        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4378        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4379            return false;
4380        }
4381
4382        if (checkPermission(permissionName, packageName, userId)
4383                == PackageManager.PERMISSION_GRANTED) {
4384            return false;
4385        }
4386
4387        final int flags;
4388
4389        final long identity = Binder.clearCallingIdentity();
4390        try {
4391            flags = getPermissionFlags(permissionName,
4392                    packageName, userId);
4393        } finally {
4394            Binder.restoreCallingIdentity(identity);
4395        }
4396
4397        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4398                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4399                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4400
4401        if ((flags & fixedFlags) != 0) {
4402            return false;
4403        }
4404
4405        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4406    }
4407
4408    @Override
4409    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4410        mContext.enforceCallingOrSelfPermission(
4411                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4412                "addOnPermissionsChangeListener");
4413
4414        synchronized (mPackages) {
4415            mOnPermissionChangeListeners.addListenerLocked(listener);
4416        }
4417    }
4418
4419    @Override
4420    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4421        synchronized (mPackages) {
4422            mOnPermissionChangeListeners.removeListenerLocked(listener);
4423        }
4424    }
4425
4426    @Override
4427    public boolean isProtectedBroadcast(String actionName) {
4428        synchronized (mPackages) {
4429            if (mProtectedBroadcasts.contains(actionName)) {
4430                return true;
4431            } else if (actionName != null) {
4432                // TODO: remove these terrible hacks
4433                if (actionName.startsWith("android.net.netmon.lingerExpired")
4434                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4435                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4436                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4437                    return true;
4438                }
4439            }
4440        }
4441        return false;
4442    }
4443
4444    @Override
4445    public int checkSignatures(String pkg1, String pkg2) {
4446        synchronized (mPackages) {
4447            final PackageParser.Package p1 = mPackages.get(pkg1);
4448            final PackageParser.Package p2 = mPackages.get(pkg2);
4449            if (p1 == null || p1.mExtras == null
4450                    || p2 == null || p2.mExtras == null) {
4451                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4452            }
4453            return compareSignatures(p1.mSignatures, p2.mSignatures);
4454        }
4455    }
4456
4457    @Override
4458    public int checkUidSignatures(int uid1, int uid2) {
4459        // Map to base uids.
4460        uid1 = UserHandle.getAppId(uid1);
4461        uid2 = UserHandle.getAppId(uid2);
4462        // reader
4463        synchronized (mPackages) {
4464            Signature[] s1;
4465            Signature[] s2;
4466            Object obj = mSettings.getUserIdLPr(uid1);
4467            if (obj != null) {
4468                if (obj instanceof SharedUserSetting) {
4469                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4470                } else if (obj instanceof PackageSetting) {
4471                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4472                } else {
4473                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4474                }
4475            } else {
4476                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4477            }
4478            obj = mSettings.getUserIdLPr(uid2);
4479            if (obj != null) {
4480                if (obj instanceof SharedUserSetting) {
4481                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4482                } else if (obj instanceof PackageSetting) {
4483                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4484                } else {
4485                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4486                }
4487            } else {
4488                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4489            }
4490            return compareSignatures(s1, s2);
4491        }
4492    }
4493
4494    /**
4495     * This method should typically only be used when granting or revoking
4496     * permissions, since the app may immediately restart after this call.
4497     * <p>
4498     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4499     * guard your work against the app being relaunched.
4500     */
4501    private void killUid(int appId, int userId, String reason) {
4502        final long identity = Binder.clearCallingIdentity();
4503        try {
4504            IActivityManager am = ActivityManagerNative.getDefault();
4505            if (am != null) {
4506                try {
4507                    am.killUid(appId, userId, reason);
4508                } catch (RemoteException e) {
4509                    /* ignore - same process */
4510                }
4511            }
4512        } finally {
4513            Binder.restoreCallingIdentity(identity);
4514        }
4515    }
4516
4517    /**
4518     * Compares two sets of signatures. Returns:
4519     * <br />
4520     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4521     * <br />
4522     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4523     * <br />
4524     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4525     * <br />
4526     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4527     * <br />
4528     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4529     */
4530    static int compareSignatures(Signature[] s1, Signature[] s2) {
4531        if (s1 == null) {
4532            return s2 == null
4533                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4534                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4535        }
4536
4537        if (s2 == null) {
4538            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4539        }
4540
4541        if (s1.length != s2.length) {
4542            return PackageManager.SIGNATURE_NO_MATCH;
4543        }
4544
4545        // Since both signature sets are of size 1, we can compare without HashSets.
4546        if (s1.length == 1) {
4547            return s1[0].equals(s2[0]) ?
4548                    PackageManager.SIGNATURE_MATCH :
4549                    PackageManager.SIGNATURE_NO_MATCH;
4550        }
4551
4552        ArraySet<Signature> set1 = new ArraySet<Signature>();
4553        for (Signature sig : s1) {
4554            set1.add(sig);
4555        }
4556        ArraySet<Signature> set2 = new ArraySet<Signature>();
4557        for (Signature sig : s2) {
4558            set2.add(sig);
4559        }
4560        // Make sure s2 contains all signatures in s1.
4561        if (set1.equals(set2)) {
4562            return PackageManager.SIGNATURE_MATCH;
4563        }
4564        return PackageManager.SIGNATURE_NO_MATCH;
4565    }
4566
4567    /**
4568     * If the database version for this type of package (internal storage or
4569     * external storage) is less than the version where package signatures
4570     * were updated, return true.
4571     */
4572    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4573        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4574        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4575    }
4576
4577    /**
4578     * Used for backward compatibility to make sure any packages with
4579     * certificate chains get upgraded to the new style. {@code existingSigs}
4580     * will be in the old format (since they were stored on disk from before the
4581     * system upgrade) and {@code scannedSigs} will be in the newer format.
4582     */
4583    private int compareSignaturesCompat(PackageSignatures existingSigs,
4584            PackageParser.Package scannedPkg) {
4585        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4586            return PackageManager.SIGNATURE_NO_MATCH;
4587        }
4588
4589        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4590        for (Signature sig : existingSigs.mSignatures) {
4591            existingSet.add(sig);
4592        }
4593        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4594        for (Signature sig : scannedPkg.mSignatures) {
4595            try {
4596                Signature[] chainSignatures = sig.getChainSignatures();
4597                for (Signature chainSig : chainSignatures) {
4598                    scannedCompatSet.add(chainSig);
4599                }
4600            } catch (CertificateEncodingException e) {
4601                scannedCompatSet.add(sig);
4602            }
4603        }
4604        /*
4605         * Make sure the expanded scanned set contains all signatures in the
4606         * existing one.
4607         */
4608        if (scannedCompatSet.equals(existingSet)) {
4609            // Migrate the old signatures to the new scheme.
4610            existingSigs.assignSignatures(scannedPkg.mSignatures);
4611            // The new KeySets will be re-added later in the scanning process.
4612            synchronized (mPackages) {
4613                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4614            }
4615            return PackageManager.SIGNATURE_MATCH;
4616        }
4617        return PackageManager.SIGNATURE_NO_MATCH;
4618    }
4619
4620    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4621        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4622        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4623    }
4624
4625    private int compareSignaturesRecover(PackageSignatures existingSigs,
4626            PackageParser.Package scannedPkg) {
4627        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4628            return PackageManager.SIGNATURE_NO_MATCH;
4629        }
4630
4631        String msg = null;
4632        try {
4633            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4634                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4635                        + scannedPkg.packageName);
4636                return PackageManager.SIGNATURE_MATCH;
4637            }
4638        } catch (CertificateException e) {
4639            msg = e.getMessage();
4640        }
4641
4642        logCriticalInfo(Log.INFO,
4643                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4644        return PackageManager.SIGNATURE_NO_MATCH;
4645    }
4646
4647    @Override
4648    public List<String> getAllPackages() {
4649        synchronized (mPackages) {
4650            return new ArrayList<String>(mPackages.keySet());
4651        }
4652    }
4653
4654    @Override
4655    public String[] getPackagesForUid(int uid) {
4656        uid = UserHandle.getAppId(uid);
4657        // reader
4658        synchronized (mPackages) {
4659            Object obj = mSettings.getUserIdLPr(uid);
4660            if (obj instanceof SharedUserSetting) {
4661                final SharedUserSetting sus = (SharedUserSetting) obj;
4662                final int N = sus.packages.size();
4663                final String[] res = new String[N];
4664                final Iterator<PackageSetting> it = sus.packages.iterator();
4665                int i = 0;
4666                while (it.hasNext()) {
4667                    res[i++] = it.next().name;
4668                }
4669                return res;
4670            } else if (obj instanceof PackageSetting) {
4671                final PackageSetting ps = (PackageSetting) obj;
4672                return new String[] { ps.name };
4673            }
4674        }
4675        return null;
4676    }
4677
4678    @Override
4679    public String getNameForUid(int uid) {
4680        // reader
4681        synchronized (mPackages) {
4682            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4683            if (obj instanceof SharedUserSetting) {
4684                final SharedUserSetting sus = (SharedUserSetting) obj;
4685                return sus.name + ":" + sus.userId;
4686            } else if (obj instanceof PackageSetting) {
4687                final PackageSetting ps = (PackageSetting) obj;
4688                return ps.name;
4689            }
4690        }
4691        return null;
4692    }
4693
4694    @Override
4695    public int getUidForSharedUser(String sharedUserName) {
4696        if(sharedUserName == null) {
4697            return -1;
4698        }
4699        // reader
4700        synchronized (mPackages) {
4701            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4702            if (suid == null) {
4703                return -1;
4704            }
4705            return suid.userId;
4706        }
4707    }
4708
4709    @Override
4710    public int getFlagsForUid(int uid) {
4711        synchronized (mPackages) {
4712            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4713            if (obj instanceof SharedUserSetting) {
4714                final SharedUserSetting sus = (SharedUserSetting) obj;
4715                return sus.pkgFlags;
4716            } else if (obj instanceof PackageSetting) {
4717                final PackageSetting ps = (PackageSetting) obj;
4718                return ps.pkgFlags;
4719            }
4720        }
4721        return 0;
4722    }
4723
4724    @Override
4725    public int getPrivateFlagsForUid(int uid) {
4726        synchronized (mPackages) {
4727            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4728            if (obj instanceof SharedUserSetting) {
4729                final SharedUserSetting sus = (SharedUserSetting) obj;
4730                return sus.pkgPrivateFlags;
4731            } else if (obj instanceof PackageSetting) {
4732                final PackageSetting ps = (PackageSetting) obj;
4733                return ps.pkgPrivateFlags;
4734            }
4735        }
4736        return 0;
4737    }
4738
4739    @Override
4740    public boolean isUidPrivileged(int uid) {
4741        uid = UserHandle.getAppId(uid);
4742        // reader
4743        synchronized (mPackages) {
4744            Object obj = mSettings.getUserIdLPr(uid);
4745            if (obj instanceof SharedUserSetting) {
4746                final SharedUserSetting sus = (SharedUserSetting) obj;
4747                final Iterator<PackageSetting> it = sus.packages.iterator();
4748                while (it.hasNext()) {
4749                    if (it.next().isPrivileged()) {
4750                        return true;
4751                    }
4752                }
4753            } else if (obj instanceof PackageSetting) {
4754                final PackageSetting ps = (PackageSetting) obj;
4755                return ps.isPrivileged();
4756            }
4757        }
4758        return false;
4759    }
4760
4761    @Override
4762    public String[] getAppOpPermissionPackages(String permissionName) {
4763        synchronized (mPackages) {
4764            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4765            if (pkgs == null) {
4766                return null;
4767            }
4768            return pkgs.toArray(new String[pkgs.size()]);
4769        }
4770    }
4771
4772    @Override
4773    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4774            int flags, int userId) {
4775        try {
4776            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4777
4778            if (!sUserManager.exists(userId)) return null;
4779            flags = updateFlagsForResolve(flags, userId, intent);
4780            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4781                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4782
4783            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4784            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4785                    flags, userId);
4786            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4787
4788            final ResolveInfo bestChoice =
4789                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4790
4791            if (isEphemeralAllowed(intent, query, userId)) {
4792                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4793                final EphemeralResolveInfo ai =
4794                        getEphemeralResolveInfo(intent, resolvedType, userId);
4795                if (ai != null) {
4796                    if (DEBUG_EPHEMERAL) {
4797                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4798                    }
4799                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4800                    bestChoice.ephemeralResolveInfo = ai;
4801                }
4802                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4803            }
4804            return bestChoice;
4805        } finally {
4806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4807        }
4808    }
4809
4810    @Override
4811    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4812            IntentFilter filter, int match, ComponentName activity) {
4813        final int userId = UserHandle.getCallingUserId();
4814        if (DEBUG_PREFERRED) {
4815            Log.v(TAG, "setLastChosenActivity intent=" + intent
4816                + " resolvedType=" + resolvedType
4817                + " flags=" + flags
4818                + " filter=" + filter
4819                + " match=" + match
4820                + " activity=" + activity);
4821            filter.dump(new PrintStreamPrinter(System.out), "    ");
4822        }
4823        intent.setComponent(null);
4824        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4825                userId);
4826        // Find any earlier preferred or last chosen entries and nuke them
4827        findPreferredActivity(intent, resolvedType,
4828                flags, query, 0, false, true, false, userId);
4829        // Add the new activity as the last chosen for this filter
4830        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4831                "Setting last chosen");
4832    }
4833
4834    @Override
4835    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4836        final int userId = UserHandle.getCallingUserId();
4837        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4838        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4839                userId);
4840        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4841                false, false, false, userId);
4842    }
4843
4844
4845    private boolean isEphemeralAllowed(
4846            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4847        // Short circuit and return early if possible.
4848        if (DISABLE_EPHEMERAL_APPS) {
4849            return false;
4850        }
4851        final int callingUser = UserHandle.getCallingUserId();
4852        if (callingUser != UserHandle.USER_SYSTEM) {
4853            return false;
4854        }
4855        if (mEphemeralResolverConnection == null) {
4856            return false;
4857        }
4858        if (intent.getComponent() != null) {
4859            return false;
4860        }
4861        if (intent.getPackage() != null) {
4862            return false;
4863        }
4864        final boolean isWebUri = hasWebURI(intent);
4865        if (!isWebUri) {
4866            return false;
4867        }
4868        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4869        synchronized (mPackages) {
4870            final int count = resolvedActivites.size();
4871            for (int n = 0; n < count; n++) {
4872                ResolveInfo info = resolvedActivites.get(n);
4873                String packageName = info.activityInfo.packageName;
4874                PackageSetting ps = mSettings.mPackages.get(packageName);
4875                if (ps != null) {
4876                    // Try to get the status from User settings first
4877                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4878                    int status = (int) (packedStatus >> 32);
4879                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4880                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4881                        if (DEBUG_EPHEMERAL) {
4882                            Slog.v(TAG, "DENY ephemeral apps;"
4883                                + " pkg: " + packageName + ", status: " + status);
4884                        }
4885                        return false;
4886                    }
4887                }
4888            }
4889        }
4890        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4891        return true;
4892    }
4893
4894    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4895            int userId) {
4896        MessageDigest digest = null;
4897        try {
4898            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4899        } catch (NoSuchAlgorithmException e) {
4900            // If we can't create a digest, ignore ephemeral apps.
4901            return null;
4902        }
4903
4904        final byte[] hostBytes = intent.getData().getHost().getBytes();
4905        final byte[] digestBytes = digest.digest(hostBytes);
4906        int shaPrefix =
4907                digestBytes[0] << 24
4908                | digestBytes[1] << 16
4909                | digestBytes[2] << 8
4910                | digestBytes[3] << 0;
4911        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4912                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4913        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4914            // No hash prefix match; there are no ephemeral apps for this domain.
4915            return null;
4916        }
4917        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4918            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4919            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4920                continue;
4921            }
4922            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4923            // No filters; this should never happen.
4924            if (filters.isEmpty()) {
4925                continue;
4926            }
4927            // We have a domain match; resolve the filters to see if anything matches.
4928            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4929            for (int j = filters.size() - 1; j >= 0; --j) {
4930                final EphemeralResolveIntentInfo intentInfo =
4931                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4932                ephemeralResolver.addFilter(intentInfo);
4933            }
4934            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4935                    intent, resolvedType, false /*defaultOnly*/, userId);
4936            if (!matchedResolveInfoList.isEmpty()) {
4937                return matchedResolveInfoList.get(0);
4938            }
4939        }
4940        // Hash or filter mis-match; no ephemeral apps for this domain.
4941        return null;
4942    }
4943
4944    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4945            int flags, List<ResolveInfo> query, int userId) {
4946        if (query != null) {
4947            final int N = query.size();
4948            if (N == 1) {
4949                return query.get(0);
4950            } else if (N > 1) {
4951                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4952                // If there is more than one activity with the same priority,
4953                // then let the user decide between them.
4954                ResolveInfo r0 = query.get(0);
4955                ResolveInfo r1 = query.get(1);
4956                if (DEBUG_INTENT_MATCHING || debug) {
4957                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4958                            + r1.activityInfo.name + "=" + r1.priority);
4959                }
4960                // If the first activity has a higher priority, or a different
4961                // default, then it is always desirable to pick it.
4962                if (r0.priority != r1.priority
4963                        || r0.preferredOrder != r1.preferredOrder
4964                        || r0.isDefault != r1.isDefault) {
4965                    return query.get(0);
4966                }
4967                // If we have saved a preference for a preferred activity for
4968                // this Intent, use that.
4969                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4970                        flags, query, r0.priority, true, false, debug, userId);
4971                if (ri != null) {
4972                    return ri;
4973                }
4974                ri = new ResolveInfo(mResolveInfo);
4975                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4976                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4977                ri.activityInfo.applicationInfo = new ApplicationInfo(
4978                        ri.activityInfo.applicationInfo);
4979                if (userId != 0) {
4980                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4981                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4982                }
4983                // Make sure that the resolver is displayable in car mode
4984                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4985                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4986                return ri;
4987            }
4988        }
4989        return null;
4990    }
4991
4992    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4993            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4994        final int N = query.size();
4995        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4996                .get(userId);
4997        // Get the list of persistent preferred activities that handle the intent
4998        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4999        List<PersistentPreferredActivity> pprefs = ppir != null
5000                ? ppir.queryIntent(intent, resolvedType,
5001                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5002                : null;
5003        if (pprefs != null && pprefs.size() > 0) {
5004            final int M = pprefs.size();
5005            for (int i=0; i<M; i++) {
5006                final PersistentPreferredActivity ppa = pprefs.get(i);
5007                if (DEBUG_PREFERRED || debug) {
5008                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5009                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5010                            + "\n  component=" + ppa.mComponent);
5011                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5012                }
5013                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5014                        flags | MATCH_DISABLED_COMPONENTS, userId);
5015                if (DEBUG_PREFERRED || debug) {
5016                    Slog.v(TAG, "Found persistent preferred activity:");
5017                    if (ai != null) {
5018                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5019                    } else {
5020                        Slog.v(TAG, "  null");
5021                    }
5022                }
5023                if (ai == null) {
5024                    // This previously registered persistent preferred activity
5025                    // component is no longer known. Ignore it and do NOT remove it.
5026                    continue;
5027                }
5028                for (int j=0; j<N; j++) {
5029                    final ResolveInfo ri = query.get(j);
5030                    if (!ri.activityInfo.applicationInfo.packageName
5031                            .equals(ai.applicationInfo.packageName)) {
5032                        continue;
5033                    }
5034                    if (!ri.activityInfo.name.equals(ai.name)) {
5035                        continue;
5036                    }
5037                    //  Found a persistent preference that can handle the intent.
5038                    if (DEBUG_PREFERRED || debug) {
5039                        Slog.v(TAG, "Returning persistent preferred activity: " +
5040                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5041                    }
5042                    return ri;
5043                }
5044            }
5045        }
5046        return null;
5047    }
5048
5049    // TODO: handle preferred activities missing while user has amnesia
5050    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5051            List<ResolveInfo> query, int priority, boolean always,
5052            boolean removeMatches, boolean debug, int userId) {
5053        if (!sUserManager.exists(userId)) return null;
5054        flags = updateFlagsForResolve(flags, userId, intent);
5055        // writer
5056        synchronized (mPackages) {
5057            if (intent.getSelector() != null) {
5058                intent = intent.getSelector();
5059            }
5060            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5061
5062            // Try to find a matching persistent preferred activity.
5063            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5064                    debug, userId);
5065
5066            // If a persistent preferred activity matched, use it.
5067            if (pri != null) {
5068                return pri;
5069            }
5070
5071            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5072            // Get the list of preferred activities that handle the intent
5073            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5074            List<PreferredActivity> prefs = pir != null
5075                    ? pir.queryIntent(intent, resolvedType,
5076                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5077                    : null;
5078            if (prefs != null && prefs.size() > 0) {
5079                boolean changed = false;
5080                try {
5081                    // First figure out how good the original match set is.
5082                    // We will only allow preferred activities that came
5083                    // from the same match quality.
5084                    int match = 0;
5085
5086                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5087
5088                    final int N = query.size();
5089                    for (int j=0; j<N; j++) {
5090                        final ResolveInfo ri = query.get(j);
5091                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5092                                + ": 0x" + Integer.toHexString(match));
5093                        if (ri.match > match) {
5094                            match = ri.match;
5095                        }
5096                    }
5097
5098                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5099                            + Integer.toHexString(match));
5100
5101                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5102                    final int M = prefs.size();
5103                    for (int i=0; i<M; i++) {
5104                        final PreferredActivity pa = prefs.get(i);
5105                        if (DEBUG_PREFERRED || debug) {
5106                            Slog.v(TAG, "Checking PreferredActivity ds="
5107                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5108                                    + "\n  component=" + pa.mPref.mComponent);
5109                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5110                        }
5111                        if (pa.mPref.mMatch != match) {
5112                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5113                                    + Integer.toHexString(pa.mPref.mMatch));
5114                            continue;
5115                        }
5116                        // If it's not an "always" type preferred activity and that's what we're
5117                        // looking for, skip it.
5118                        if (always && !pa.mPref.mAlways) {
5119                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5120                            continue;
5121                        }
5122                        final ActivityInfo ai = getActivityInfo(
5123                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5124                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5125                                userId);
5126                        if (DEBUG_PREFERRED || debug) {
5127                            Slog.v(TAG, "Found preferred activity:");
5128                            if (ai != null) {
5129                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5130                            } else {
5131                                Slog.v(TAG, "  null");
5132                            }
5133                        }
5134                        if (ai == null) {
5135                            // This previously registered preferred activity
5136                            // component is no longer known.  Most likely an update
5137                            // to the app was installed and in the new version this
5138                            // component no longer exists.  Clean it up by removing
5139                            // it from the preferred activities list, and skip it.
5140                            Slog.w(TAG, "Removing dangling preferred activity: "
5141                                    + pa.mPref.mComponent);
5142                            pir.removeFilter(pa);
5143                            changed = true;
5144                            continue;
5145                        }
5146                        for (int j=0; j<N; j++) {
5147                            final ResolveInfo ri = query.get(j);
5148                            if (!ri.activityInfo.applicationInfo.packageName
5149                                    .equals(ai.applicationInfo.packageName)) {
5150                                continue;
5151                            }
5152                            if (!ri.activityInfo.name.equals(ai.name)) {
5153                                continue;
5154                            }
5155
5156                            if (removeMatches) {
5157                                pir.removeFilter(pa);
5158                                changed = true;
5159                                if (DEBUG_PREFERRED) {
5160                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5161                                }
5162                                break;
5163                            }
5164
5165                            // Okay we found a previously set preferred or last chosen app.
5166                            // If the result set is different from when this
5167                            // was created, we need to clear it and re-ask the
5168                            // user their preference, if we're looking for an "always" type entry.
5169                            if (always && !pa.mPref.sameSet(query)) {
5170                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5171                                        + intent + " type " + resolvedType);
5172                                if (DEBUG_PREFERRED) {
5173                                    Slog.v(TAG, "Removing preferred activity since set changed "
5174                                            + pa.mPref.mComponent);
5175                                }
5176                                pir.removeFilter(pa);
5177                                // Re-add the filter as a "last chosen" entry (!always)
5178                                PreferredActivity lastChosen = new PreferredActivity(
5179                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5180                                pir.addFilter(lastChosen);
5181                                changed = true;
5182                                return null;
5183                            }
5184
5185                            // Yay! Either the set matched or we're looking for the last chosen
5186                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5187                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5188                            return ri;
5189                        }
5190                    }
5191                } finally {
5192                    if (changed) {
5193                        if (DEBUG_PREFERRED) {
5194                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5195                        }
5196                        scheduleWritePackageRestrictionsLocked(userId);
5197                    }
5198                }
5199            }
5200        }
5201        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5202        return null;
5203    }
5204
5205    /*
5206     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5207     */
5208    @Override
5209    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5210            int targetUserId) {
5211        mContext.enforceCallingOrSelfPermission(
5212                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5213        List<CrossProfileIntentFilter> matches =
5214                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5215        if (matches != null) {
5216            int size = matches.size();
5217            for (int i = 0; i < size; i++) {
5218                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5219            }
5220        }
5221        if (hasWebURI(intent)) {
5222            // cross-profile app linking works only towards the parent.
5223            final UserInfo parent = getProfileParent(sourceUserId);
5224            synchronized(mPackages) {
5225                int flags = updateFlagsForResolve(0, parent.id, intent);
5226                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5227                        intent, resolvedType, flags, sourceUserId, parent.id);
5228                return xpDomainInfo != null;
5229            }
5230        }
5231        return false;
5232    }
5233
5234    private UserInfo getProfileParent(int userId) {
5235        final long identity = Binder.clearCallingIdentity();
5236        try {
5237            return sUserManager.getProfileParent(userId);
5238        } finally {
5239            Binder.restoreCallingIdentity(identity);
5240        }
5241    }
5242
5243    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5244            String resolvedType, int userId) {
5245        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5246        if (resolver != null) {
5247            return resolver.queryIntent(intent, resolvedType, false, userId);
5248        }
5249        return null;
5250    }
5251
5252    @Override
5253    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5254            String resolvedType, int flags, int userId) {
5255        try {
5256            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5257
5258            return new ParceledListSlice<>(
5259                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5260        } finally {
5261            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5262        }
5263    }
5264
5265    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5266            String resolvedType, int flags, int userId) {
5267        if (!sUserManager.exists(userId)) return Collections.emptyList();
5268        flags = updateFlagsForResolve(flags, userId, intent);
5269        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5270                false /* requireFullPermission */, false /* checkShell */,
5271                "query intent activities");
5272        ComponentName comp = intent.getComponent();
5273        if (comp == null) {
5274            if (intent.getSelector() != null) {
5275                intent = intent.getSelector();
5276                comp = intent.getComponent();
5277            }
5278        }
5279
5280        if (comp != null) {
5281            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5282            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5283            if (ai != null) {
5284                final ResolveInfo ri = new ResolveInfo();
5285                ri.activityInfo = ai;
5286                list.add(ri);
5287            }
5288            return list;
5289        }
5290
5291        // reader
5292        synchronized (mPackages) {
5293            final String pkgName = intent.getPackage();
5294            if (pkgName == null) {
5295                List<CrossProfileIntentFilter> matchingFilters =
5296                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5297                // Check for results that need to skip the current profile.
5298                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5299                        resolvedType, flags, userId);
5300                if (xpResolveInfo != null) {
5301                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5302                    result.add(xpResolveInfo);
5303                    return filterIfNotSystemUser(result, userId);
5304                }
5305
5306                // Check for results in the current profile.
5307                List<ResolveInfo> result = mActivities.queryIntent(
5308                        intent, resolvedType, flags, userId);
5309                result = filterIfNotSystemUser(result, userId);
5310
5311                // Check for cross profile results.
5312                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5313                xpResolveInfo = queryCrossProfileIntents(
5314                        matchingFilters, intent, resolvedType, flags, userId,
5315                        hasNonNegativePriorityResult);
5316                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5317                    boolean isVisibleToUser = filterIfNotSystemUser(
5318                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5319                    if (isVisibleToUser) {
5320                        result.add(xpResolveInfo);
5321                        Collections.sort(result, mResolvePrioritySorter);
5322                    }
5323                }
5324                if (hasWebURI(intent)) {
5325                    CrossProfileDomainInfo xpDomainInfo = null;
5326                    final UserInfo parent = getProfileParent(userId);
5327                    if (parent != null) {
5328                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5329                                flags, userId, parent.id);
5330                    }
5331                    if (xpDomainInfo != null) {
5332                        if (xpResolveInfo != null) {
5333                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5334                            // in the result.
5335                            result.remove(xpResolveInfo);
5336                        }
5337                        if (result.size() == 0) {
5338                            result.add(xpDomainInfo.resolveInfo);
5339                            return result;
5340                        }
5341                    } else if (result.size() <= 1) {
5342                        return result;
5343                    }
5344                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5345                            xpDomainInfo, userId);
5346                    Collections.sort(result, mResolvePrioritySorter);
5347                }
5348                return result;
5349            }
5350            final PackageParser.Package pkg = mPackages.get(pkgName);
5351            if (pkg != null) {
5352                return filterIfNotSystemUser(
5353                        mActivities.queryIntentForPackage(
5354                                intent, resolvedType, flags, pkg.activities, userId),
5355                        userId);
5356            }
5357            return new ArrayList<ResolveInfo>();
5358        }
5359    }
5360
5361    private static class CrossProfileDomainInfo {
5362        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5363        ResolveInfo resolveInfo;
5364        /* Best domain verification status of the activities found in the other profile */
5365        int bestDomainVerificationStatus;
5366    }
5367
5368    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5369            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5370        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5371                sourceUserId)) {
5372            return null;
5373        }
5374        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5375                resolvedType, flags, parentUserId);
5376
5377        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5378            return null;
5379        }
5380        CrossProfileDomainInfo result = null;
5381        int size = resultTargetUser.size();
5382        for (int i = 0; i < size; i++) {
5383            ResolveInfo riTargetUser = resultTargetUser.get(i);
5384            // Intent filter verification is only for filters that specify a host. So don't return
5385            // those that handle all web uris.
5386            if (riTargetUser.handleAllWebDataURI) {
5387                continue;
5388            }
5389            String packageName = riTargetUser.activityInfo.packageName;
5390            PackageSetting ps = mSettings.mPackages.get(packageName);
5391            if (ps == null) {
5392                continue;
5393            }
5394            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5395            int status = (int)(verificationState >> 32);
5396            if (result == null) {
5397                result = new CrossProfileDomainInfo();
5398                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5399                        sourceUserId, parentUserId);
5400                result.bestDomainVerificationStatus = status;
5401            } else {
5402                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5403                        result.bestDomainVerificationStatus);
5404            }
5405        }
5406        // Don't consider matches with status NEVER across profiles.
5407        if (result != null && result.bestDomainVerificationStatus
5408                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5409            return null;
5410        }
5411        return result;
5412    }
5413
5414    /**
5415     * Verification statuses are ordered from the worse to the best, except for
5416     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5417     */
5418    private int bestDomainVerificationStatus(int status1, int status2) {
5419        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5420            return status2;
5421        }
5422        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5423            return status1;
5424        }
5425        return (int) MathUtils.max(status1, status2);
5426    }
5427
5428    private boolean isUserEnabled(int userId) {
5429        long callingId = Binder.clearCallingIdentity();
5430        try {
5431            UserInfo userInfo = sUserManager.getUserInfo(userId);
5432            return userInfo != null && userInfo.isEnabled();
5433        } finally {
5434            Binder.restoreCallingIdentity(callingId);
5435        }
5436    }
5437
5438    /**
5439     * Filter out activities with systemUserOnly flag set, when current user is not System.
5440     *
5441     * @return filtered list
5442     */
5443    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5444        if (userId == UserHandle.USER_SYSTEM) {
5445            return resolveInfos;
5446        }
5447        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5448            ResolveInfo info = resolveInfos.get(i);
5449            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5450                resolveInfos.remove(i);
5451            }
5452        }
5453        return resolveInfos;
5454    }
5455
5456    /**
5457     * @param resolveInfos list of resolve infos in descending priority order
5458     * @return if the list contains a resolve info with non-negative priority
5459     */
5460    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5461        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5462    }
5463
5464    private static boolean hasWebURI(Intent intent) {
5465        if (intent.getData() == null) {
5466            return false;
5467        }
5468        final String scheme = intent.getScheme();
5469        if (TextUtils.isEmpty(scheme)) {
5470            return false;
5471        }
5472        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5473    }
5474
5475    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5476            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5477            int userId) {
5478        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5479
5480        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5481            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5482                    candidates.size());
5483        }
5484
5485        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5486        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5487        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5488        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5489        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5490        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5491
5492        synchronized (mPackages) {
5493            final int count = candidates.size();
5494            // First, try to use linked apps. Partition the candidates into four lists:
5495            // one for the final results, one for the "do not use ever", one for "undefined status"
5496            // and finally one for "browser app type".
5497            for (int n=0; n<count; n++) {
5498                ResolveInfo info = candidates.get(n);
5499                String packageName = info.activityInfo.packageName;
5500                PackageSetting ps = mSettings.mPackages.get(packageName);
5501                if (ps != null) {
5502                    // Add to the special match all list (Browser use case)
5503                    if (info.handleAllWebDataURI) {
5504                        matchAllList.add(info);
5505                        continue;
5506                    }
5507                    // Try to get the status from User settings first
5508                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5509                    int status = (int)(packedStatus >> 32);
5510                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5511                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5512                        if (DEBUG_DOMAIN_VERIFICATION) {
5513                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5514                                    + " : linkgen=" + linkGeneration);
5515                        }
5516                        // Use link-enabled generation as preferredOrder, i.e.
5517                        // prefer newly-enabled over earlier-enabled.
5518                        info.preferredOrder = linkGeneration;
5519                        alwaysList.add(info);
5520                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5521                        if (DEBUG_DOMAIN_VERIFICATION) {
5522                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5523                        }
5524                        neverList.add(info);
5525                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5526                        if (DEBUG_DOMAIN_VERIFICATION) {
5527                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5528                        }
5529                        alwaysAskList.add(info);
5530                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5531                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5532                        if (DEBUG_DOMAIN_VERIFICATION) {
5533                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5534                        }
5535                        undefinedList.add(info);
5536                    }
5537                }
5538            }
5539
5540            // We'll want to include browser possibilities in a few cases
5541            boolean includeBrowser = false;
5542
5543            // First try to add the "always" resolution(s) for the current user, if any
5544            if (alwaysList.size() > 0) {
5545                result.addAll(alwaysList);
5546            } else {
5547                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5548                result.addAll(undefinedList);
5549                // Maybe add one for the other profile.
5550                if (xpDomainInfo != null && (
5551                        xpDomainInfo.bestDomainVerificationStatus
5552                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5553                    result.add(xpDomainInfo.resolveInfo);
5554                }
5555                includeBrowser = true;
5556            }
5557
5558            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5559            // If there were 'always' entries their preferred order has been set, so we also
5560            // back that off to make the alternatives equivalent
5561            if (alwaysAskList.size() > 0) {
5562                for (ResolveInfo i : result) {
5563                    i.preferredOrder = 0;
5564                }
5565                result.addAll(alwaysAskList);
5566                includeBrowser = true;
5567            }
5568
5569            if (includeBrowser) {
5570                // Also add browsers (all of them or only the default one)
5571                if (DEBUG_DOMAIN_VERIFICATION) {
5572                    Slog.v(TAG, "   ...including browsers in candidate set");
5573                }
5574                if ((matchFlags & MATCH_ALL) != 0) {
5575                    result.addAll(matchAllList);
5576                } else {
5577                    // Browser/generic handling case.  If there's a default browser, go straight
5578                    // to that (but only if there is no other higher-priority match).
5579                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5580                    int maxMatchPrio = 0;
5581                    ResolveInfo defaultBrowserMatch = null;
5582                    final int numCandidates = matchAllList.size();
5583                    for (int n = 0; n < numCandidates; n++) {
5584                        ResolveInfo info = matchAllList.get(n);
5585                        // track the highest overall match priority...
5586                        if (info.priority > maxMatchPrio) {
5587                            maxMatchPrio = info.priority;
5588                        }
5589                        // ...and the highest-priority default browser match
5590                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5591                            if (defaultBrowserMatch == null
5592                                    || (defaultBrowserMatch.priority < info.priority)) {
5593                                if (debug) {
5594                                    Slog.v(TAG, "Considering default browser match " + info);
5595                                }
5596                                defaultBrowserMatch = info;
5597                            }
5598                        }
5599                    }
5600                    if (defaultBrowserMatch != null
5601                            && defaultBrowserMatch.priority >= maxMatchPrio
5602                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5603                    {
5604                        if (debug) {
5605                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5606                        }
5607                        result.add(defaultBrowserMatch);
5608                    } else {
5609                        result.addAll(matchAllList);
5610                    }
5611                }
5612
5613                // If there is nothing selected, add all candidates and remove the ones that the user
5614                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5615                if (result.size() == 0) {
5616                    result.addAll(candidates);
5617                    result.removeAll(neverList);
5618                }
5619            }
5620        }
5621        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5622            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5623                    result.size());
5624            for (ResolveInfo info : result) {
5625                Slog.v(TAG, "  + " + info.activityInfo);
5626            }
5627        }
5628        return result;
5629    }
5630
5631    // Returns a packed value as a long:
5632    //
5633    // high 'int'-sized word: link status: undefined/ask/never/always.
5634    // low 'int'-sized word: relative priority among 'always' results.
5635    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5636        long result = ps.getDomainVerificationStatusForUser(userId);
5637        // if none available, get the master status
5638        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5639            if (ps.getIntentFilterVerificationInfo() != null) {
5640                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5641            }
5642        }
5643        return result;
5644    }
5645
5646    private ResolveInfo querySkipCurrentProfileIntents(
5647            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5648            int flags, int sourceUserId) {
5649        if (matchingFilters != null) {
5650            int size = matchingFilters.size();
5651            for (int i = 0; i < size; i ++) {
5652                CrossProfileIntentFilter filter = matchingFilters.get(i);
5653                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5654                    // Checking if there are activities in the target user that can handle the
5655                    // intent.
5656                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5657                            resolvedType, flags, sourceUserId);
5658                    if (resolveInfo != null) {
5659                        return resolveInfo;
5660                    }
5661                }
5662            }
5663        }
5664        return null;
5665    }
5666
5667    // Return matching ResolveInfo in target user if any.
5668    private ResolveInfo queryCrossProfileIntents(
5669            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5670            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5671        if (matchingFilters != null) {
5672            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5673            // match the same intent. For performance reasons, it is better not to
5674            // run queryIntent twice for the same userId
5675            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5676            int size = matchingFilters.size();
5677            for (int i = 0; i < size; i++) {
5678                CrossProfileIntentFilter filter = matchingFilters.get(i);
5679                int targetUserId = filter.getTargetUserId();
5680                boolean skipCurrentProfile =
5681                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5682                boolean skipCurrentProfileIfNoMatchFound =
5683                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5684                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5685                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5686                    // Checking if there are activities in the target user that can handle the
5687                    // intent.
5688                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5689                            resolvedType, flags, sourceUserId);
5690                    if (resolveInfo != null) return resolveInfo;
5691                    alreadyTriedUserIds.put(targetUserId, true);
5692                }
5693            }
5694        }
5695        return null;
5696    }
5697
5698    /**
5699     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5700     * will forward the intent to the filter's target user.
5701     * Otherwise, returns null.
5702     */
5703    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5704            String resolvedType, int flags, int sourceUserId) {
5705        int targetUserId = filter.getTargetUserId();
5706        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5707                resolvedType, flags, targetUserId);
5708        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5709            // If all the matches in the target profile are suspended, return null.
5710            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5711                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5712                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5713                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5714                            targetUserId);
5715                }
5716            }
5717        }
5718        return null;
5719    }
5720
5721    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5722            int sourceUserId, int targetUserId) {
5723        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5724        long ident = Binder.clearCallingIdentity();
5725        boolean targetIsProfile;
5726        try {
5727            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5728        } finally {
5729            Binder.restoreCallingIdentity(ident);
5730        }
5731        String className;
5732        if (targetIsProfile) {
5733            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5734        } else {
5735            className = FORWARD_INTENT_TO_PARENT;
5736        }
5737        ComponentName forwardingActivityComponentName = new ComponentName(
5738                mAndroidApplication.packageName, className);
5739        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5740                sourceUserId);
5741        if (!targetIsProfile) {
5742            forwardingActivityInfo.showUserIcon = targetUserId;
5743            forwardingResolveInfo.noResourceId = true;
5744        }
5745        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5746        forwardingResolveInfo.priority = 0;
5747        forwardingResolveInfo.preferredOrder = 0;
5748        forwardingResolveInfo.match = 0;
5749        forwardingResolveInfo.isDefault = true;
5750        forwardingResolveInfo.filter = filter;
5751        forwardingResolveInfo.targetUserId = targetUserId;
5752        return forwardingResolveInfo;
5753    }
5754
5755    @Override
5756    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5757            Intent[] specifics, String[] specificTypes, Intent intent,
5758            String resolvedType, int flags, int userId) {
5759        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5760                specificTypes, intent, resolvedType, flags, userId));
5761    }
5762
5763    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5764            Intent[] specifics, String[] specificTypes, Intent intent,
5765            String resolvedType, int flags, int userId) {
5766        if (!sUserManager.exists(userId)) return Collections.emptyList();
5767        flags = updateFlagsForResolve(flags, userId, intent);
5768        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5769                false /* requireFullPermission */, false /* checkShell */,
5770                "query intent activity options");
5771        final String resultsAction = intent.getAction();
5772
5773        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5774                | PackageManager.GET_RESOLVED_FILTER, userId);
5775
5776        if (DEBUG_INTENT_MATCHING) {
5777            Log.v(TAG, "Query " + intent + ": " + results);
5778        }
5779
5780        int specificsPos = 0;
5781        int N;
5782
5783        // todo: note that the algorithm used here is O(N^2).  This
5784        // isn't a problem in our current environment, but if we start running
5785        // into situations where we have more than 5 or 10 matches then this
5786        // should probably be changed to something smarter...
5787
5788        // First we go through and resolve each of the specific items
5789        // that were supplied, taking care of removing any corresponding
5790        // duplicate items in the generic resolve list.
5791        if (specifics != null) {
5792            for (int i=0; i<specifics.length; i++) {
5793                final Intent sintent = specifics[i];
5794                if (sintent == null) {
5795                    continue;
5796                }
5797
5798                if (DEBUG_INTENT_MATCHING) {
5799                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5800                }
5801
5802                String action = sintent.getAction();
5803                if (resultsAction != null && resultsAction.equals(action)) {
5804                    // If this action was explicitly requested, then don't
5805                    // remove things that have it.
5806                    action = null;
5807                }
5808
5809                ResolveInfo ri = null;
5810                ActivityInfo ai = null;
5811
5812                ComponentName comp = sintent.getComponent();
5813                if (comp == null) {
5814                    ri = resolveIntent(
5815                        sintent,
5816                        specificTypes != null ? specificTypes[i] : null,
5817                            flags, userId);
5818                    if (ri == null) {
5819                        continue;
5820                    }
5821                    if (ri == mResolveInfo) {
5822                        // ACK!  Must do something better with this.
5823                    }
5824                    ai = ri.activityInfo;
5825                    comp = new ComponentName(ai.applicationInfo.packageName,
5826                            ai.name);
5827                } else {
5828                    ai = getActivityInfo(comp, flags, userId);
5829                    if (ai == null) {
5830                        continue;
5831                    }
5832                }
5833
5834                // Look for any generic query activities that are duplicates
5835                // of this specific one, and remove them from the results.
5836                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5837                N = results.size();
5838                int j;
5839                for (j=specificsPos; j<N; j++) {
5840                    ResolveInfo sri = results.get(j);
5841                    if ((sri.activityInfo.name.equals(comp.getClassName())
5842                            && sri.activityInfo.applicationInfo.packageName.equals(
5843                                    comp.getPackageName()))
5844                        || (action != null && sri.filter.matchAction(action))) {
5845                        results.remove(j);
5846                        if (DEBUG_INTENT_MATCHING) Log.v(
5847                            TAG, "Removing duplicate item from " + j
5848                            + " due to specific " + specificsPos);
5849                        if (ri == null) {
5850                            ri = sri;
5851                        }
5852                        j--;
5853                        N--;
5854                    }
5855                }
5856
5857                // Add this specific item to its proper place.
5858                if (ri == null) {
5859                    ri = new ResolveInfo();
5860                    ri.activityInfo = ai;
5861                }
5862                results.add(specificsPos, ri);
5863                ri.specificIndex = i;
5864                specificsPos++;
5865            }
5866        }
5867
5868        // Now we go through the remaining generic results and remove any
5869        // duplicate actions that are found here.
5870        N = results.size();
5871        for (int i=specificsPos; i<N-1; i++) {
5872            final ResolveInfo rii = results.get(i);
5873            if (rii.filter == null) {
5874                continue;
5875            }
5876
5877            // Iterate over all of the actions of this result's intent
5878            // filter...  typically this should be just one.
5879            final Iterator<String> it = rii.filter.actionsIterator();
5880            if (it == null) {
5881                continue;
5882            }
5883            while (it.hasNext()) {
5884                final String action = it.next();
5885                if (resultsAction != null && resultsAction.equals(action)) {
5886                    // If this action was explicitly requested, then don't
5887                    // remove things that have it.
5888                    continue;
5889                }
5890                for (int j=i+1; j<N; j++) {
5891                    final ResolveInfo rij = results.get(j);
5892                    if (rij.filter != null && rij.filter.hasAction(action)) {
5893                        results.remove(j);
5894                        if (DEBUG_INTENT_MATCHING) Log.v(
5895                            TAG, "Removing duplicate item from " + j
5896                            + " due to action " + action + " at " + i);
5897                        j--;
5898                        N--;
5899                    }
5900                }
5901            }
5902
5903            // If the caller didn't request filter information, drop it now
5904            // so we don't have to marshall/unmarshall it.
5905            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5906                rii.filter = null;
5907            }
5908        }
5909
5910        // Filter out the caller activity if so requested.
5911        if (caller != null) {
5912            N = results.size();
5913            for (int i=0; i<N; i++) {
5914                ActivityInfo ainfo = results.get(i).activityInfo;
5915                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5916                        && caller.getClassName().equals(ainfo.name)) {
5917                    results.remove(i);
5918                    break;
5919                }
5920            }
5921        }
5922
5923        // If the caller didn't request filter information,
5924        // drop them now so we don't have to
5925        // marshall/unmarshall it.
5926        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5927            N = results.size();
5928            for (int i=0; i<N; i++) {
5929                results.get(i).filter = null;
5930            }
5931        }
5932
5933        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5934        return results;
5935    }
5936
5937    @Override
5938    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5939            String resolvedType, int flags, int userId) {
5940        return new ParceledListSlice<>(
5941                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5942    }
5943
5944    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5945            String resolvedType, int flags, int userId) {
5946        if (!sUserManager.exists(userId)) return Collections.emptyList();
5947        flags = updateFlagsForResolve(flags, userId, intent);
5948        ComponentName comp = intent.getComponent();
5949        if (comp == null) {
5950            if (intent.getSelector() != null) {
5951                intent = intent.getSelector();
5952                comp = intent.getComponent();
5953            }
5954        }
5955        if (comp != null) {
5956            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5957            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5958            if (ai != null) {
5959                ResolveInfo ri = new ResolveInfo();
5960                ri.activityInfo = ai;
5961                list.add(ri);
5962            }
5963            return list;
5964        }
5965
5966        // reader
5967        synchronized (mPackages) {
5968            String pkgName = intent.getPackage();
5969            if (pkgName == null) {
5970                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5971            }
5972            final PackageParser.Package pkg = mPackages.get(pkgName);
5973            if (pkg != null) {
5974                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5975                        userId);
5976            }
5977            return Collections.emptyList();
5978        }
5979    }
5980
5981    @Override
5982    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5983        if (!sUserManager.exists(userId)) return null;
5984        flags = updateFlagsForResolve(flags, userId, intent);
5985        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5986        if (query != null) {
5987            if (query.size() >= 1) {
5988                // If there is more than one service with the same priority,
5989                // just arbitrarily pick the first one.
5990                return query.get(0);
5991            }
5992        }
5993        return null;
5994    }
5995
5996    @Override
5997    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5998            String resolvedType, int flags, int userId) {
5999        return new ParceledListSlice<>(
6000                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6001    }
6002
6003    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6004            String resolvedType, int flags, int userId) {
6005        if (!sUserManager.exists(userId)) return Collections.emptyList();
6006        flags = updateFlagsForResolve(flags, userId, intent);
6007        ComponentName comp = intent.getComponent();
6008        if (comp == null) {
6009            if (intent.getSelector() != null) {
6010                intent = intent.getSelector();
6011                comp = intent.getComponent();
6012            }
6013        }
6014        if (comp != null) {
6015            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6016            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6017            if (si != null) {
6018                final ResolveInfo ri = new ResolveInfo();
6019                ri.serviceInfo = si;
6020                list.add(ri);
6021            }
6022            return list;
6023        }
6024
6025        // reader
6026        synchronized (mPackages) {
6027            String pkgName = intent.getPackage();
6028            if (pkgName == null) {
6029                return mServices.queryIntent(intent, resolvedType, flags, userId);
6030            }
6031            final PackageParser.Package pkg = mPackages.get(pkgName);
6032            if (pkg != null) {
6033                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6034                        userId);
6035            }
6036            return Collections.emptyList();
6037        }
6038    }
6039
6040    @Override
6041    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6042            String resolvedType, int flags, int userId) {
6043        return new ParceledListSlice<>(
6044                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6045    }
6046
6047    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6048            Intent intent, String resolvedType, int flags, int userId) {
6049        if (!sUserManager.exists(userId)) return Collections.emptyList();
6050        flags = updateFlagsForResolve(flags, userId, intent);
6051        ComponentName comp = intent.getComponent();
6052        if (comp == null) {
6053            if (intent.getSelector() != null) {
6054                intent = intent.getSelector();
6055                comp = intent.getComponent();
6056            }
6057        }
6058        if (comp != null) {
6059            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6060            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6061            if (pi != null) {
6062                final ResolveInfo ri = new ResolveInfo();
6063                ri.providerInfo = pi;
6064                list.add(ri);
6065            }
6066            return list;
6067        }
6068
6069        // reader
6070        synchronized (mPackages) {
6071            String pkgName = intent.getPackage();
6072            if (pkgName == null) {
6073                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6074            }
6075            final PackageParser.Package pkg = mPackages.get(pkgName);
6076            if (pkg != null) {
6077                return mProviders.queryIntentForPackage(
6078                        intent, resolvedType, flags, pkg.providers, userId);
6079            }
6080            return Collections.emptyList();
6081        }
6082    }
6083
6084    @Override
6085    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6086        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6087        flags = updateFlagsForPackage(flags, userId, null);
6088        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6089        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6090                true /* requireFullPermission */, false /* checkShell */,
6091                "get installed packages");
6092
6093        // writer
6094        synchronized (mPackages) {
6095            ArrayList<PackageInfo> list;
6096            if (listUninstalled) {
6097                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6098                for (PackageSetting ps : mSettings.mPackages.values()) {
6099                    final PackageInfo pi;
6100                    if (ps.pkg != null) {
6101                        pi = generatePackageInfo(ps, flags, userId);
6102                    } else {
6103                        pi = generatePackageInfo(ps, flags, userId);
6104                    }
6105                    if (pi != null) {
6106                        list.add(pi);
6107                    }
6108                }
6109            } else {
6110                list = new ArrayList<PackageInfo>(mPackages.size());
6111                for (PackageParser.Package p : mPackages.values()) {
6112                    final PackageInfo pi =
6113                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6114                    if (pi != null) {
6115                        list.add(pi);
6116                    }
6117                }
6118            }
6119
6120            return new ParceledListSlice<PackageInfo>(list);
6121        }
6122    }
6123
6124    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6125            String[] permissions, boolean[] tmp, int flags, int userId) {
6126        int numMatch = 0;
6127        final PermissionsState permissionsState = ps.getPermissionsState();
6128        for (int i=0; i<permissions.length; i++) {
6129            final String permission = permissions[i];
6130            if (permissionsState.hasPermission(permission, userId)) {
6131                tmp[i] = true;
6132                numMatch++;
6133            } else {
6134                tmp[i] = false;
6135            }
6136        }
6137        if (numMatch == 0) {
6138            return;
6139        }
6140        final PackageInfo pi;
6141        if (ps.pkg != null) {
6142            pi = generatePackageInfo(ps, flags, userId);
6143        } else {
6144            pi = generatePackageInfo(ps, flags, userId);
6145        }
6146        // The above might return null in cases of uninstalled apps or install-state
6147        // skew across users/profiles.
6148        if (pi != null) {
6149            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6150                if (numMatch == permissions.length) {
6151                    pi.requestedPermissions = permissions;
6152                } else {
6153                    pi.requestedPermissions = new String[numMatch];
6154                    numMatch = 0;
6155                    for (int i=0; i<permissions.length; i++) {
6156                        if (tmp[i]) {
6157                            pi.requestedPermissions[numMatch] = permissions[i];
6158                            numMatch++;
6159                        }
6160                    }
6161                }
6162            }
6163            list.add(pi);
6164        }
6165    }
6166
6167    @Override
6168    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6169            String[] permissions, int flags, int userId) {
6170        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6171        flags = updateFlagsForPackage(flags, userId, permissions);
6172        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6173
6174        // writer
6175        synchronized (mPackages) {
6176            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6177            boolean[] tmpBools = new boolean[permissions.length];
6178            if (listUninstalled) {
6179                for (PackageSetting ps : mSettings.mPackages.values()) {
6180                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6181                }
6182            } else {
6183                for (PackageParser.Package pkg : mPackages.values()) {
6184                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6185                    if (ps != null) {
6186                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6187                                userId);
6188                    }
6189                }
6190            }
6191
6192            return new ParceledListSlice<PackageInfo>(list);
6193        }
6194    }
6195
6196    @Override
6197    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6198        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6199        flags = updateFlagsForApplication(flags, userId, null);
6200        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6201
6202        // writer
6203        synchronized (mPackages) {
6204            ArrayList<ApplicationInfo> list;
6205            if (listUninstalled) {
6206                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6207                for (PackageSetting ps : mSettings.mPackages.values()) {
6208                    ApplicationInfo ai;
6209                    if (ps.pkg != null) {
6210                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6211                                ps.readUserState(userId), userId);
6212                    } else {
6213                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6214                    }
6215                    if (ai != null) {
6216                        list.add(ai);
6217                    }
6218                }
6219            } else {
6220                list = new ArrayList<ApplicationInfo>(mPackages.size());
6221                for (PackageParser.Package p : mPackages.values()) {
6222                    if (p.mExtras != null) {
6223                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6224                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6225                        if (ai != null) {
6226                            list.add(ai);
6227                        }
6228                    }
6229                }
6230            }
6231
6232            return new ParceledListSlice<ApplicationInfo>(list);
6233        }
6234    }
6235
6236    @Override
6237    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6238        if (DISABLE_EPHEMERAL_APPS) {
6239            return null;
6240        }
6241
6242        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6243                "getEphemeralApplications");
6244        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6245                true /* requireFullPermission */, false /* checkShell */,
6246                "getEphemeralApplications");
6247        synchronized (mPackages) {
6248            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6249                    .getEphemeralApplicationsLPw(userId);
6250            if (ephemeralApps != null) {
6251                return new ParceledListSlice<>(ephemeralApps);
6252            }
6253        }
6254        return null;
6255    }
6256
6257    @Override
6258    public boolean isEphemeralApplication(String packageName, int userId) {
6259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6260                true /* requireFullPermission */, false /* checkShell */,
6261                "isEphemeral");
6262        if (DISABLE_EPHEMERAL_APPS) {
6263            return false;
6264        }
6265
6266        if (!isCallerSameApp(packageName)) {
6267            return false;
6268        }
6269        synchronized (mPackages) {
6270            PackageParser.Package pkg = mPackages.get(packageName);
6271            if (pkg != null) {
6272                return pkg.applicationInfo.isEphemeralApp();
6273            }
6274        }
6275        return false;
6276    }
6277
6278    @Override
6279    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6280        if (DISABLE_EPHEMERAL_APPS) {
6281            return null;
6282        }
6283
6284        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6285                true /* requireFullPermission */, false /* checkShell */,
6286                "getCookie");
6287        if (!isCallerSameApp(packageName)) {
6288            return null;
6289        }
6290        synchronized (mPackages) {
6291            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6292                    packageName, userId);
6293        }
6294    }
6295
6296    @Override
6297    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6298        if (DISABLE_EPHEMERAL_APPS) {
6299            return true;
6300        }
6301
6302        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6303                true /* requireFullPermission */, true /* checkShell */,
6304                "setCookie");
6305        if (!isCallerSameApp(packageName)) {
6306            return false;
6307        }
6308        synchronized (mPackages) {
6309            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6310                    packageName, cookie, userId);
6311        }
6312    }
6313
6314    @Override
6315    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6316        if (DISABLE_EPHEMERAL_APPS) {
6317            return null;
6318        }
6319
6320        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6321                "getEphemeralApplicationIcon");
6322        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6323                true /* requireFullPermission */, false /* checkShell */,
6324                "getEphemeralApplicationIcon");
6325        synchronized (mPackages) {
6326            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6327                    packageName, userId);
6328        }
6329    }
6330
6331    private boolean isCallerSameApp(String packageName) {
6332        PackageParser.Package pkg = mPackages.get(packageName);
6333        return pkg != null
6334                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6335    }
6336
6337    @Override
6338    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6339        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6340    }
6341
6342    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6343        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6344
6345        // reader
6346        synchronized (mPackages) {
6347            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6348            final int userId = UserHandle.getCallingUserId();
6349            while (i.hasNext()) {
6350                final PackageParser.Package p = i.next();
6351                if (p.applicationInfo == null) continue;
6352
6353                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6354                        && !p.applicationInfo.isDirectBootAware();
6355                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6356                        && p.applicationInfo.isDirectBootAware();
6357
6358                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6359                        && (!mSafeMode || isSystemApp(p))
6360                        && (matchesUnaware || matchesAware)) {
6361                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6362                    if (ps != null) {
6363                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6364                                ps.readUserState(userId), userId);
6365                        if (ai != null) {
6366                            finalList.add(ai);
6367                        }
6368                    }
6369                }
6370            }
6371        }
6372
6373        return finalList;
6374    }
6375
6376    @Override
6377    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6378        if (!sUserManager.exists(userId)) return null;
6379        flags = updateFlagsForComponent(flags, userId, name);
6380        // reader
6381        synchronized (mPackages) {
6382            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6383            PackageSetting ps = provider != null
6384                    ? mSettings.mPackages.get(provider.owner.packageName)
6385                    : null;
6386            return ps != null
6387                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6388                    ? PackageParser.generateProviderInfo(provider, flags,
6389                            ps.readUserState(userId), userId)
6390                    : null;
6391        }
6392    }
6393
6394    /**
6395     * @deprecated
6396     */
6397    @Deprecated
6398    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6399        // reader
6400        synchronized (mPackages) {
6401            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6402                    .entrySet().iterator();
6403            final int userId = UserHandle.getCallingUserId();
6404            while (i.hasNext()) {
6405                Map.Entry<String, PackageParser.Provider> entry = i.next();
6406                PackageParser.Provider p = entry.getValue();
6407                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6408
6409                if (ps != null && p.syncable
6410                        && (!mSafeMode || (p.info.applicationInfo.flags
6411                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6412                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6413                            ps.readUserState(userId), userId);
6414                    if (info != null) {
6415                        outNames.add(entry.getKey());
6416                        outInfo.add(info);
6417                    }
6418                }
6419            }
6420        }
6421    }
6422
6423    @Override
6424    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6425            int uid, int flags) {
6426        final int userId = processName != null ? UserHandle.getUserId(uid)
6427                : UserHandle.getCallingUserId();
6428        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6429        flags = updateFlagsForComponent(flags, userId, processName);
6430
6431        ArrayList<ProviderInfo> finalList = null;
6432        // reader
6433        synchronized (mPackages) {
6434            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6435            while (i.hasNext()) {
6436                final PackageParser.Provider p = i.next();
6437                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6438                if (ps != null && p.info.authority != null
6439                        && (processName == null
6440                                || (p.info.processName.equals(processName)
6441                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6442                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6443                    if (finalList == null) {
6444                        finalList = new ArrayList<ProviderInfo>(3);
6445                    }
6446                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6447                            ps.readUserState(userId), userId);
6448                    if (info != null) {
6449                        finalList.add(info);
6450                    }
6451                }
6452            }
6453        }
6454
6455        if (finalList != null) {
6456            Collections.sort(finalList, mProviderInitOrderSorter);
6457            return new ParceledListSlice<ProviderInfo>(finalList);
6458        }
6459
6460        return ParceledListSlice.emptyList();
6461    }
6462
6463    @Override
6464    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6465        // reader
6466        synchronized (mPackages) {
6467            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6468            return PackageParser.generateInstrumentationInfo(i, flags);
6469        }
6470    }
6471
6472    @Override
6473    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6474            String targetPackage, int flags) {
6475        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6476    }
6477
6478    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6479            int flags) {
6480        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6481
6482        // reader
6483        synchronized (mPackages) {
6484            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6485            while (i.hasNext()) {
6486                final PackageParser.Instrumentation p = i.next();
6487                if (targetPackage == null
6488                        || targetPackage.equals(p.info.targetPackage)) {
6489                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6490                            flags);
6491                    if (ii != null) {
6492                        finalList.add(ii);
6493                    }
6494                }
6495            }
6496        }
6497
6498        return finalList;
6499    }
6500
6501    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6502        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6503        if (overlays == null) {
6504            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6505            return;
6506        }
6507        for (PackageParser.Package opkg : overlays.values()) {
6508            // Not much to do if idmap fails: we already logged the error
6509            // and we certainly don't want to abort installation of pkg simply
6510            // because an overlay didn't fit properly. For these reasons,
6511            // ignore the return value of createIdmapForPackagePairLI.
6512            createIdmapForPackagePairLI(pkg, opkg);
6513        }
6514    }
6515
6516    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6517            PackageParser.Package opkg) {
6518        if (!opkg.mTrustedOverlay) {
6519            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6520                    opkg.baseCodePath + ": overlay not trusted");
6521            return false;
6522        }
6523        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6524        if (overlaySet == null) {
6525            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6526                    opkg.baseCodePath + " but target package has no known overlays");
6527            return false;
6528        }
6529        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6530        // TODO: generate idmap for split APKs
6531        try {
6532            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6533        } catch (InstallerException e) {
6534            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6535                    + opkg.baseCodePath);
6536            return false;
6537        }
6538        PackageParser.Package[] overlayArray =
6539            overlaySet.values().toArray(new PackageParser.Package[0]);
6540        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6541            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6542                return p1.mOverlayPriority - p2.mOverlayPriority;
6543            }
6544        };
6545        Arrays.sort(overlayArray, cmp);
6546
6547        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6548        int i = 0;
6549        for (PackageParser.Package p : overlayArray) {
6550            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6551        }
6552        return true;
6553    }
6554
6555    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6556        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6557        try {
6558            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6559        } finally {
6560            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6561        }
6562    }
6563
6564    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6565        final File[] files = dir.listFiles();
6566        if (ArrayUtils.isEmpty(files)) {
6567            Log.d(TAG, "No files in app dir " + dir);
6568            return;
6569        }
6570
6571        if (DEBUG_PACKAGE_SCANNING) {
6572            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6573                    + " flags=0x" + Integer.toHexString(parseFlags));
6574        }
6575
6576        for (File file : files) {
6577            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6578                    && !PackageInstallerService.isStageName(file.getName());
6579            if (!isPackage) {
6580                // Ignore entries which are not packages
6581                continue;
6582            }
6583            try {
6584                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6585                        scanFlags, currentTime, null);
6586            } catch (PackageManagerException e) {
6587                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6588
6589                // Delete invalid userdata apps
6590                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6591                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6592                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6593                    removeCodePathLI(file);
6594                }
6595            }
6596        }
6597    }
6598
6599    private static File getSettingsProblemFile() {
6600        File dataDir = Environment.getDataDirectory();
6601        File systemDir = new File(dataDir, "system");
6602        File fname = new File(systemDir, "uiderrors.txt");
6603        return fname;
6604    }
6605
6606    static void reportSettingsProblem(int priority, String msg) {
6607        logCriticalInfo(priority, msg);
6608    }
6609
6610    static void logCriticalInfo(int priority, String msg) {
6611        Slog.println(priority, TAG, msg);
6612        EventLogTags.writePmCriticalInfo(msg);
6613        try {
6614            File fname = getSettingsProblemFile();
6615            FileOutputStream out = new FileOutputStream(fname, true);
6616            PrintWriter pw = new FastPrintWriter(out);
6617            SimpleDateFormat formatter = new SimpleDateFormat();
6618            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6619            pw.println(dateString + ": " + msg);
6620            pw.close();
6621            FileUtils.setPermissions(
6622                    fname.toString(),
6623                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6624                    -1, -1);
6625        } catch (java.io.IOException e) {
6626        }
6627    }
6628
6629    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6630            final int policyFlags) throws PackageManagerException {
6631        if (ps != null
6632                && ps.codePath.equals(srcFile)
6633                && ps.timeStamp == srcFile.lastModified()
6634                && !isCompatSignatureUpdateNeeded(pkg)
6635                && !isRecoverSignatureUpdateNeeded(pkg)) {
6636            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6637            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6638            ArraySet<PublicKey> signingKs;
6639            synchronized (mPackages) {
6640                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6641            }
6642            if (ps.signatures.mSignatures != null
6643                    && ps.signatures.mSignatures.length != 0
6644                    && signingKs != null) {
6645                // Optimization: reuse the existing cached certificates
6646                // if the package appears to be unchanged.
6647                pkg.mSignatures = ps.signatures.mSignatures;
6648                pkg.mSigningKeys = signingKs;
6649                return;
6650            }
6651
6652            Slog.w(TAG, "PackageSetting for " + ps.name
6653                    + " is missing signatures.  Collecting certs again to recover them.");
6654        } else {
6655            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6656        }
6657
6658        try {
6659            PackageParser.collectCertificates(pkg, policyFlags);
6660        } catch (PackageParserException e) {
6661            throw PackageManagerException.from(e);
6662        }
6663    }
6664
6665    /**
6666     *  Traces a package scan.
6667     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6668     */
6669    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6670            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6671        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6672        try {
6673            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6674        } finally {
6675            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6676        }
6677    }
6678
6679    /**
6680     *  Scans a package and returns the newly parsed package.
6681     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6682     */
6683    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6684            long currentTime, UserHandle user) throws PackageManagerException {
6685        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6686        PackageParser pp = new PackageParser();
6687        pp.setSeparateProcesses(mSeparateProcesses);
6688        pp.setOnlyCoreApps(mOnlyCore);
6689        pp.setDisplayMetrics(mMetrics);
6690
6691        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6692            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6693        }
6694
6695        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6696        final PackageParser.Package pkg;
6697        try {
6698            pkg = pp.parsePackage(scanFile, parseFlags);
6699        } catch (PackageParserException e) {
6700            throw PackageManagerException.from(e);
6701        } finally {
6702            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6703        }
6704
6705        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6706    }
6707
6708    /**
6709     *  Scans a package and returns the newly parsed package.
6710     *  @throws PackageManagerException on a parse error.
6711     */
6712    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6713            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6714            throws PackageManagerException {
6715        // If the package has children and this is the first dive in the function
6716        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6717        // packages (parent and children) would be successfully scanned before the
6718        // actual scan since scanning mutates internal state and we want to atomically
6719        // install the package and its children.
6720        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6721            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6722                scanFlags |= SCAN_CHECK_ONLY;
6723            }
6724        } else {
6725            scanFlags &= ~SCAN_CHECK_ONLY;
6726        }
6727
6728        // Scan the parent
6729        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6730                scanFlags, currentTime, user);
6731
6732        // Scan the children
6733        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6734        for (int i = 0; i < childCount; i++) {
6735            PackageParser.Package childPackage = pkg.childPackages.get(i);
6736            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6737                    currentTime, user);
6738        }
6739
6740
6741        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6742            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6743        }
6744
6745        return scannedPkg;
6746    }
6747
6748    /**
6749     *  Scans a package and returns the newly parsed package.
6750     *  @throws PackageManagerException on a parse error.
6751     */
6752    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6753            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6754            throws PackageManagerException {
6755        PackageSetting ps = null;
6756        PackageSetting updatedPkg;
6757        // reader
6758        synchronized (mPackages) {
6759            // Look to see if we already know about this package.
6760            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6761            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6762                // This package has been renamed to its original name.  Let's
6763                // use that.
6764                ps = mSettings.peekPackageLPr(oldName);
6765            }
6766            // If there was no original package, see one for the real package name.
6767            if (ps == null) {
6768                ps = mSettings.peekPackageLPr(pkg.packageName);
6769            }
6770            // Check to see if this package could be hiding/updating a system
6771            // package.  Must look for it either under the original or real
6772            // package name depending on our state.
6773            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6774            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6775
6776            // If this is a package we don't know about on the system partition, we
6777            // may need to remove disabled child packages on the system partition
6778            // or may need to not add child packages if the parent apk is updated
6779            // on the data partition and no longer defines this child package.
6780            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6781                // If this is a parent package for an updated system app and this system
6782                // app got an OTA update which no longer defines some of the child packages
6783                // we have to prune them from the disabled system packages.
6784                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6785                if (disabledPs != null) {
6786                    final int scannedChildCount = (pkg.childPackages != null)
6787                            ? pkg.childPackages.size() : 0;
6788                    final int disabledChildCount = disabledPs.childPackageNames != null
6789                            ? disabledPs.childPackageNames.size() : 0;
6790                    for (int i = 0; i < disabledChildCount; i++) {
6791                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6792                        boolean disabledPackageAvailable = false;
6793                        for (int j = 0; j < scannedChildCount; j++) {
6794                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6795                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6796                                disabledPackageAvailable = true;
6797                                break;
6798                            }
6799                         }
6800                         if (!disabledPackageAvailable) {
6801                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6802                         }
6803                    }
6804                }
6805            }
6806        }
6807
6808        boolean updatedPkgBetter = false;
6809        // First check if this is a system package that may involve an update
6810        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6811            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6812            // it needs to drop FLAG_PRIVILEGED.
6813            if (locationIsPrivileged(scanFile)) {
6814                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6815            } else {
6816                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6817            }
6818
6819            if (ps != null && !ps.codePath.equals(scanFile)) {
6820                // The path has changed from what was last scanned...  check the
6821                // version of the new path against what we have stored to determine
6822                // what to do.
6823                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6824                if (pkg.mVersionCode <= ps.versionCode) {
6825                    // The system package has been updated and the code path does not match
6826                    // Ignore entry. Skip it.
6827                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6828                            + " ignored: updated version " + ps.versionCode
6829                            + " better than this " + pkg.mVersionCode);
6830                    if (!updatedPkg.codePath.equals(scanFile)) {
6831                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6832                                + ps.name + " changing from " + updatedPkg.codePathString
6833                                + " to " + scanFile);
6834                        updatedPkg.codePath = scanFile;
6835                        updatedPkg.codePathString = scanFile.toString();
6836                        updatedPkg.resourcePath = scanFile;
6837                        updatedPkg.resourcePathString = scanFile.toString();
6838                    }
6839                    updatedPkg.pkg = pkg;
6840                    updatedPkg.versionCode = pkg.mVersionCode;
6841
6842                    // Update the disabled system child packages to point to the package too.
6843                    final int childCount = updatedPkg.childPackageNames != null
6844                            ? updatedPkg.childPackageNames.size() : 0;
6845                    for (int i = 0; i < childCount; i++) {
6846                        String childPackageName = updatedPkg.childPackageNames.get(i);
6847                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6848                                childPackageName);
6849                        if (updatedChildPkg != null) {
6850                            updatedChildPkg.pkg = pkg;
6851                            updatedChildPkg.versionCode = pkg.mVersionCode;
6852                        }
6853                    }
6854
6855                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6856                            + scanFile + " ignored: updated version " + ps.versionCode
6857                            + " better than this " + pkg.mVersionCode);
6858                } else {
6859                    // The current app on the system partition is better than
6860                    // what we have updated to on the data partition; switch
6861                    // back to the system partition version.
6862                    // At this point, its safely assumed that package installation for
6863                    // apps in system partition will go through. If not there won't be a working
6864                    // version of the app
6865                    // writer
6866                    synchronized (mPackages) {
6867                        // Just remove the loaded entries from package lists.
6868                        mPackages.remove(ps.name);
6869                    }
6870
6871                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6872                            + " reverting from " + ps.codePathString
6873                            + ": new version " + pkg.mVersionCode
6874                            + " better than installed " + ps.versionCode);
6875
6876                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6877                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6878                    synchronized (mInstallLock) {
6879                        args.cleanUpResourcesLI();
6880                    }
6881                    synchronized (mPackages) {
6882                        mSettings.enableSystemPackageLPw(ps.name);
6883                    }
6884                    updatedPkgBetter = true;
6885                }
6886            }
6887        }
6888
6889        if (updatedPkg != null) {
6890            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6891            // initially
6892            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6893
6894            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6895            // flag set initially
6896            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6897                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6898            }
6899        }
6900
6901        // Verify certificates against what was last scanned
6902        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6903
6904        /*
6905         * A new system app appeared, but we already had a non-system one of the
6906         * same name installed earlier.
6907         */
6908        boolean shouldHideSystemApp = false;
6909        if (updatedPkg == null && ps != null
6910                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6911            /*
6912             * Check to make sure the signatures match first. If they don't,
6913             * wipe the installed application and its data.
6914             */
6915            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6916                    != PackageManager.SIGNATURE_MATCH) {
6917                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6918                        + " signatures don't match existing userdata copy; removing");
6919                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6920                        "scanPackageInternalLI")) {
6921                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6922                }
6923                ps = null;
6924            } else {
6925                /*
6926                 * If the newly-added system app is an older version than the
6927                 * already installed version, hide it. It will be scanned later
6928                 * and re-added like an update.
6929                 */
6930                if (pkg.mVersionCode <= ps.versionCode) {
6931                    shouldHideSystemApp = true;
6932                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6933                            + " but new version " + pkg.mVersionCode + " better than installed "
6934                            + ps.versionCode + "; hiding system");
6935                } else {
6936                    /*
6937                     * The newly found system app is a newer version that the
6938                     * one previously installed. Simply remove the
6939                     * already-installed application and replace it with our own
6940                     * while keeping the application data.
6941                     */
6942                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6943                            + " reverting from " + ps.codePathString + ": new version "
6944                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6945                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6946                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6947                    synchronized (mInstallLock) {
6948                        args.cleanUpResourcesLI();
6949                    }
6950                }
6951            }
6952        }
6953
6954        // The apk is forward locked (not public) if its code and resources
6955        // are kept in different files. (except for app in either system or
6956        // vendor path).
6957        // TODO grab this value from PackageSettings
6958        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6959            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6960                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6961            }
6962        }
6963
6964        // TODO: extend to support forward-locked splits
6965        String resourcePath = null;
6966        String baseResourcePath = null;
6967        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6968            if (ps != null && ps.resourcePathString != null) {
6969                resourcePath = ps.resourcePathString;
6970                baseResourcePath = ps.resourcePathString;
6971            } else {
6972                // Should not happen at all. Just log an error.
6973                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6974            }
6975        } else {
6976            resourcePath = pkg.codePath;
6977            baseResourcePath = pkg.baseCodePath;
6978        }
6979
6980        // Set application objects path explicitly.
6981        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6982        pkg.setApplicationInfoCodePath(pkg.codePath);
6983        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6984        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6985        pkg.setApplicationInfoResourcePath(resourcePath);
6986        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6987        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6988
6989        // Note that we invoke the following method only if we are about to unpack an application
6990        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
6991                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6992
6993        /*
6994         * If the system app should be overridden by a previously installed
6995         * data, hide the system app now and let the /data/app scan pick it up
6996         * again.
6997         */
6998        if (shouldHideSystemApp) {
6999            synchronized (mPackages) {
7000                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7001            }
7002        }
7003
7004        return scannedPkg;
7005    }
7006
7007    private static String fixProcessName(String defProcessName,
7008            String processName, int uid) {
7009        if (processName == null) {
7010            return defProcessName;
7011        }
7012        return processName;
7013    }
7014
7015    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7016            throws PackageManagerException {
7017        if (pkgSetting.signatures.mSignatures != null) {
7018            // Already existing package. Make sure signatures match
7019            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7020                    == PackageManager.SIGNATURE_MATCH;
7021            if (!match) {
7022                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7023                        == PackageManager.SIGNATURE_MATCH;
7024            }
7025            if (!match) {
7026                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7027                        == PackageManager.SIGNATURE_MATCH;
7028            }
7029            if (!match) {
7030                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7031                        + pkg.packageName + " signatures do not match the "
7032                        + "previously installed version; ignoring!");
7033            }
7034        }
7035
7036        // Check for shared user signatures
7037        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7038            // Already existing package. Make sure signatures match
7039            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7040                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7041            if (!match) {
7042                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7043                        == PackageManager.SIGNATURE_MATCH;
7044            }
7045            if (!match) {
7046                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7047                        == PackageManager.SIGNATURE_MATCH;
7048            }
7049            if (!match) {
7050                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7051                        "Package " + pkg.packageName
7052                        + " has no signatures that match those in shared user "
7053                        + pkgSetting.sharedUser.name + "; ignoring!");
7054            }
7055        }
7056    }
7057
7058    /**
7059     * Enforces that only the system UID or root's UID can call a method exposed
7060     * via Binder.
7061     *
7062     * @param message used as message if SecurityException is thrown
7063     * @throws SecurityException if the caller is not system or root
7064     */
7065    private static final void enforceSystemOrRoot(String message) {
7066        final int uid = Binder.getCallingUid();
7067        if (uid != Process.SYSTEM_UID && uid != 0) {
7068            throw new SecurityException(message);
7069        }
7070    }
7071
7072    @Override
7073    public void performFstrimIfNeeded() {
7074        enforceSystemOrRoot("Only the system can request fstrim");
7075
7076        // Before everything else, see whether we need to fstrim.
7077        try {
7078            IMountService ms = PackageHelper.getMountService();
7079            if (ms != null) {
7080                final boolean isUpgrade = isUpgrade();
7081                boolean doTrim = isUpgrade;
7082                if (doTrim) {
7083                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7084                } else {
7085                    final long interval = android.provider.Settings.Global.getLong(
7086                            mContext.getContentResolver(),
7087                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7088                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7089                    if (interval > 0) {
7090                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7091                        if (timeSinceLast > interval) {
7092                            doTrim = true;
7093                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7094                                    + "; running immediately");
7095                        }
7096                    }
7097                }
7098                if (doTrim) {
7099                    if (!isFirstBoot()) {
7100                        try {
7101                            ActivityManagerNative.getDefault().showBootMessage(
7102                                    mContext.getResources().getString(
7103                                            R.string.android_upgrading_fstrim), true);
7104                        } catch (RemoteException e) {
7105                        }
7106                    }
7107                    ms.runMaintenance();
7108                }
7109            } else {
7110                Slog.e(TAG, "Mount service unavailable!");
7111            }
7112        } catch (RemoteException e) {
7113            // Can't happen; MountService is local
7114        }
7115    }
7116
7117    @Override
7118    public void updatePackagesIfNeeded() {
7119        enforceSystemOrRoot("Only the system can request package update");
7120
7121        // We need to re-extract after an OTA.
7122        boolean causeUpgrade = isUpgrade();
7123
7124        // First boot or factory reset.
7125        // Note: we also handle devices that are upgrading to N right now as if it is their
7126        //       first boot, as they do not have profile data.
7127        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7128
7129        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7130        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7131
7132        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7133            return;
7134        }
7135
7136        List<PackageParser.Package> pkgs;
7137        synchronized (mPackages) {
7138            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7139        }
7140
7141        int curr = 0;
7142        int total = pkgs.size();
7143        for (PackageParser.Package pkg : pkgs) {
7144            curr++;
7145
7146            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7147                if (DEBUG_DEXOPT) {
7148                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7149                }
7150                continue;
7151            }
7152
7153            if (DEBUG_DEXOPT) {
7154                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7155            }
7156
7157            if (!isFirstBoot()) {
7158                try {
7159                    ActivityManagerNative.getDefault().showBootMessage(
7160                            mContext.getResources().getString(R.string.android_upgrading_apk,
7161                                    curr, total), true);
7162                } catch (RemoteException e) {
7163                }
7164            }
7165
7166            performDexOpt(pkg.packageName,
7167                    null /* instructionSet */,
7168                    true /* checkProfiles */,
7169                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7170                    false /* force */);
7171        }
7172    }
7173
7174    @Override
7175    public void notifyPackageUse(String packageName, int reason) {
7176        synchronized (mPackages) {
7177            PackageParser.Package p = mPackages.get(packageName);
7178            if (p == null) {
7179                return;
7180            }
7181            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7182        }
7183    }
7184
7185    // TODO: this is not used nor needed. Delete it.
7186    @Override
7187    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7188        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7189                getFullCompilerFilter(), false /* force */);
7190    }
7191
7192    @Override
7193    public boolean performDexOpt(String packageName, String instructionSet,
7194            boolean checkProfiles, int compileReason, boolean force) {
7195        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7196                getCompilerFilterForReason(compileReason), force);
7197    }
7198
7199    @Override
7200    public boolean performDexOptMode(String packageName, String instructionSet,
7201            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7202        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7203                targetCompilerFilter, force);
7204    }
7205
7206    private boolean performDexOptTraced(String packageName, String instructionSet,
7207                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7208        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7209        try {
7210            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7211                    targetCompilerFilter, force);
7212        } finally {
7213            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7214        }
7215    }
7216
7217    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7218    // if the package can now be considered up to date for the given filter.
7219    private boolean performDexOptInternal(String packageName, String instructionSet,
7220                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7221        PackageParser.Package p;
7222        final String targetInstructionSet;
7223        synchronized (mPackages) {
7224            p = mPackages.get(packageName);
7225            if (p == null) {
7226                return false;
7227            }
7228            mPackageUsage.write(false);
7229
7230            targetInstructionSet = instructionSet != null ? instructionSet :
7231                    getPrimaryInstructionSet(p.applicationInfo);
7232        }
7233        long callingId = Binder.clearCallingIdentity();
7234        try {
7235            synchronized (mInstallLock) {
7236                final String[] instructionSets = new String[] { targetInstructionSet };
7237                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7238                        checkProfiles, targetCompilerFilter, force);
7239                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7240            }
7241        } finally {
7242            Binder.restoreCallingIdentity(callingId);
7243        }
7244    }
7245
7246    public ArraySet<String> getOptimizablePackages() {
7247        ArraySet<String> pkgs = new ArraySet<String>();
7248        synchronized (mPackages) {
7249            for (PackageParser.Package p : mPackages.values()) {
7250                if (PackageDexOptimizer.canOptimizePackage(p)) {
7251                    pkgs.add(p.packageName);
7252                }
7253            }
7254        }
7255        return pkgs;
7256    }
7257
7258    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7259            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7260            boolean force) {
7261        // Select the dex optimizer based on the force parameter.
7262        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7263        //       allocate an object here.
7264        PackageDexOptimizer pdo = force
7265                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7266                : mPackageDexOptimizer;
7267
7268        // Optimize all dependencies first. Note: we ignore the return value and march on
7269        // on errors.
7270        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7271        if (!deps.isEmpty()) {
7272            for (PackageParser.Package depPackage : deps) {
7273                // TODO: Analyze and investigate if we (should) profile libraries.
7274                // Currently this will do a full compilation of the library by default.
7275                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7276                        false /* checkProfiles */,
7277                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7278            }
7279        }
7280
7281        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7282                targetCompilerFilter);
7283    }
7284
7285    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7286        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7287            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7288            Set<String> collectedNames = new HashSet<>();
7289            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7290
7291            retValue.remove(p);
7292
7293            return retValue;
7294        } else {
7295            return Collections.emptyList();
7296        }
7297    }
7298
7299    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7300            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7301        if (!collectedNames.contains(p.packageName)) {
7302            collectedNames.add(p.packageName);
7303            collected.add(p);
7304
7305            if (p.usesLibraries != null) {
7306                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7307            }
7308            if (p.usesOptionalLibraries != null) {
7309                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7310                        collectedNames);
7311            }
7312        }
7313    }
7314
7315    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7316            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7317        for (String libName : libs) {
7318            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7319            if (libPkg != null) {
7320                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7321            }
7322        }
7323    }
7324
7325    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7326        synchronized (mPackages) {
7327            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7328            if (lib != null && lib.apk != null) {
7329                return mPackages.get(lib.apk);
7330            }
7331        }
7332        return null;
7333    }
7334
7335    public void shutdown() {
7336        mPackageUsage.write(true);
7337    }
7338
7339    @Override
7340    public void forceDexOpt(String packageName) {
7341        enforceSystemOrRoot("forceDexOpt");
7342
7343        PackageParser.Package pkg;
7344        synchronized (mPackages) {
7345            pkg = mPackages.get(packageName);
7346            if (pkg == null) {
7347                throw new IllegalArgumentException("Unknown package: " + packageName);
7348            }
7349        }
7350
7351        synchronized (mInstallLock) {
7352            final String[] instructionSets = new String[] {
7353                    getPrimaryInstructionSet(pkg.applicationInfo) };
7354
7355            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7356
7357            // Whoever is calling forceDexOpt wants a fully compiled package.
7358            // Don't use profiles since that may cause compilation to be skipped.
7359            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7360                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7361                    true /* force */);
7362
7363            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7364            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7365                throw new IllegalStateException("Failed to dexopt: " + res);
7366            }
7367        }
7368    }
7369
7370    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7371        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7372            Slog.w(TAG, "Unable to update from " + oldPkg.name
7373                    + " to " + newPkg.packageName
7374                    + ": old package not in system partition");
7375            return false;
7376        } else if (mPackages.get(oldPkg.name) != null) {
7377            Slog.w(TAG, "Unable to update from " + oldPkg.name
7378                    + " to " + newPkg.packageName
7379                    + ": old package still exists");
7380            return false;
7381        }
7382        return true;
7383    }
7384
7385    void removeCodePathLI(File codePath) {
7386        if (codePath.isDirectory()) {
7387            try {
7388                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7389            } catch (InstallerException e) {
7390                Slog.w(TAG, "Failed to remove code path", e);
7391            }
7392        } else {
7393            codePath.delete();
7394        }
7395    }
7396
7397    private int[] resolveUserIds(int userId) {
7398        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7399    }
7400
7401    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7402        if (pkg == null) {
7403            Slog.wtf(TAG, "Package was null!", new Throwable());
7404            return;
7405        }
7406        clearAppDataLeafLIF(pkg, userId, flags);
7407        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7408        for (int i = 0; i < childCount; i++) {
7409            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7410        }
7411    }
7412
7413    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7414        final PackageSetting ps;
7415        synchronized (mPackages) {
7416            ps = mSettings.mPackages.get(pkg.packageName);
7417        }
7418        for (int realUserId : resolveUserIds(userId)) {
7419            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7420            try {
7421                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7422                        ceDataInode);
7423            } catch (InstallerException e) {
7424                Slog.w(TAG, String.valueOf(e));
7425            }
7426        }
7427    }
7428
7429    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7430        if (pkg == null) {
7431            Slog.wtf(TAG, "Package was null!", new Throwable());
7432            return;
7433        }
7434        destroyAppDataLeafLIF(pkg, userId, flags);
7435        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7436        for (int i = 0; i < childCount; i++) {
7437            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7438        }
7439    }
7440
7441    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7442        final PackageSetting ps;
7443        synchronized (mPackages) {
7444            ps = mSettings.mPackages.get(pkg.packageName);
7445        }
7446        for (int realUserId : resolveUserIds(userId)) {
7447            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7448            try {
7449                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7450                        ceDataInode);
7451            } catch (InstallerException e) {
7452                Slog.w(TAG, String.valueOf(e));
7453            }
7454        }
7455    }
7456
7457    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7458        if (pkg == null) {
7459            Slog.wtf(TAG, "Package was null!", new Throwable());
7460            return;
7461        }
7462        destroyAppProfilesLeafLIF(pkg);
7463        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7464        for (int i = 0; i < childCount; i++) {
7465            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7466        }
7467    }
7468
7469    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7470        try {
7471            mInstaller.destroyAppProfiles(pkg.packageName);
7472        } catch (InstallerException e) {
7473            Slog.w(TAG, String.valueOf(e));
7474        }
7475    }
7476
7477    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7478        if (pkg == null) {
7479            Slog.wtf(TAG, "Package was null!", new Throwable());
7480            return;
7481        }
7482        clearAppProfilesLeafLIF(pkg);
7483        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7484        for (int i = 0; i < childCount; i++) {
7485            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7486        }
7487    }
7488
7489    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7490        try {
7491            mInstaller.clearAppProfiles(pkg.packageName);
7492        } catch (InstallerException e) {
7493            Slog.w(TAG, String.valueOf(e));
7494        }
7495    }
7496
7497    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7498            long lastUpdateTime) {
7499        // Set parent install/update time
7500        PackageSetting ps = (PackageSetting) pkg.mExtras;
7501        if (ps != null) {
7502            ps.firstInstallTime = firstInstallTime;
7503            ps.lastUpdateTime = lastUpdateTime;
7504        }
7505        // Set children install/update time
7506        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7507        for (int i = 0; i < childCount; i++) {
7508            PackageParser.Package childPkg = pkg.childPackages.get(i);
7509            ps = (PackageSetting) childPkg.mExtras;
7510            if (ps != null) {
7511                ps.firstInstallTime = firstInstallTime;
7512                ps.lastUpdateTime = lastUpdateTime;
7513            }
7514        }
7515    }
7516
7517    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7518            PackageParser.Package changingLib) {
7519        if (file.path != null) {
7520            usesLibraryFiles.add(file.path);
7521            return;
7522        }
7523        PackageParser.Package p = mPackages.get(file.apk);
7524        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7525            // If we are doing this while in the middle of updating a library apk,
7526            // then we need to make sure to use that new apk for determining the
7527            // dependencies here.  (We haven't yet finished committing the new apk
7528            // to the package manager state.)
7529            if (p == null || p.packageName.equals(changingLib.packageName)) {
7530                p = changingLib;
7531            }
7532        }
7533        if (p != null) {
7534            usesLibraryFiles.addAll(p.getAllCodePaths());
7535        }
7536    }
7537
7538    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7539            PackageParser.Package changingLib) throws PackageManagerException {
7540        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7541            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7542            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7543            for (int i=0; i<N; i++) {
7544                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7545                if (file == null) {
7546                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7547                            "Package " + pkg.packageName + " requires unavailable shared library "
7548                            + pkg.usesLibraries.get(i) + "; failing!");
7549                }
7550                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7551            }
7552            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7553            for (int i=0; i<N; i++) {
7554                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7555                if (file == null) {
7556                    Slog.w(TAG, "Package " + pkg.packageName
7557                            + " desires unavailable shared library "
7558                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7559                } else {
7560                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7561                }
7562            }
7563            N = usesLibraryFiles.size();
7564            if (N > 0) {
7565                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7566            } else {
7567                pkg.usesLibraryFiles = null;
7568            }
7569        }
7570    }
7571
7572    private static boolean hasString(List<String> list, List<String> which) {
7573        if (list == null) {
7574            return false;
7575        }
7576        for (int i=list.size()-1; i>=0; i--) {
7577            for (int j=which.size()-1; j>=0; j--) {
7578                if (which.get(j).equals(list.get(i))) {
7579                    return true;
7580                }
7581            }
7582        }
7583        return false;
7584    }
7585
7586    private void updateAllSharedLibrariesLPw() {
7587        for (PackageParser.Package pkg : mPackages.values()) {
7588            try {
7589                updateSharedLibrariesLPw(pkg, null);
7590            } catch (PackageManagerException e) {
7591                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7592            }
7593        }
7594    }
7595
7596    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7597            PackageParser.Package changingPkg) {
7598        ArrayList<PackageParser.Package> res = null;
7599        for (PackageParser.Package pkg : mPackages.values()) {
7600            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7601                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7602                if (res == null) {
7603                    res = new ArrayList<PackageParser.Package>();
7604                }
7605                res.add(pkg);
7606                try {
7607                    updateSharedLibrariesLPw(pkg, changingPkg);
7608                } catch (PackageManagerException e) {
7609                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7610                }
7611            }
7612        }
7613        return res;
7614    }
7615
7616    /**
7617     * Derive the value of the {@code cpuAbiOverride} based on the provided
7618     * value and an optional stored value from the package settings.
7619     */
7620    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7621        String cpuAbiOverride = null;
7622
7623        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7624            cpuAbiOverride = null;
7625        } else if (abiOverride != null) {
7626            cpuAbiOverride = abiOverride;
7627        } else if (settings != null) {
7628            cpuAbiOverride = settings.cpuAbiOverrideString;
7629        }
7630
7631        return cpuAbiOverride;
7632    }
7633
7634    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7635            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7636                    throws PackageManagerException {
7637        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7638        // If the package has children and this is the first dive in the function
7639        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7640        // whether all packages (parent and children) would be successfully scanned
7641        // before the actual scan since scanning mutates internal state and we want
7642        // to atomically install the package and its children.
7643        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7644            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7645                scanFlags |= SCAN_CHECK_ONLY;
7646            }
7647        } else {
7648            scanFlags &= ~SCAN_CHECK_ONLY;
7649        }
7650
7651        final PackageParser.Package scannedPkg;
7652        try {
7653            // Scan the parent
7654            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7655            // Scan the children
7656            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7657            for (int i = 0; i < childCount; i++) {
7658                PackageParser.Package childPkg = pkg.childPackages.get(i);
7659                scanPackageLI(childPkg, policyFlags,
7660                        scanFlags, currentTime, user);
7661            }
7662        } finally {
7663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7664        }
7665
7666        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7667            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7668        }
7669
7670        return scannedPkg;
7671    }
7672
7673    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7674            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7675        boolean success = false;
7676        try {
7677            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7678                    currentTime, user);
7679            success = true;
7680            return res;
7681        } finally {
7682            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7683                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7684                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7685                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7686                destroyAppProfilesLIF(pkg);
7687            }
7688        }
7689    }
7690
7691    /**
7692     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7693     */
7694    private static boolean apkHasCode(String fileName) {
7695        StrictJarFile jarFile = null;
7696        try {
7697            jarFile = new StrictJarFile(fileName,
7698                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7699            return jarFile.findEntry("classes.dex") != null;
7700        } catch (IOException ignore) {
7701        } finally {
7702            try {
7703                jarFile.close();
7704            } catch (IOException ignore) {}
7705        }
7706        return false;
7707    }
7708
7709    /**
7710     * Enforces code policy for the package. This ensures that if an APK has
7711     * declared hasCode="true" in its manifest that the APK actually contains
7712     * code.
7713     *
7714     * @throws PackageManagerException If bytecode could not be found when it should exist
7715     */
7716    private static void enforceCodePolicy(PackageParser.Package pkg)
7717            throws PackageManagerException {
7718        final boolean shouldHaveCode =
7719                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7720        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7721            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7722                    "Package " + pkg.baseCodePath + " code is missing");
7723        }
7724
7725        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7726            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7727                final boolean splitShouldHaveCode =
7728                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7729                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7730                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7731                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7732                }
7733            }
7734        }
7735    }
7736
7737    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7738            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7739            throws PackageManagerException {
7740        final File scanFile = new File(pkg.codePath);
7741        if (pkg.applicationInfo.getCodePath() == null ||
7742                pkg.applicationInfo.getResourcePath() == null) {
7743            // Bail out. The resource and code paths haven't been set.
7744            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7745                    "Code and resource paths haven't been set correctly");
7746        }
7747
7748        // Apply policy
7749        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7750            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7751            if (pkg.applicationInfo.isDirectBootAware()) {
7752                // we're direct boot aware; set for all components
7753                for (PackageParser.Service s : pkg.services) {
7754                    s.info.encryptionAware = s.info.directBootAware = true;
7755                }
7756                for (PackageParser.Provider p : pkg.providers) {
7757                    p.info.encryptionAware = p.info.directBootAware = true;
7758                }
7759                for (PackageParser.Activity a : pkg.activities) {
7760                    a.info.encryptionAware = a.info.directBootAware = true;
7761                }
7762                for (PackageParser.Activity r : pkg.receivers) {
7763                    r.info.encryptionAware = r.info.directBootAware = true;
7764                }
7765            }
7766        } else {
7767            // Only allow system apps to be flagged as core apps.
7768            pkg.coreApp = false;
7769            // clear flags not applicable to regular apps
7770            pkg.applicationInfo.privateFlags &=
7771                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7772            pkg.applicationInfo.privateFlags &=
7773                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7774        }
7775        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7776
7777        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7778            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7779        }
7780
7781        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7782            enforceCodePolicy(pkg);
7783        }
7784
7785        if (mCustomResolverComponentName != null &&
7786                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7787            setUpCustomResolverActivity(pkg);
7788        }
7789
7790        if (pkg.packageName.equals("android")) {
7791            synchronized (mPackages) {
7792                if (mAndroidApplication != null) {
7793                    Slog.w(TAG, "*************************************************");
7794                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7795                    Slog.w(TAG, " file=" + scanFile);
7796                    Slog.w(TAG, "*************************************************");
7797                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7798                            "Core android package being redefined.  Skipping.");
7799                }
7800
7801                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7802                    // Set up information for our fall-back user intent resolution activity.
7803                    mPlatformPackage = pkg;
7804                    pkg.mVersionCode = mSdkVersion;
7805                    mAndroidApplication = pkg.applicationInfo;
7806
7807                    if (!mResolverReplaced) {
7808                        mResolveActivity.applicationInfo = mAndroidApplication;
7809                        mResolveActivity.name = ResolverActivity.class.getName();
7810                        mResolveActivity.packageName = mAndroidApplication.packageName;
7811                        mResolveActivity.processName = "system:ui";
7812                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7813                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7814                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7815                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7816                        mResolveActivity.exported = true;
7817                        mResolveActivity.enabled = true;
7818                        mResolveInfo.activityInfo = mResolveActivity;
7819                        mResolveInfo.priority = 0;
7820                        mResolveInfo.preferredOrder = 0;
7821                        mResolveInfo.match = 0;
7822                        mResolveComponentName = new ComponentName(
7823                                mAndroidApplication.packageName, mResolveActivity.name);
7824                    }
7825                }
7826            }
7827        }
7828
7829        if (DEBUG_PACKAGE_SCANNING) {
7830            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7831                Log.d(TAG, "Scanning package " + pkg.packageName);
7832        }
7833
7834        synchronized (mPackages) {
7835            if (mPackages.containsKey(pkg.packageName)
7836                    || mSharedLibraries.containsKey(pkg.packageName)) {
7837                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7838                        "Application package " + pkg.packageName
7839                                + " already installed.  Skipping duplicate.");
7840            }
7841
7842            // If we're only installing presumed-existing packages, require that the
7843            // scanned APK is both already known and at the path previously established
7844            // for it.  Previously unknown packages we pick up normally, but if we have an
7845            // a priori expectation about this package's install presence, enforce it.
7846            // With a singular exception for new system packages. When an OTA contains
7847            // a new system package, we allow the codepath to change from a system location
7848            // to the user-installed location. If we don't allow this change, any newer,
7849            // user-installed version of the application will be ignored.
7850            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7851                if (mExpectingBetter.containsKey(pkg.packageName)) {
7852                    logCriticalInfo(Log.WARN,
7853                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7854                } else {
7855                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7856                    if (known != null) {
7857                        if (DEBUG_PACKAGE_SCANNING) {
7858                            Log.d(TAG, "Examining " + pkg.codePath
7859                                    + " and requiring known paths " + known.codePathString
7860                                    + " & " + known.resourcePathString);
7861                        }
7862                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7863                                || !pkg.applicationInfo.getResourcePath().equals(
7864                                known.resourcePathString)) {
7865                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7866                                    "Application package " + pkg.packageName
7867                                            + " found at " + pkg.applicationInfo.getCodePath()
7868                                            + " but expected at " + known.codePathString
7869                                            + "; ignoring.");
7870                        }
7871                    }
7872                }
7873            }
7874        }
7875
7876        // Initialize package source and resource directories
7877        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7878        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7879
7880        SharedUserSetting suid = null;
7881        PackageSetting pkgSetting = null;
7882
7883        if (!isSystemApp(pkg)) {
7884            // Only system apps can use these features.
7885            pkg.mOriginalPackages = null;
7886            pkg.mRealPackage = null;
7887            pkg.mAdoptPermissions = null;
7888        }
7889
7890        // Getting the package setting may have a side-effect, so if we
7891        // are only checking if scan would succeed, stash a copy of the
7892        // old setting to restore at the end.
7893        PackageSetting nonMutatedPs = null;
7894
7895        // writer
7896        synchronized (mPackages) {
7897            if (pkg.mSharedUserId != null) {
7898                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7899                if (suid == null) {
7900                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7901                            "Creating application package " + pkg.packageName
7902                            + " for shared user failed");
7903                }
7904                if (DEBUG_PACKAGE_SCANNING) {
7905                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7906                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7907                                + "): packages=" + suid.packages);
7908                }
7909            }
7910
7911            // Check if we are renaming from an original package name.
7912            PackageSetting origPackage = null;
7913            String realName = null;
7914            if (pkg.mOriginalPackages != null) {
7915                // This package may need to be renamed to a previously
7916                // installed name.  Let's check on that...
7917                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7918                if (pkg.mOriginalPackages.contains(renamed)) {
7919                    // This package had originally been installed as the
7920                    // original name, and we have already taken care of
7921                    // transitioning to the new one.  Just update the new
7922                    // one to continue using the old name.
7923                    realName = pkg.mRealPackage;
7924                    if (!pkg.packageName.equals(renamed)) {
7925                        // Callers into this function may have already taken
7926                        // care of renaming the package; only do it here if
7927                        // it is not already done.
7928                        pkg.setPackageName(renamed);
7929                    }
7930
7931                } else {
7932                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7933                        if ((origPackage = mSettings.peekPackageLPr(
7934                                pkg.mOriginalPackages.get(i))) != null) {
7935                            // We do have the package already installed under its
7936                            // original name...  should we use it?
7937                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7938                                // New package is not compatible with original.
7939                                origPackage = null;
7940                                continue;
7941                            } else if (origPackage.sharedUser != null) {
7942                                // Make sure uid is compatible between packages.
7943                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7944                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7945                                            + " to " + pkg.packageName + ": old uid "
7946                                            + origPackage.sharedUser.name
7947                                            + " differs from " + pkg.mSharedUserId);
7948                                    origPackage = null;
7949                                    continue;
7950                                }
7951                                // TODO: Add case when shared user id is added [b/28144775]
7952                            } else {
7953                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7954                                        + pkg.packageName + " to old name " + origPackage.name);
7955                            }
7956                            break;
7957                        }
7958                    }
7959                }
7960            }
7961
7962            if (mTransferedPackages.contains(pkg.packageName)) {
7963                Slog.w(TAG, "Package " + pkg.packageName
7964                        + " was transferred to another, but its .apk remains");
7965            }
7966
7967            // See comments in nonMutatedPs declaration
7968            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7969                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7970                if (foundPs != null) {
7971                    nonMutatedPs = new PackageSetting(foundPs);
7972                }
7973            }
7974
7975            // Just create the setting, don't add it yet. For already existing packages
7976            // the PkgSetting exists already and doesn't have to be created.
7977            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7978                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7979                    pkg.applicationInfo.primaryCpuAbi,
7980                    pkg.applicationInfo.secondaryCpuAbi,
7981                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7982                    user, false);
7983            if (pkgSetting == null) {
7984                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7985                        "Creating application package " + pkg.packageName + " failed");
7986            }
7987
7988            if (pkgSetting.origPackage != null) {
7989                // If we are first transitioning from an original package,
7990                // fix up the new package's name now.  We need to do this after
7991                // looking up the package under its new name, so getPackageLP
7992                // can take care of fiddling things correctly.
7993                pkg.setPackageName(origPackage.name);
7994
7995                // File a report about this.
7996                String msg = "New package " + pkgSetting.realName
7997                        + " renamed to replace old package " + pkgSetting.name;
7998                reportSettingsProblem(Log.WARN, msg);
7999
8000                // Make a note of it.
8001                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8002                    mTransferedPackages.add(origPackage.name);
8003                }
8004
8005                // No longer need to retain this.
8006                pkgSetting.origPackage = null;
8007            }
8008
8009            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8010                // Make a note of it.
8011                mTransferedPackages.add(pkg.packageName);
8012            }
8013
8014            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8015                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8016            }
8017
8018            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8019                // Check all shared libraries and map to their actual file path.
8020                // We only do this here for apps not on a system dir, because those
8021                // are the only ones that can fail an install due to this.  We
8022                // will take care of the system apps by updating all of their
8023                // library paths after the scan is done.
8024                updateSharedLibrariesLPw(pkg, null);
8025            }
8026
8027            if (mFoundPolicyFile) {
8028                SELinuxMMAC.assignSeinfoValue(pkg);
8029            }
8030
8031            pkg.applicationInfo.uid = pkgSetting.appId;
8032            pkg.mExtras = pkgSetting;
8033            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8034                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8035                    // We just determined the app is signed correctly, so bring
8036                    // over the latest parsed certs.
8037                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8038                } else {
8039                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8040                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8041                                "Package " + pkg.packageName + " upgrade keys do not match the "
8042                                + "previously installed version");
8043                    } else {
8044                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8045                        String msg = "System package " + pkg.packageName
8046                            + " signature changed; retaining data.";
8047                        reportSettingsProblem(Log.WARN, msg);
8048                    }
8049                }
8050            } else {
8051                try {
8052                    verifySignaturesLP(pkgSetting, pkg);
8053                    // We just determined the app is signed correctly, so bring
8054                    // over the latest parsed certs.
8055                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8056                } catch (PackageManagerException e) {
8057                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8058                        throw e;
8059                    }
8060                    // The signature has changed, but this package is in the system
8061                    // image...  let's recover!
8062                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8063                    // However...  if this package is part of a shared user, but it
8064                    // doesn't match the signature of the shared user, let's fail.
8065                    // What this means is that you can't change the signatures
8066                    // associated with an overall shared user, which doesn't seem all
8067                    // that unreasonable.
8068                    if (pkgSetting.sharedUser != null) {
8069                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8070                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8071                            throw new PackageManagerException(
8072                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8073                                            "Signature mismatch for shared user: "
8074                                            + pkgSetting.sharedUser);
8075                        }
8076                    }
8077                    // File a report about this.
8078                    String msg = "System package " + pkg.packageName
8079                        + " signature changed; retaining data.";
8080                    reportSettingsProblem(Log.WARN, msg);
8081                }
8082            }
8083            // Verify that this new package doesn't have any content providers
8084            // that conflict with existing packages.  Only do this if the
8085            // package isn't already installed, since we don't want to break
8086            // things that are installed.
8087            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8088                final int N = pkg.providers.size();
8089                int i;
8090                for (i=0; i<N; i++) {
8091                    PackageParser.Provider p = pkg.providers.get(i);
8092                    if (p.info.authority != null) {
8093                        String names[] = p.info.authority.split(";");
8094                        for (int j = 0; j < names.length; j++) {
8095                            if (mProvidersByAuthority.containsKey(names[j])) {
8096                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8097                                final String otherPackageName =
8098                                        ((other != null && other.getComponentName() != null) ?
8099                                                other.getComponentName().getPackageName() : "?");
8100                                throw new PackageManagerException(
8101                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8102                                                "Can't install because provider name " + names[j]
8103                                                + " (in package " + pkg.applicationInfo.packageName
8104                                                + ") is already used by " + otherPackageName);
8105                            }
8106                        }
8107                    }
8108                }
8109            }
8110
8111            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8112                // This package wants to adopt ownership of permissions from
8113                // another package.
8114                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8115                    final String origName = pkg.mAdoptPermissions.get(i);
8116                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8117                    if (orig != null) {
8118                        if (verifyPackageUpdateLPr(orig, pkg)) {
8119                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8120                                    + pkg.packageName);
8121                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8122                        }
8123                    }
8124                }
8125            }
8126        }
8127
8128        final String pkgName = pkg.packageName;
8129
8130        final long scanFileTime = scanFile.lastModified();
8131        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8132        pkg.applicationInfo.processName = fixProcessName(
8133                pkg.applicationInfo.packageName,
8134                pkg.applicationInfo.processName,
8135                pkg.applicationInfo.uid);
8136
8137        if (pkg != mPlatformPackage) {
8138            // Get all of our default paths setup
8139            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8140        }
8141
8142        final String path = scanFile.getPath();
8143        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8144
8145        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8146            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8147
8148            // Some system apps still use directory structure for native libraries
8149            // in which case we might end up not detecting abi solely based on apk
8150            // structure. Try to detect abi based on directory structure.
8151            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8152                    pkg.applicationInfo.primaryCpuAbi == null) {
8153                setBundledAppAbisAndRoots(pkg, pkgSetting);
8154                setNativeLibraryPaths(pkg);
8155            }
8156
8157        } else {
8158            if ((scanFlags & SCAN_MOVE) != 0) {
8159                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8160                // but we already have this packages package info in the PackageSetting. We just
8161                // use that and derive the native library path based on the new codepath.
8162                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8163                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8164            }
8165
8166            // Set native library paths again. For moves, the path will be updated based on the
8167            // ABIs we've determined above. For non-moves, the path will be updated based on the
8168            // ABIs we determined during compilation, but the path will depend on the final
8169            // package path (after the rename away from the stage path).
8170            setNativeLibraryPaths(pkg);
8171        }
8172
8173        // This is a special case for the "system" package, where the ABI is
8174        // dictated by the zygote configuration (and init.rc). We should keep track
8175        // of this ABI so that we can deal with "normal" applications that run under
8176        // the same UID correctly.
8177        if (mPlatformPackage == pkg) {
8178            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8179                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8180        }
8181
8182        // If there's a mismatch between the abi-override in the package setting
8183        // and the abiOverride specified for the install. Warn about this because we
8184        // would've already compiled the app without taking the package setting into
8185        // account.
8186        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8187            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8188                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8189                        " for package " + pkg.packageName);
8190            }
8191        }
8192
8193        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8194        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8195        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8196
8197        // Copy the derived override back to the parsed package, so that we can
8198        // update the package settings accordingly.
8199        pkg.cpuAbiOverride = cpuAbiOverride;
8200
8201        if (DEBUG_ABI_SELECTION) {
8202            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8203                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8204                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8205        }
8206
8207        // Push the derived path down into PackageSettings so we know what to
8208        // clean up at uninstall time.
8209        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8210
8211        if (DEBUG_ABI_SELECTION) {
8212            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8213                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8214                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8215        }
8216
8217        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8218            // We don't do this here during boot because we can do it all
8219            // at once after scanning all existing packages.
8220            //
8221            // We also do this *before* we perform dexopt on this package, so that
8222            // we can avoid redundant dexopts, and also to make sure we've got the
8223            // code and package path correct.
8224            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8225                    pkg, true /* boot complete */);
8226        }
8227
8228        if (mFactoryTest && pkg.requestedPermissions.contains(
8229                android.Manifest.permission.FACTORY_TEST)) {
8230            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8231        }
8232
8233        ArrayList<PackageParser.Package> clientLibPkgs = null;
8234
8235        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8236            if (nonMutatedPs != null) {
8237                synchronized (mPackages) {
8238                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8239                }
8240            }
8241            return pkg;
8242        }
8243
8244        // Only privileged apps and updated privileged apps can add child packages.
8245        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8246            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8247                throw new PackageManagerException("Only privileged apps and updated "
8248                        + "privileged apps can add child packages. Ignoring package "
8249                        + pkg.packageName);
8250            }
8251            final int childCount = pkg.childPackages.size();
8252            for (int i = 0; i < childCount; i++) {
8253                PackageParser.Package childPkg = pkg.childPackages.get(i);
8254                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8255                        childPkg.packageName)) {
8256                    throw new PackageManagerException("Cannot override a child package of "
8257                            + "another disabled system app. Ignoring package " + pkg.packageName);
8258                }
8259            }
8260        }
8261
8262        // writer
8263        synchronized (mPackages) {
8264            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8265                // Only system apps can add new shared libraries.
8266                if (pkg.libraryNames != null) {
8267                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8268                        String name = pkg.libraryNames.get(i);
8269                        boolean allowed = false;
8270                        if (pkg.isUpdatedSystemApp()) {
8271                            // New library entries can only be added through the
8272                            // system image.  This is important to get rid of a lot
8273                            // of nasty edge cases: for example if we allowed a non-
8274                            // system update of the app to add a library, then uninstalling
8275                            // the update would make the library go away, and assumptions
8276                            // we made such as through app install filtering would now
8277                            // have allowed apps on the device which aren't compatible
8278                            // with it.  Better to just have the restriction here, be
8279                            // conservative, and create many fewer cases that can negatively
8280                            // impact the user experience.
8281                            final PackageSetting sysPs = mSettings
8282                                    .getDisabledSystemPkgLPr(pkg.packageName);
8283                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8284                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8285                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8286                                        allowed = true;
8287                                        break;
8288                                    }
8289                                }
8290                            }
8291                        } else {
8292                            allowed = true;
8293                        }
8294                        if (allowed) {
8295                            if (!mSharedLibraries.containsKey(name)) {
8296                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8297                            } else if (!name.equals(pkg.packageName)) {
8298                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8299                                        + name + " already exists; skipping");
8300                            }
8301                        } else {
8302                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8303                                    + name + " that is not declared on system image; skipping");
8304                        }
8305                    }
8306                    if ((scanFlags & SCAN_BOOTING) == 0) {
8307                        // If we are not booting, we need to update any applications
8308                        // that are clients of our shared library.  If we are booting,
8309                        // this will all be done once the scan is complete.
8310                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8311                    }
8312                }
8313            }
8314        }
8315
8316        if ((scanFlags & SCAN_BOOTING) != 0) {
8317            // No apps can run during boot scan, so they don't need to be frozen
8318        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8319            // Caller asked to not kill app, so it's probably not frozen
8320        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8321            // Caller asked us to ignore frozen check for some reason; they
8322            // probably didn't know the package name
8323        } else {
8324            // We're doing major surgery on this package, so it better be frozen
8325            // right now to keep it from launching
8326            checkPackageFrozen(pkgName);
8327        }
8328
8329        // Also need to kill any apps that are dependent on the library.
8330        if (clientLibPkgs != null) {
8331            for (int i=0; i<clientLibPkgs.size(); i++) {
8332                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8333                killApplication(clientPkg.applicationInfo.packageName,
8334                        clientPkg.applicationInfo.uid, "update lib");
8335            }
8336        }
8337
8338        // Make sure we're not adding any bogus keyset info
8339        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8340        ksms.assertScannedPackageValid(pkg);
8341
8342        // writer
8343        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8344
8345        boolean createIdmapFailed = false;
8346        synchronized (mPackages) {
8347            // We don't expect installation to fail beyond this point
8348
8349            // Add the new setting to mSettings
8350            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8351            // Add the new setting to mPackages
8352            mPackages.put(pkg.applicationInfo.packageName, pkg);
8353            // Make sure we don't accidentally delete its data.
8354            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8355            while (iter.hasNext()) {
8356                PackageCleanItem item = iter.next();
8357                if (pkgName.equals(item.packageName)) {
8358                    iter.remove();
8359                }
8360            }
8361
8362            // Take care of first install / last update times.
8363            if (currentTime != 0) {
8364                if (pkgSetting.firstInstallTime == 0) {
8365                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8366                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8367                    pkgSetting.lastUpdateTime = currentTime;
8368                }
8369            } else if (pkgSetting.firstInstallTime == 0) {
8370                // We need *something*.  Take time time stamp of the file.
8371                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8372            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8373                if (scanFileTime != pkgSetting.timeStamp) {
8374                    // A package on the system image has changed; consider this
8375                    // to be an update.
8376                    pkgSetting.lastUpdateTime = scanFileTime;
8377                }
8378            }
8379
8380            // Add the package's KeySets to the global KeySetManagerService
8381            ksms.addScannedPackageLPw(pkg);
8382
8383            int N = pkg.providers.size();
8384            StringBuilder r = null;
8385            int i;
8386            for (i=0; i<N; i++) {
8387                PackageParser.Provider p = pkg.providers.get(i);
8388                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8389                        p.info.processName, pkg.applicationInfo.uid);
8390                mProviders.addProvider(p);
8391                p.syncable = p.info.isSyncable;
8392                if (p.info.authority != null) {
8393                    String names[] = p.info.authority.split(";");
8394                    p.info.authority = null;
8395                    for (int j = 0; j < names.length; j++) {
8396                        if (j == 1 && p.syncable) {
8397                            // We only want the first authority for a provider to possibly be
8398                            // syncable, so if we already added this provider using a different
8399                            // authority clear the syncable flag. We copy the provider before
8400                            // changing it because the mProviders object contains a reference
8401                            // to a provider that we don't want to change.
8402                            // Only do this for the second authority since the resulting provider
8403                            // object can be the same for all future authorities for this provider.
8404                            p = new PackageParser.Provider(p);
8405                            p.syncable = false;
8406                        }
8407                        if (!mProvidersByAuthority.containsKey(names[j])) {
8408                            mProvidersByAuthority.put(names[j], p);
8409                            if (p.info.authority == null) {
8410                                p.info.authority = names[j];
8411                            } else {
8412                                p.info.authority = p.info.authority + ";" + names[j];
8413                            }
8414                            if (DEBUG_PACKAGE_SCANNING) {
8415                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8416                                    Log.d(TAG, "Registered content provider: " + names[j]
8417                                            + ", className = " + p.info.name + ", isSyncable = "
8418                                            + p.info.isSyncable);
8419                            }
8420                        } else {
8421                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8422                            Slog.w(TAG, "Skipping provider name " + names[j] +
8423                                    " (in package " + pkg.applicationInfo.packageName +
8424                                    "): name already used by "
8425                                    + ((other != null && other.getComponentName() != null)
8426                                            ? other.getComponentName().getPackageName() : "?"));
8427                        }
8428                    }
8429                }
8430                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8431                    if (r == null) {
8432                        r = new StringBuilder(256);
8433                    } else {
8434                        r.append(' ');
8435                    }
8436                    r.append(p.info.name);
8437                }
8438            }
8439            if (r != null) {
8440                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8441            }
8442
8443            N = pkg.services.size();
8444            r = null;
8445            for (i=0; i<N; i++) {
8446                PackageParser.Service s = pkg.services.get(i);
8447                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8448                        s.info.processName, pkg.applicationInfo.uid);
8449                mServices.addService(s);
8450                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8451                    if (r == null) {
8452                        r = new StringBuilder(256);
8453                    } else {
8454                        r.append(' ');
8455                    }
8456                    r.append(s.info.name);
8457                }
8458            }
8459            if (r != null) {
8460                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8461            }
8462
8463            N = pkg.receivers.size();
8464            r = null;
8465            for (i=0; i<N; i++) {
8466                PackageParser.Activity a = pkg.receivers.get(i);
8467                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8468                        a.info.processName, pkg.applicationInfo.uid);
8469                mReceivers.addActivity(a, "receiver");
8470                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8471                    if (r == null) {
8472                        r = new StringBuilder(256);
8473                    } else {
8474                        r.append(' ');
8475                    }
8476                    r.append(a.info.name);
8477                }
8478            }
8479            if (r != null) {
8480                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8481            }
8482
8483            N = pkg.activities.size();
8484            r = null;
8485            for (i=0; i<N; i++) {
8486                PackageParser.Activity a = pkg.activities.get(i);
8487                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8488                        a.info.processName, pkg.applicationInfo.uid);
8489                mActivities.addActivity(a, "activity");
8490                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8491                    if (r == null) {
8492                        r = new StringBuilder(256);
8493                    } else {
8494                        r.append(' ');
8495                    }
8496                    r.append(a.info.name);
8497                }
8498            }
8499            if (r != null) {
8500                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8501            }
8502
8503            N = pkg.permissionGroups.size();
8504            r = null;
8505            for (i=0; i<N; i++) {
8506                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8507                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8508                if (cur == null) {
8509                    mPermissionGroups.put(pg.info.name, pg);
8510                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8511                        if (r == null) {
8512                            r = new StringBuilder(256);
8513                        } else {
8514                            r.append(' ');
8515                        }
8516                        r.append(pg.info.name);
8517                    }
8518                } else {
8519                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8520                            + pg.info.packageName + " ignored: original from "
8521                            + cur.info.packageName);
8522                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8523                        if (r == null) {
8524                            r = new StringBuilder(256);
8525                        } else {
8526                            r.append(' ');
8527                        }
8528                        r.append("DUP:");
8529                        r.append(pg.info.name);
8530                    }
8531                }
8532            }
8533            if (r != null) {
8534                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8535            }
8536
8537            N = pkg.permissions.size();
8538            r = null;
8539            for (i=0; i<N; i++) {
8540                PackageParser.Permission p = pkg.permissions.get(i);
8541
8542                // Assume by default that we did not install this permission into the system.
8543                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8544
8545                // Now that permission groups have a special meaning, we ignore permission
8546                // groups for legacy apps to prevent unexpected behavior. In particular,
8547                // permissions for one app being granted to someone just becase they happen
8548                // to be in a group defined by another app (before this had no implications).
8549                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8550                    p.group = mPermissionGroups.get(p.info.group);
8551                    // Warn for a permission in an unknown group.
8552                    if (p.info.group != null && p.group == null) {
8553                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8554                                + p.info.packageName + " in an unknown group " + p.info.group);
8555                    }
8556                }
8557
8558                ArrayMap<String, BasePermission> permissionMap =
8559                        p.tree ? mSettings.mPermissionTrees
8560                                : mSettings.mPermissions;
8561                BasePermission bp = permissionMap.get(p.info.name);
8562
8563                // Allow system apps to redefine non-system permissions
8564                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8565                    final boolean currentOwnerIsSystem = (bp.perm != null
8566                            && isSystemApp(bp.perm.owner));
8567                    if (isSystemApp(p.owner)) {
8568                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8569                            // It's a built-in permission and no owner, take ownership now
8570                            bp.packageSetting = pkgSetting;
8571                            bp.perm = p;
8572                            bp.uid = pkg.applicationInfo.uid;
8573                            bp.sourcePackage = p.info.packageName;
8574                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8575                        } else if (!currentOwnerIsSystem) {
8576                            String msg = "New decl " + p.owner + " of permission  "
8577                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8578                            reportSettingsProblem(Log.WARN, msg);
8579                            bp = null;
8580                        }
8581                    }
8582                }
8583
8584                if (bp == null) {
8585                    bp = new BasePermission(p.info.name, p.info.packageName,
8586                            BasePermission.TYPE_NORMAL);
8587                    permissionMap.put(p.info.name, bp);
8588                }
8589
8590                if (bp.perm == null) {
8591                    if (bp.sourcePackage == null
8592                            || bp.sourcePackage.equals(p.info.packageName)) {
8593                        BasePermission tree = findPermissionTreeLP(p.info.name);
8594                        if (tree == null
8595                                || tree.sourcePackage.equals(p.info.packageName)) {
8596                            bp.packageSetting = pkgSetting;
8597                            bp.perm = p;
8598                            bp.uid = pkg.applicationInfo.uid;
8599                            bp.sourcePackage = p.info.packageName;
8600                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8601                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8602                                if (r == null) {
8603                                    r = new StringBuilder(256);
8604                                } else {
8605                                    r.append(' ');
8606                                }
8607                                r.append(p.info.name);
8608                            }
8609                        } else {
8610                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8611                                    + p.info.packageName + " ignored: base tree "
8612                                    + tree.name + " is from package "
8613                                    + tree.sourcePackage);
8614                        }
8615                    } else {
8616                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8617                                + p.info.packageName + " ignored: original from "
8618                                + bp.sourcePackage);
8619                    }
8620                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8621                    if (r == null) {
8622                        r = new StringBuilder(256);
8623                    } else {
8624                        r.append(' ');
8625                    }
8626                    r.append("DUP:");
8627                    r.append(p.info.name);
8628                }
8629                if (bp.perm == p) {
8630                    bp.protectionLevel = p.info.protectionLevel;
8631                }
8632            }
8633
8634            if (r != null) {
8635                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8636            }
8637
8638            N = pkg.instrumentation.size();
8639            r = null;
8640            for (i=0; i<N; i++) {
8641                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8642                a.info.packageName = pkg.applicationInfo.packageName;
8643                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8644                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8645                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8646                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8647                a.info.dataDir = pkg.applicationInfo.dataDir;
8648                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8649                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8650
8651                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8652                // need other information about the application, like the ABI and what not ?
8653                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8654                mInstrumentation.put(a.getComponentName(), a);
8655                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8656                    if (r == null) {
8657                        r = new StringBuilder(256);
8658                    } else {
8659                        r.append(' ');
8660                    }
8661                    r.append(a.info.name);
8662                }
8663            }
8664            if (r != null) {
8665                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8666            }
8667
8668            if (pkg.protectedBroadcasts != null) {
8669                N = pkg.protectedBroadcasts.size();
8670                for (i=0; i<N; i++) {
8671                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8672                }
8673            }
8674
8675            pkgSetting.setTimeStamp(scanFileTime);
8676
8677            // Create idmap files for pairs of (packages, overlay packages).
8678            // Note: "android", ie framework-res.apk, is handled by native layers.
8679            if (pkg.mOverlayTarget != null) {
8680                // This is an overlay package.
8681                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8682                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8683                        mOverlays.put(pkg.mOverlayTarget,
8684                                new ArrayMap<String, PackageParser.Package>());
8685                    }
8686                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8687                    map.put(pkg.packageName, pkg);
8688                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8689                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8690                        createIdmapFailed = true;
8691                    }
8692                }
8693            } else if (mOverlays.containsKey(pkg.packageName) &&
8694                    !pkg.packageName.equals("android")) {
8695                // This is a regular package, with one or more known overlay packages.
8696                createIdmapsForPackageLI(pkg);
8697            }
8698        }
8699
8700        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8701
8702        if (createIdmapFailed) {
8703            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8704                    "scanPackageLI failed to createIdmap");
8705        }
8706        return pkg;
8707    }
8708
8709    /**
8710     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8711     * is derived purely on the basis of the contents of {@code scanFile} and
8712     * {@code cpuAbiOverride}.
8713     *
8714     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8715     */
8716    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8717                                 String cpuAbiOverride, boolean extractLibs)
8718            throws PackageManagerException {
8719        // TODO: We can probably be smarter about this stuff. For installed apps,
8720        // we can calculate this information at install time once and for all. For
8721        // system apps, we can probably assume that this information doesn't change
8722        // after the first boot scan. As things stand, we do lots of unnecessary work.
8723
8724        // Give ourselves some initial paths; we'll come back for another
8725        // pass once we've determined ABI below.
8726        setNativeLibraryPaths(pkg);
8727
8728        // We would never need to extract libs for forward-locked and external packages,
8729        // since the container service will do it for us. We shouldn't attempt to
8730        // extract libs from system app when it was not updated.
8731        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8732                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8733            extractLibs = false;
8734        }
8735
8736        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8737        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8738
8739        NativeLibraryHelper.Handle handle = null;
8740        try {
8741            handle = NativeLibraryHelper.Handle.create(pkg);
8742            // TODO(multiArch): This can be null for apps that didn't go through the
8743            // usual installation process. We can calculate it again, like we
8744            // do during install time.
8745            //
8746            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8747            // unnecessary.
8748            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8749
8750            // Null out the abis so that they can be recalculated.
8751            pkg.applicationInfo.primaryCpuAbi = null;
8752            pkg.applicationInfo.secondaryCpuAbi = null;
8753            if (isMultiArch(pkg.applicationInfo)) {
8754                // Warn if we've set an abiOverride for multi-lib packages..
8755                // By definition, we need to copy both 32 and 64 bit libraries for
8756                // such packages.
8757                if (pkg.cpuAbiOverride != null
8758                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8759                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8760                }
8761
8762                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8763                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8764                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8765                    if (extractLibs) {
8766                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8767                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8768                                useIsaSpecificSubdirs);
8769                    } else {
8770                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8771                    }
8772                }
8773
8774                maybeThrowExceptionForMultiArchCopy(
8775                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8776
8777                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8778                    if (extractLibs) {
8779                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8780                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8781                                useIsaSpecificSubdirs);
8782                    } else {
8783                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8784                    }
8785                }
8786
8787                maybeThrowExceptionForMultiArchCopy(
8788                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8789
8790                if (abi64 >= 0) {
8791                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8792                }
8793
8794                if (abi32 >= 0) {
8795                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8796                    if (abi64 >= 0) {
8797                        if (pkg.use32bitAbi) {
8798                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8799                            pkg.applicationInfo.primaryCpuAbi = abi;
8800                        } else {
8801                            pkg.applicationInfo.secondaryCpuAbi = abi;
8802                        }
8803                    } else {
8804                        pkg.applicationInfo.primaryCpuAbi = abi;
8805                    }
8806                }
8807
8808            } else {
8809                String[] abiList = (cpuAbiOverride != null) ?
8810                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8811
8812                // Enable gross and lame hacks for apps that are built with old
8813                // SDK tools. We must scan their APKs for renderscript bitcode and
8814                // not launch them if it's present. Don't bother checking on devices
8815                // that don't have 64 bit support.
8816                boolean needsRenderScriptOverride = false;
8817                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8818                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8819                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8820                    needsRenderScriptOverride = true;
8821                }
8822
8823                final int copyRet;
8824                if (extractLibs) {
8825                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8826                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8827                } else {
8828                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8829                }
8830
8831                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8832                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8833                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8834                }
8835
8836                if (copyRet >= 0) {
8837                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8838                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8839                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8840                } else if (needsRenderScriptOverride) {
8841                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8842                }
8843            }
8844        } catch (IOException ioe) {
8845            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8846        } finally {
8847            IoUtils.closeQuietly(handle);
8848        }
8849
8850        // Now that we've calculated the ABIs and determined if it's an internal app,
8851        // we will go ahead and populate the nativeLibraryPath.
8852        setNativeLibraryPaths(pkg);
8853    }
8854
8855    /**
8856     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8857     * i.e, so that all packages can be run inside a single process if required.
8858     *
8859     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8860     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8861     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8862     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8863     * updating a package that belongs to a shared user.
8864     *
8865     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8866     * adds unnecessary complexity.
8867     */
8868    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8869            PackageParser.Package scannedPackage, boolean bootComplete) {
8870        String requiredInstructionSet = null;
8871        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8872            requiredInstructionSet = VMRuntime.getInstructionSet(
8873                     scannedPackage.applicationInfo.primaryCpuAbi);
8874        }
8875
8876        PackageSetting requirer = null;
8877        for (PackageSetting ps : packagesForUser) {
8878            // If packagesForUser contains scannedPackage, we skip it. This will happen
8879            // when scannedPackage is an update of an existing package. Without this check,
8880            // we will never be able to change the ABI of any package belonging to a shared
8881            // user, even if it's compatible with other packages.
8882            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8883                if (ps.primaryCpuAbiString == null) {
8884                    continue;
8885                }
8886
8887                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8888                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8889                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8890                    // this but there's not much we can do.
8891                    String errorMessage = "Instruction set mismatch, "
8892                            + ((requirer == null) ? "[caller]" : requirer)
8893                            + " requires " + requiredInstructionSet + " whereas " + ps
8894                            + " requires " + instructionSet;
8895                    Slog.w(TAG, errorMessage);
8896                }
8897
8898                if (requiredInstructionSet == null) {
8899                    requiredInstructionSet = instructionSet;
8900                    requirer = ps;
8901                }
8902            }
8903        }
8904
8905        if (requiredInstructionSet != null) {
8906            String adjustedAbi;
8907            if (requirer != null) {
8908                // requirer != null implies that either scannedPackage was null or that scannedPackage
8909                // did not require an ABI, in which case we have to adjust scannedPackage to match
8910                // the ABI of the set (which is the same as requirer's ABI)
8911                adjustedAbi = requirer.primaryCpuAbiString;
8912                if (scannedPackage != null) {
8913                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8914                }
8915            } else {
8916                // requirer == null implies that we're updating all ABIs in the set to
8917                // match scannedPackage.
8918                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8919            }
8920
8921            for (PackageSetting ps : packagesForUser) {
8922                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8923                    if (ps.primaryCpuAbiString != null) {
8924                        continue;
8925                    }
8926
8927                    ps.primaryCpuAbiString = adjustedAbi;
8928                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8929                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8930                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8931                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8932                                + " (requirer="
8933                                + (requirer == null ? "null" : requirer.pkg.packageName)
8934                                + ", scannedPackage="
8935                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8936                                + ")");
8937                        try {
8938                            mInstaller.rmdex(ps.codePathString,
8939                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8940                        } catch (InstallerException ignored) {
8941                        }
8942                    }
8943                }
8944            }
8945        }
8946    }
8947
8948    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8949        synchronized (mPackages) {
8950            mResolverReplaced = true;
8951            // Set up information for custom user intent resolution activity.
8952            mResolveActivity.applicationInfo = pkg.applicationInfo;
8953            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8954            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8955            mResolveActivity.processName = pkg.applicationInfo.packageName;
8956            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8957            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8958                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8959            mResolveActivity.theme = 0;
8960            mResolveActivity.exported = true;
8961            mResolveActivity.enabled = true;
8962            mResolveInfo.activityInfo = mResolveActivity;
8963            mResolveInfo.priority = 0;
8964            mResolveInfo.preferredOrder = 0;
8965            mResolveInfo.match = 0;
8966            mResolveComponentName = mCustomResolverComponentName;
8967            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8968                    mResolveComponentName);
8969        }
8970    }
8971
8972    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8973        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8974
8975        // Set up information for ephemeral installer activity
8976        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8977        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8978        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8979        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8980        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8981        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8982                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8983        mEphemeralInstallerActivity.theme = 0;
8984        mEphemeralInstallerActivity.exported = true;
8985        mEphemeralInstallerActivity.enabled = true;
8986        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8987        mEphemeralInstallerInfo.priority = 0;
8988        mEphemeralInstallerInfo.preferredOrder = 0;
8989        mEphemeralInstallerInfo.match = 0;
8990
8991        if (DEBUG_EPHEMERAL) {
8992            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8993        }
8994    }
8995
8996    private static String calculateBundledApkRoot(final String codePathString) {
8997        final File codePath = new File(codePathString);
8998        final File codeRoot;
8999        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9000            codeRoot = Environment.getRootDirectory();
9001        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9002            codeRoot = Environment.getOemDirectory();
9003        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9004            codeRoot = Environment.getVendorDirectory();
9005        } else {
9006            // Unrecognized code path; take its top real segment as the apk root:
9007            // e.g. /something/app/blah.apk => /something
9008            try {
9009                File f = codePath.getCanonicalFile();
9010                File parent = f.getParentFile();    // non-null because codePath is a file
9011                File tmp;
9012                while ((tmp = parent.getParentFile()) != null) {
9013                    f = parent;
9014                    parent = tmp;
9015                }
9016                codeRoot = f;
9017                Slog.w(TAG, "Unrecognized code path "
9018                        + codePath + " - using " + codeRoot);
9019            } catch (IOException e) {
9020                // Can't canonicalize the code path -- shenanigans?
9021                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9022                return Environment.getRootDirectory().getPath();
9023            }
9024        }
9025        return codeRoot.getPath();
9026    }
9027
9028    /**
9029     * Derive and set the location of native libraries for the given package,
9030     * which varies depending on where and how the package was installed.
9031     */
9032    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9033        final ApplicationInfo info = pkg.applicationInfo;
9034        final String codePath = pkg.codePath;
9035        final File codeFile = new File(codePath);
9036        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9037        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9038
9039        info.nativeLibraryRootDir = null;
9040        info.nativeLibraryRootRequiresIsa = false;
9041        info.nativeLibraryDir = null;
9042        info.secondaryNativeLibraryDir = null;
9043
9044        if (isApkFile(codeFile)) {
9045            // Monolithic install
9046            if (bundledApp) {
9047                // If "/system/lib64/apkname" exists, assume that is the per-package
9048                // native library directory to use; otherwise use "/system/lib/apkname".
9049                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9050                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9051                        getPrimaryInstructionSet(info));
9052
9053                // This is a bundled system app so choose the path based on the ABI.
9054                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9055                // is just the default path.
9056                final String apkName = deriveCodePathName(codePath);
9057                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9058                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9059                        apkName).getAbsolutePath();
9060
9061                if (info.secondaryCpuAbi != null) {
9062                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9063                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9064                            secondaryLibDir, apkName).getAbsolutePath();
9065                }
9066            } else if (asecApp) {
9067                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9068                        .getAbsolutePath();
9069            } else {
9070                final String apkName = deriveCodePathName(codePath);
9071                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9072                        .getAbsolutePath();
9073            }
9074
9075            info.nativeLibraryRootRequiresIsa = false;
9076            info.nativeLibraryDir = info.nativeLibraryRootDir;
9077        } else {
9078            // Cluster install
9079            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9080            info.nativeLibraryRootRequiresIsa = true;
9081
9082            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9083                    getPrimaryInstructionSet(info)).getAbsolutePath();
9084
9085            if (info.secondaryCpuAbi != null) {
9086                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9087                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9088            }
9089        }
9090    }
9091
9092    /**
9093     * Calculate the abis and roots for a bundled app. These can uniquely
9094     * be determined from the contents of the system partition, i.e whether
9095     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9096     * of this information, and instead assume that the system was built
9097     * sensibly.
9098     */
9099    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9100                                           PackageSetting pkgSetting) {
9101        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9102
9103        // If "/system/lib64/apkname" exists, assume that is the per-package
9104        // native library directory to use; otherwise use "/system/lib/apkname".
9105        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9106        setBundledAppAbi(pkg, apkRoot, apkName);
9107        // pkgSetting might be null during rescan following uninstall of updates
9108        // to a bundled app, so accommodate that possibility.  The settings in
9109        // that case will be established later from the parsed package.
9110        //
9111        // If the settings aren't null, sync them up with what we've just derived.
9112        // note that apkRoot isn't stored in the package settings.
9113        if (pkgSetting != null) {
9114            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9115            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9116        }
9117    }
9118
9119    /**
9120     * Deduces the ABI of a bundled app and sets the relevant fields on the
9121     * parsed pkg object.
9122     *
9123     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9124     *        under which system libraries are installed.
9125     * @param apkName the name of the installed package.
9126     */
9127    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9128        final File codeFile = new File(pkg.codePath);
9129
9130        final boolean has64BitLibs;
9131        final boolean has32BitLibs;
9132        if (isApkFile(codeFile)) {
9133            // Monolithic install
9134            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9135            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9136        } else {
9137            // Cluster install
9138            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9139            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9140                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9141                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9142                has64BitLibs = (new File(rootDir, isa)).exists();
9143            } else {
9144                has64BitLibs = false;
9145            }
9146            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9147                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9148                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9149                has32BitLibs = (new File(rootDir, isa)).exists();
9150            } else {
9151                has32BitLibs = false;
9152            }
9153        }
9154
9155        if (has64BitLibs && !has32BitLibs) {
9156            // The package has 64 bit libs, but not 32 bit libs. Its primary
9157            // ABI should be 64 bit. We can safely assume here that the bundled
9158            // native libraries correspond to the most preferred ABI in the list.
9159
9160            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9161            pkg.applicationInfo.secondaryCpuAbi = null;
9162        } else if (has32BitLibs && !has64BitLibs) {
9163            // The package has 32 bit libs but not 64 bit libs. Its primary
9164            // ABI should be 32 bit.
9165
9166            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9167            pkg.applicationInfo.secondaryCpuAbi = null;
9168        } else if (has32BitLibs && has64BitLibs) {
9169            // The application has both 64 and 32 bit bundled libraries. We check
9170            // here that the app declares multiArch support, and warn if it doesn't.
9171            //
9172            // We will be lenient here and record both ABIs. The primary will be the
9173            // ABI that's higher on the list, i.e, a device that's configured to prefer
9174            // 64 bit apps will see a 64 bit primary ABI,
9175
9176            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9177                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9178            }
9179
9180            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9181                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9182                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9183            } else {
9184                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9185                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9186            }
9187        } else {
9188            pkg.applicationInfo.primaryCpuAbi = null;
9189            pkg.applicationInfo.secondaryCpuAbi = null;
9190        }
9191    }
9192
9193    private void killApplication(String pkgName, int appId, String reason) {
9194        // Request the ActivityManager to kill the process(only for existing packages)
9195        // so that we do not end up in a confused state while the user is still using the older
9196        // version of the application while the new one gets installed.
9197        final long token = Binder.clearCallingIdentity();
9198        try {
9199            IActivityManager am = ActivityManagerNative.getDefault();
9200            if (am != null) {
9201                try {
9202                    am.killApplicationWithAppId(pkgName, appId, reason);
9203                } catch (RemoteException e) {
9204                }
9205            }
9206        } finally {
9207            Binder.restoreCallingIdentity(token);
9208        }
9209    }
9210
9211    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9212        // Remove the parent package setting
9213        PackageSetting ps = (PackageSetting) pkg.mExtras;
9214        if (ps != null) {
9215            removePackageLI(ps, chatty);
9216        }
9217        // Remove the child package setting
9218        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9219        for (int i = 0; i < childCount; i++) {
9220            PackageParser.Package childPkg = pkg.childPackages.get(i);
9221            ps = (PackageSetting) childPkg.mExtras;
9222            if (ps != null) {
9223                removePackageLI(ps, chatty);
9224            }
9225        }
9226    }
9227
9228    void removePackageLI(PackageSetting ps, boolean chatty) {
9229        if (DEBUG_INSTALL) {
9230            if (chatty)
9231                Log.d(TAG, "Removing package " + ps.name);
9232        }
9233
9234        // writer
9235        synchronized (mPackages) {
9236            mPackages.remove(ps.name);
9237            final PackageParser.Package pkg = ps.pkg;
9238            if (pkg != null) {
9239                cleanPackageDataStructuresLILPw(pkg, chatty);
9240            }
9241        }
9242    }
9243
9244    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9245        if (DEBUG_INSTALL) {
9246            if (chatty)
9247                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9248        }
9249
9250        // writer
9251        synchronized (mPackages) {
9252            // Remove the parent package
9253            mPackages.remove(pkg.applicationInfo.packageName);
9254            cleanPackageDataStructuresLILPw(pkg, chatty);
9255
9256            // Remove the child packages
9257            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9258            for (int i = 0; i < childCount; i++) {
9259                PackageParser.Package childPkg = pkg.childPackages.get(i);
9260                mPackages.remove(childPkg.applicationInfo.packageName);
9261                cleanPackageDataStructuresLILPw(childPkg, chatty);
9262            }
9263        }
9264    }
9265
9266    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9267        int N = pkg.providers.size();
9268        StringBuilder r = null;
9269        int i;
9270        for (i=0; i<N; i++) {
9271            PackageParser.Provider p = pkg.providers.get(i);
9272            mProviders.removeProvider(p);
9273            if (p.info.authority == null) {
9274
9275                /* There was another ContentProvider with this authority when
9276                 * this app was installed so this authority is null,
9277                 * Ignore it as we don't have to unregister the provider.
9278                 */
9279                continue;
9280            }
9281            String names[] = p.info.authority.split(";");
9282            for (int j = 0; j < names.length; j++) {
9283                if (mProvidersByAuthority.get(names[j]) == p) {
9284                    mProvidersByAuthority.remove(names[j]);
9285                    if (DEBUG_REMOVE) {
9286                        if (chatty)
9287                            Log.d(TAG, "Unregistered content provider: " + names[j]
9288                                    + ", className = " + p.info.name + ", isSyncable = "
9289                                    + p.info.isSyncable);
9290                    }
9291                }
9292            }
9293            if (DEBUG_REMOVE && chatty) {
9294                if (r == null) {
9295                    r = new StringBuilder(256);
9296                } else {
9297                    r.append(' ');
9298                }
9299                r.append(p.info.name);
9300            }
9301        }
9302        if (r != null) {
9303            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9304        }
9305
9306        N = pkg.services.size();
9307        r = null;
9308        for (i=0; i<N; i++) {
9309            PackageParser.Service s = pkg.services.get(i);
9310            mServices.removeService(s);
9311            if (chatty) {
9312                if (r == null) {
9313                    r = new StringBuilder(256);
9314                } else {
9315                    r.append(' ');
9316                }
9317                r.append(s.info.name);
9318            }
9319        }
9320        if (r != null) {
9321            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9322        }
9323
9324        N = pkg.receivers.size();
9325        r = null;
9326        for (i=0; i<N; i++) {
9327            PackageParser.Activity a = pkg.receivers.get(i);
9328            mReceivers.removeActivity(a, "receiver");
9329            if (DEBUG_REMOVE && chatty) {
9330                if (r == null) {
9331                    r = new StringBuilder(256);
9332                } else {
9333                    r.append(' ');
9334                }
9335                r.append(a.info.name);
9336            }
9337        }
9338        if (r != null) {
9339            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9340        }
9341
9342        N = pkg.activities.size();
9343        r = null;
9344        for (i=0; i<N; i++) {
9345            PackageParser.Activity a = pkg.activities.get(i);
9346            mActivities.removeActivity(a, "activity");
9347            if (DEBUG_REMOVE && chatty) {
9348                if (r == null) {
9349                    r = new StringBuilder(256);
9350                } else {
9351                    r.append(' ');
9352                }
9353                r.append(a.info.name);
9354            }
9355        }
9356        if (r != null) {
9357            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9358        }
9359
9360        N = pkg.permissions.size();
9361        r = null;
9362        for (i=0; i<N; i++) {
9363            PackageParser.Permission p = pkg.permissions.get(i);
9364            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9365            if (bp == null) {
9366                bp = mSettings.mPermissionTrees.get(p.info.name);
9367            }
9368            if (bp != null && bp.perm == p) {
9369                bp.perm = null;
9370                if (DEBUG_REMOVE && chatty) {
9371                    if (r == null) {
9372                        r = new StringBuilder(256);
9373                    } else {
9374                        r.append(' ');
9375                    }
9376                    r.append(p.info.name);
9377                }
9378            }
9379            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9380                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9381                if (appOpPkgs != null) {
9382                    appOpPkgs.remove(pkg.packageName);
9383                }
9384            }
9385        }
9386        if (r != null) {
9387            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9388        }
9389
9390        N = pkg.requestedPermissions.size();
9391        r = null;
9392        for (i=0; i<N; i++) {
9393            String perm = pkg.requestedPermissions.get(i);
9394            BasePermission bp = mSettings.mPermissions.get(perm);
9395            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9396                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9397                if (appOpPkgs != null) {
9398                    appOpPkgs.remove(pkg.packageName);
9399                    if (appOpPkgs.isEmpty()) {
9400                        mAppOpPermissionPackages.remove(perm);
9401                    }
9402                }
9403            }
9404        }
9405        if (r != null) {
9406            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9407        }
9408
9409        N = pkg.instrumentation.size();
9410        r = null;
9411        for (i=0; i<N; i++) {
9412            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9413            mInstrumentation.remove(a.getComponentName());
9414            if (DEBUG_REMOVE && chatty) {
9415                if (r == null) {
9416                    r = new StringBuilder(256);
9417                } else {
9418                    r.append(' ');
9419                }
9420                r.append(a.info.name);
9421            }
9422        }
9423        if (r != null) {
9424            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9425        }
9426
9427        r = null;
9428        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9429            // Only system apps can hold shared libraries.
9430            if (pkg.libraryNames != null) {
9431                for (i=0; i<pkg.libraryNames.size(); i++) {
9432                    String name = pkg.libraryNames.get(i);
9433                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9434                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9435                        mSharedLibraries.remove(name);
9436                        if (DEBUG_REMOVE && chatty) {
9437                            if (r == null) {
9438                                r = new StringBuilder(256);
9439                            } else {
9440                                r.append(' ');
9441                            }
9442                            r.append(name);
9443                        }
9444                    }
9445                }
9446            }
9447        }
9448        if (r != null) {
9449            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9450        }
9451    }
9452
9453    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9454        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9455            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9456                return true;
9457            }
9458        }
9459        return false;
9460    }
9461
9462    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9463    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9464    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9465
9466    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9467        // Update the parent permissions
9468        updatePermissionsLPw(pkg.packageName, pkg, flags);
9469        // Update the child permissions
9470        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9471        for (int i = 0; i < childCount; i++) {
9472            PackageParser.Package childPkg = pkg.childPackages.get(i);
9473            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9474        }
9475    }
9476
9477    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9478            int flags) {
9479        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9480        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9481    }
9482
9483    private void updatePermissionsLPw(String changingPkg,
9484            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9485        // Make sure there are no dangling permission trees.
9486        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9487        while (it.hasNext()) {
9488            final BasePermission bp = it.next();
9489            if (bp.packageSetting == null) {
9490                // We may not yet have parsed the package, so just see if
9491                // we still know about its settings.
9492                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9493            }
9494            if (bp.packageSetting == null) {
9495                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9496                        + " from package " + bp.sourcePackage);
9497                it.remove();
9498            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9499                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9500                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9501                            + " from package " + bp.sourcePackage);
9502                    flags |= UPDATE_PERMISSIONS_ALL;
9503                    it.remove();
9504                }
9505            }
9506        }
9507
9508        // Make sure all dynamic permissions have been assigned to a package,
9509        // and make sure there are no dangling permissions.
9510        it = mSettings.mPermissions.values().iterator();
9511        while (it.hasNext()) {
9512            final BasePermission bp = it.next();
9513            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9514                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9515                        + bp.name + " pkg=" + bp.sourcePackage
9516                        + " info=" + bp.pendingInfo);
9517                if (bp.packageSetting == null && bp.pendingInfo != null) {
9518                    final BasePermission tree = findPermissionTreeLP(bp.name);
9519                    if (tree != null && tree.perm != null) {
9520                        bp.packageSetting = tree.packageSetting;
9521                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9522                                new PermissionInfo(bp.pendingInfo));
9523                        bp.perm.info.packageName = tree.perm.info.packageName;
9524                        bp.perm.info.name = bp.name;
9525                        bp.uid = tree.uid;
9526                    }
9527                }
9528            }
9529            if (bp.packageSetting == null) {
9530                // We may not yet have parsed the package, so just see if
9531                // we still know about its settings.
9532                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9533            }
9534            if (bp.packageSetting == null) {
9535                Slog.w(TAG, "Removing dangling permission: " + bp.name
9536                        + " from package " + bp.sourcePackage);
9537                it.remove();
9538            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9539                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9540                    Slog.i(TAG, "Removing old permission: " + bp.name
9541                            + " from package " + bp.sourcePackage);
9542                    flags |= UPDATE_PERMISSIONS_ALL;
9543                    it.remove();
9544                }
9545            }
9546        }
9547
9548        // Now update the permissions for all packages, in particular
9549        // replace the granted permissions of the system packages.
9550        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9551            for (PackageParser.Package pkg : mPackages.values()) {
9552                if (pkg != pkgInfo) {
9553                    // Only replace for packages on requested volume
9554                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9555                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9556                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9557                    grantPermissionsLPw(pkg, replace, changingPkg);
9558                }
9559            }
9560        }
9561
9562        if (pkgInfo != null) {
9563            // Only replace for packages on requested volume
9564            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9565            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9566                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9567            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9568        }
9569    }
9570
9571    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9572            String packageOfInterest) {
9573        // IMPORTANT: There are two types of permissions: install and runtime.
9574        // Install time permissions are granted when the app is installed to
9575        // all device users and users added in the future. Runtime permissions
9576        // are granted at runtime explicitly to specific users. Normal and signature
9577        // protected permissions are install time permissions. Dangerous permissions
9578        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9579        // otherwise they are runtime permissions. This function does not manage
9580        // runtime permissions except for the case an app targeting Lollipop MR1
9581        // being upgraded to target a newer SDK, in which case dangerous permissions
9582        // are transformed from install time to runtime ones.
9583
9584        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9585        if (ps == null) {
9586            return;
9587        }
9588
9589        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9590
9591        PermissionsState permissionsState = ps.getPermissionsState();
9592        PermissionsState origPermissions = permissionsState;
9593
9594        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9595
9596        boolean runtimePermissionsRevoked = false;
9597        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9598
9599        boolean changedInstallPermission = false;
9600
9601        if (replace) {
9602            ps.installPermissionsFixed = false;
9603            if (!ps.isSharedUser()) {
9604                origPermissions = new PermissionsState(permissionsState);
9605                permissionsState.reset();
9606            } else {
9607                // We need to know only about runtime permission changes since the
9608                // calling code always writes the install permissions state but
9609                // the runtime ones are written only if changed. The only cases of
9610                // changed runtime permissions here are promotion of an install to
9611                // runtime and revocation of a runtime from a shared user.
9612                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9613                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9614                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9615                    runtimePermissionsRevoked = true;
9616                }
9617            }
9618        }
9619
9620        permissionsState.setGlobalGids(mGlobalGids);
9621
9622        final int N = pkg.requestedPermissions.size();
9623        for (int i=0; i<N; i++) {
9624            final String name = pkg.requestedPermissions.get(i);
9625            final BasePermission bp = mSettings.mPermissions.get(name);
9626
9627            if (DEBUG_INSTALL) {
9628                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9629            }
9630
9631            if (bp == null || bp.packageSetting == null) {
9632                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9633                    Slog.w(TAG, "Unknown permission " + name
9634                            + " in package " + pkg.packageName);
9635                }
9636                continue;
9637            }
9638
9639            final String perm = bp.name;
9640            boolean allowedSig = false;
9641            int grant = GRANT_DENIED;
9642
9643            // Keep track of app op permissions.
9644            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9645                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9646                if (pkgs == null) {
9647                    pkgs = new ArraySet<>();
9648                    mAppOpPermissionPackages.put(bp.name, pkgs);
9649                }
9650                pkgs.add(pkg.packageName);
9651            }
9652
9653            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9654            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9655                    >= Build.VERSION_CODES.M;
9656            switch (level) {
9657                case PermissionInfo.PROTECTION_NORMAL: {
9658                    // For all apps normal permissions are install time ones.
9659                    grant = GRANT_INSTALL;
9660                } break;
9661
9662                case PermissionInfo.PROTECTION_DANGEROUS: {
9663                    // If a permission review is required for legacy apps we represent
9664                    // their permissions as always granted runtime ones since we need
9665                    // to keep the review required permission flag per user while an
9666                    // install permission's state is shared across all users.
9667                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9668                        // For legacy apps dangerous permissions are install time ones.
9669                        grant = GRANT_INSTALL;
9670                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9671                        // For legacy apps that became modern, install becomes runtime.
9672                        grant = GRANT_UPGRADE;
9673                    } else if (mPromoteSystemApps
9674                            && isSystemApp(ps)
9675                            && mExistingSystemPackages.contains(ps.name)) {
9676                        // For legacy system apps, install becomes runtime.
9677                        // We cannot check hasInstallPermission() for system apps since those
9678                        // permissions were granted implicitly and not persisted pre-M.
9679                        grant = GRANT_UPGRADE;
9680                    } else {
9681                        // For modern apps keep runtime permissions unchanged.
9682                        grant = GRANT_RUNTIME;
9683                    }
9684                } break;
9685
9686                case PermissionInfo.PROTECTION_SIGNATURE: {
9687                    // For all apps signature permissions are install time ones.
9688                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9689                    if (allowedSig) {
9690                        grant = GRANT_INSTALL;
9691                    }
9692                } break;
9693            }
9694
9695            if (DEBUG_INSTALL) {
9696                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9697            }
9698
9699            if (grant != GRANT_DENIED) {
9700                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9701                    // If this is an existing, non-system package, then
9702                    // we can't add any new permissions to it.
9703                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9704                        // Except...  if this is a permission that was added
9705                        // to the platform (note: need to only do this when
9706                        // updating the platform).
9707                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9708                            grant = GRANT_DENIED;
9709                        }
9710                    }
9711                }
9712
9713                switch (grant) {
9714                    case GRANT_INSTALL: {
9715                        // Revoke this as runtime permission to handle the case of
9716                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9717                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9718                            if (origPermissions.getRuntimePermissionState(
9719                                    bp.name, userId) != null) {
9720                                // Revoke the runtime permission and clear the flags.
9721                                origPermissions.revokeRuntimePermission(bp, userId);
9722                                origPermissions.updatePermissionFlags(bp, userId,
9723                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9724                                // If we revoked a permission permission, we have to write.
9725                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9726                                        changedRuntimePermissionUserIds, userId);
9727                            }
9728                        }
9729                        // Grant an install permission.
9730                        if (permissionsState.grantInstallPermission(bp) !=
9731                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9732                            changedInstallPermission = true;
9733                        }
9734                    } break;
9735
9736                    case GRANT_RUNTIME: {
9737                        // Grant previously granted runtime permissions.
9738                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9739                            PermissionState permissionState = origPermissions
9740                                    .getRuntimePermissionState(bp.name, userId);
9741                            int flags = permissionState != null
9742                                    ? permissionState.getFlags() : 0;
9743                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9744                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9745                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9746                                    // If we cannot put the permission as it was, we have to write.
9747                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9748                                            changedRuntimePermissionUserIds, userId);
9749                                }
9750                                // If the app supports runtime permissions no need for a review.
9751                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9752                                        && appSupportsRuntimePermissions
9753                                        && (flags & PackageManager
9754                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9755                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9756                                    // Since we changed the flags, we have to write.
9757                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9758                                            changedRuntimePermissionUserIds, userId);
9759                                }
9760                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9761                                    && !appSupportsRuntimePermissions) {
9762                                // For legacy apps that need a permission review, every new
9763                                // runtime permission is granted but it is pending a review.
9764                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9765                                    permissionsState.grantRuntimePermission(bp, userId);
9766                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9767                                    // We changed the permission and flags, hence have to write.
9768                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9769                                            changedRuntimePermissionUserIds, userId);
9770                                }
9771                            }
9772                            // Propagate the permission flags.
9773                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9774                        }
9775                    } break;
9776
9777                    case GRANT_UPGRADE: {
9778                        // Grant runtime permissions for a previously held install permission.
9779                        PermissionState permissionState = origPermissions
9780                                .getInstallPermissionState(bp.name);
9781                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9782
9783                        if (origPermissions.revokeInstallPermission(bp)
9784                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9785                            // We will be transferring the permission flags, so clear them.
9786                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9787                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9788                            changedInstallPermission = true;
9789                        }
9790
9791                        // If the permission is not to be promoted to runtime we ignore it and
9792                        // also its other flags as they are not applicable to install permissions.
9793                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9794                            for (int userId : currentUserIds) {
9795                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9796                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9797                                    // Transfer the permission flags.
9798                                    permissionsState.updatePermissionFlags(bp, userId,
9799                                            flags, flags);
9800                                    // If we granted the permission, we have to write.
9801                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9802                                            changedRuntimePermissionUserIds, userId);
9803                                }
9804                            }
9805                        }
9806                    } break;
9807
9808                    default: {
9809                        if (packageOfInterest == null
9810                                || packageOfInterest.equals(pkg.packageName)) {
9811                            Slog.w(TAG, "Not granting permission " + perm
9812                                    + " to package " + pkg.packageName
9813                                    + " because it was previously installed without");
9814                        }
9815                    } break;
9816                }
9817            } else {
9818                if (permissionsState.revokeInstallPermission(bp) !=
9819                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9820                    // Also drop the permission flags.
9821                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9822                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9823                    changedInstallPermission = true;
9824                    Slog.i(TAG, "Un-granting permission " + perm
9825                            + " from package " + pkg.packageName
9826                            + " (protectionLevel=" + bp.protectionLevel
9827                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9828                            + ")");
9829                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9830                    // Don't print warning for app op permissions, since it is fine for them
9831                    // not to be granted, there is a UI for the user to decide.
9832                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9833                        Slog.w(TAG, "Not granting permission " + perm
9834                                + " to package " + pkg.packageName
9835                                + " (protectionLevel=" + bp.protectionLevel
9836                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9837                                + ")");
9838                    }
9839                }
9840            }
9841        }
9842
9843        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9844                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9845            // This is the first that we have heard about this package, so the
9846            // permissions we have now selected are fixed until explicitly
9847            // changed.
9848            ps.installPermissionsFixed = true;
9849        }
9850
9851        // Persist the runtime permissions state for users with changes. If permissions
9852        // were revoked because no app in the shared user declares them we have to
9853        // write synchronously to avoid losing runtime permissions state.
9854        for (int userId : changedRuntimePermissionUserIds) {
9855            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9856        }
9857
9858        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9859    }
9860
9861    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9862        boolean allowed = false;
9863        final int NP = PackageParser.NEW_PERMISSIONS.length;
9864        for (int ip=0; ip<NP; ip++) {
9865            final PackageParser.NewPermissionInfo npi
9866                    = PackageParser.NEW_PERMISSIONS[ip];
9867            if (npi.name.equals(perm)
9868                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9869                allowed = true;
9870                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9871                        + pkg.packageName);
9872                break;
9873            }
9874        }
9875        return allowed;
9876    }
9877
9878    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9879            BasePermission bp, PermissionsState origPermissions) {
9880        boolean allowed;
9881        allowed = (compareSignatures(
9882                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9883                        == PackageManager.SIGNATURE_MATCH)
9884                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9885                        == PackageManager.SIGNATURE_MATCH);
9886        if (!allowed && (bp.protectionLevel
9887                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9888            if (isSystemApp(pkg)) {
9889                // For updated system applications, a system permission
9890                // is granted only if it had been defined by the original application.
9891                if (pkg.isUpdatedSystemApp()) {
9892                    final PackageSetting sysPs = mSettings
9893                            .getDisabledSystemPkgLPr(pkg.packageName);
9894                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9895                        // If the original was granted this permission, we take
9896                        // that grant decision as read and propagate it to the
9897                        // update.
9898                        if (sysPs.isPrivileged()) {
9899                            allowed = true;
9900                        }
9901                    } else {
9902                        // The system apk may have been updated with an older
9903                        // version of the one on the data partition, but which
9904                        // granted a new system permission that it didn't have
9905                        // before.  In this case we do want to allow the app to
9906                        // now get the new permission if the ancestral apk is
9907                        // privileged to get it.
9908                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9909                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9910                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9911                                    allowed = true;
9912                                    break;
9913                                }
9914                            }
9915                        }
9916                        // Also if a privileged parent package on the system image or any of
9917                        // its children requested a privileged permission, the updated child
9918                        // packages can also get the permission.
9919                        if (pkg.parentPackage != null) {
9920                            final PackageSetting disabledSysParentPs = mSettings
9921                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9922                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9923                                    && disabledSysParentPs.isPrivileged()) {
9924                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9925                                    allowed = true;
9926                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9927                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9928                                    for (int i = 0; i < count; i++) {
9929                                        PackageParser.Package disabledSysChildPkg =
9930                                                disabledSysParentPs.pkg.childPackages.get(i);
9931                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9932                                                perm)) {
9933                                            allowed = true;
9934                                            break;
9935                                        }
9936                                    }
9937                                }
9938                            }
9939                        }
9940                    }
9941                } else {
9942                    allowed = isPrivilegedApp(pkg);
9943                }
9944            }
9945        }
9946        if (!allowed) {
9947            if (!allowed && (bp.protectionLevel
9948                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9949                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9950                // If this was a previously normal/dangerous permission that got moved
9951                // to a system permission as part of the runtime permission redesign, then
9952                // we still want to blindly grant it to old apps.
9953                allowed = true;
9954            }
9955            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9956                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9957                // If this permission is to be granted to the system installer and
9958                // this app is an installer, then it gets the permission.
9959                allowed = true;
9960            }
9961            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9962                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9963                // If this permission is to be granted to the system verifier and
9964                // this app is a verifier, then it gets the permission.
9965                allowed = true;
9966            }
9967            if (!allowed && (bp.protectionLevel
9968                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9969                    && isSystemApp(pkg)) {
9970                // Any pre-installed system app is allowed to get this permission.
9971                allowed = true;
9972            }
9973            if (!allowed && (bp.protectionLevel
9974                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9975                // For development permissions, a development permission
9976                // is granted only if it was already granted.
9977                allowed = origPermissions.hasInstallPermission(perm);
9978            }
9979            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
9980                    && pkg.packageName.equals(mSetupWizardPackage)) {
9981                // If this permission is to be granted to the system setup wizard and
9982                // this app is a setup wizard, then it gets the permission.
9983                allowed = true;
9984            }
9985        }
9986        return allowed;
9987    }
9988
9989    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9990        final int permCount = pkg.requestedPermissions.size();
9991        for (int j = 0; j < permCount; j++) {
9992            String requestedPermission = pkg.requestedPermissions.get(j);
9993            if (permission.equals(requestedPermission)) {
9994                return true;
9995            }
9996        }
9997        return false;
9998    }
9999
10000    final class ActivityIntentResolver
10001            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10002        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10003                boolean defaultOnly, int userId) {
10004            if (!sUserManager.exists(userId)) return null;
10005            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10006            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10007        }
10008
10009        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10010                int userId) {
10011            if (!sUserManager.exists(userId)) return null;
10012            mFlags = flags;
10013            return super.queryIntent(intent, resolvedType,
10014                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10015        }
10016
10017        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10018                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10019            if (!sUserManager.exists(userId)) return null;
10020            if (packageActivities == null) {
10021                return null;
10022            }
10023            mFlags = flags;
10024            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10025            final int N = packageActivities.size();
10026            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10027                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10028
10029            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10030            for (int i = 0; i < N; ++i) {
10031                intentFilters = packageActivities.get(i).intents;
10032                if (intentFilters != null && intentFilters.size() > 0) {
10033                    PackageParser.ActivityIntentInfo[] array =
10034                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10035                    intentFilters.toArray(array);
10036                    listCut.add(array);
10037                }
10038            }
10039            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10040        }
10041
10042        /**
10043         * Finds a privileged activity that matches the specified activity names.
10044         */
10045        private PackageParser.Activity findMatchingActivity(
10046                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10047            for (PackageParser.Activity sysActivity : activityList) {
10048                if (sysActivity.info.name.equals(activityInfo.name)) {
10049                    return sysActivity;
10050                }
10051                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10052                    return sysActivity;
10053                }
10054                if (sysActivity.info.targetActivity != null) {
10055                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10056                        return sysActivity;
10057                    }
10058                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10059                        return sysActivity;
10060                    }
10061                }
10062            }
10063            return null;
10064        }
10065
10066        public class IterGenerator<E> {
10067            public Iterator<E> generate(ActivityIntentInfo info) {
10068                return null;
10069            }
10070        }
10071
10072        public class ActionIterGenerator extends IterGenerator<String> {
10073            @Override
10074            public Iterator<String> generate(ActivityIntentInfo info) {
10075                return info.actionsIterator();
10076            }
10077        }
10078
10079        public class CategoriesIterGenerator extends IterGenerator<String> {
10080            @Override
10081            public Iterator<String> generate(ActivityIntentInfo info) {
10082                return info.categoriesIterator();
10083            }
10084        }
10085
10086        public class SchemesIterGenerator extends IterGenerator<String> {
10087            @Override
10088            public Iterator<String> generate(ActivityIntentInfo info) {
10089                return info.schemesIterator();
10090            }
10091        }
10092
10093        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10094            @Override
10095            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10096                return info.authoritiesIterator();
10097            }
10098        }
10099
10100        /**
10101         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10102         * MODIFIED. Do not pass in a list that should not be changed.
10103         */
10104        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10105                IterGenerator<T> generator, Iterator<T> searchIterator) {
10106            // loop through the set of actions; every one must be found in the intent filter
10107            while (searchIterator.hasNext()) {
10108                // we must have at least one filter in the list to consider a match
10109                if (intentList.size() == 0) {
10110                    break;
10111                }
10112
10113                final T searchAction = searchIterator.next();
10114
10115                // loop through the set of intent filters
10116                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10117                while (intentIter.hasNext()) {
10118                    final ActivityIntentInfo intentInfo = intentIter.next();
10119                    boolean selectionFound = false;
10120
10121                    // loop through the intent filter's selection criteria; at least one
10122                    // of them must match the searched criteria
10123                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10124                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10125                        final T intentSelection = intentSelectionIter.next();
10126                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10127                            selectionFound = true;
10128                            break;
10129                        }
10130                    }
10131
10132                    // the selection criteria wasn't found in this filter's set; this filter
10133                    // is not a potential match
10134                    if (!selectionFound) {
10135                        intentIter.remove();
10136                    }
10137                }
10138            }
10139        }
10140
10141        private boolean isProtectedAction(ActivityIntentInfo filter) {
10142            final Iterator<String> actionsIter = filter.actionsIterator();
10143            while (actionsIter != null && actionsIter.hasNext()) {
10144                final String filterAction = actionsIter.next();
10145                if (PROTECTED_ACTIONS.contains(filterAction)) {
10146                    return true;
10147                }
10148            }
10149            return false;
10150        }
10151
10152        /**
10153         * Adjusts the priority of the given intent filter according to policy.
10154         * <p>
10155         * <ul>
10156         * <li>The priority for non privileged applications is capped to '0'</li>
10157         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10158         * <li>The priority for unbundled updates to privileged applications is capped to the
10159         *      priority defined on the system partition</li>
10160         * </ul>
10161         * <p>
10162         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10163         * allowed to obtain any priority on any action.
10164         */
10165        private void adjustPriority(
10166                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10167            // nothing to do; priority is fine as-is
10168            if (intent.getPriority() <= 0) {
10169                return;
10170            }
10171
10172            final ActivityInfo activityInfo = intent.activity.info;
10173            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10174
10175            final boolean privilegedApp =
10176                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10177            if (!privilegedApp) {
10178                // non-privileged applications can never define a priority >0
10179                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10180                        + " package: " + applicationInfo.packageName
10181                        + " activity: " + intent.activity.className
10182                        + " origPrio: " + intent.getPriority());
10183                intent.setPriority(0);
10184                return;
10185            }
10186
10187            if (systemActivities == null) {
10188                // the system package is not disabled; we're parsing the system partition
10189                if (isProtectedAction(intent)) {
10190                    if (mDeferProtectedFilters) {
10191                        // We can't deal with these just yet. No component should ever obtain a
10192                        // >0 priority for a protected actions, with ONE exception -- the setup
10193                        // wizard. The setup wizard, however, cannot be known until we're able to
10194                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10195                        // until all intent filters have been processed. Chicken, meet egg.
10196                        // Let the filter temporarily have a high priority and rectify the
10197                        // priorities after all system packages have been scanned.
10198                        mProtectedFilters.add(intent);
10199                        if (DEBUG_FILTERS) {
10200                            Slog.i(TAG, "Protected action; save for later;"
10201                                    + " package: " + applicationInfo.packageName
10202                                    + " activity: " + intent.activity.className
10203                                    + " origPrio: " + intent.getPriority());
10204                        }
10205                        return;
10206                    } else {
10207                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10208                            Slog.i(TAG, "No setup wizard;"
10209                                + " All protected intents capped to priority 0");
10210                        }
10211                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10212                            if (DEBUG_FILTERS) {
10213                                Slog.i(TAG, "Found setup wizard;"
10214                                    + " allow priority " + intent.getPriority() + ";"
10215                                    + " package: " + intent.activity.info.packageName
10216                                    + " activity: " + intent.activity.className
10217                                    + " priority: " + intent.getPriority());
10218                            }
10219                            // setup wizard gets whatever it wants
10220                            return;
10221                        }
10222                        Slog.w(TAG, "Protected action; cap priority to 0;"
10223                                + " package: " + intent.activity.info.packageName
10224                                + " activity: " + intent.activity.className
10225                                + " origPrio: " + intent.getPriority());
10226                        intent.setPriority(0);
10227                        return;
10228                    }
10229                }
10230                // privileged apps on the system image get whatever priority they request
10231                return;
10232            }
10233
10234            // privileged app unbundled update ... try to find the same activity
10235            final PackageParser.Activity foundActivity =
10236                    findMatchingActivity(systemActivities, activityInfo);
10237            if (foundActivity == null) {
10238                // this is a new activity; it cannot obtain >0 priority
10239                if (DEBUG_FILTERS) {
10240                    Slog.i(TAG, "New activity; cap priority to 0;"
10241                            + " package: " + applicationInfo.packageName
10242                            + " activity: " + intent.activity.className
10243                            + " origPrio: " + intent.getPriority());
10244                }
10245                intent.setPriority(0);
10246                return;
10247            }
10248
10249            // found activity, now check for filter equivalence
10250
10251            // a shallow copy is enough; we modify the list, not its contents
10252            final List<ActivityIntentInfo> intentListCopy =
10253                    new ArrayList<>(foundActivity.intents);
10254            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10255
10256            // find matching action subsets
10257            final Iterator<String> actionsIterator = intent.actionsIterator();
10258            if (actionsIterator != null) {
10259                getIntentListSubset(
10260                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10261                if (intentListCopy.size() == 0) {
10262                    // no more intents to match; we're not equivalent
10263                    if (DEBUG_FILTERS) {
10264                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10265                                + " package: " + applicationInfo.packageName
10266                                + " activity: " + intent.activity.className
10267                                + " origPrio: " + intent.getPriority());
10268                    }
10269                    intent.setPriority(0);
10270                    return;
10271                }
10272            }
10273
10274            // find matching category subsets
10275            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10276            if (categoriesIterator != null) {
10277                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10278                        categoriesIterator);
10279                if (intentListCopy.size() == 0) {
10280                    // no more intents to match; we're not equivalent
10281                    if (DEBUG_FILTERS) {
10282                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10283                                + " package: " + applicationInfo.packageName
10284                                + " activity: " + intent.activity.className
10285                                + " origPrio: " + intent.getPriority());
10286                    }
10287                    intent.setPriority(0);
10288                    return;
10289                }
10290            }
10291
10292            // find matching schemes subsets
10293            final Iterator<String> schemesIterator = intent.schemesIterator();
10294            if (schemesIterator != null) {
10295                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10296                        schemesIterator);
10297                if (intentListCopy.size() == 0) {
10298                    // no more intents to match; we're not equivalent
10299                    if (DEBUG_FILTERS) {
10300                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10301                                + " package: " + applicationInfo.packageName
10302                                + " activity: " + intent.activity.className
10303                                + " origPrio: " + intent.getPriority());
10304                    }
10305                    intent.setPriority(0);
10306                    return;
10307                }
10308            }
10309
10310            // find matching authorities subsets
10311            final Iterator<IntentFilter.AuthorityEntry>
10312                    authoritiesIterator = intent.authoritiesIterator();
10313            if (authoritiesIterator != null) {
10314                getIntentListSubset(intentListCopy,
10315                        new AuthoritiesIterGenerator(),
10316                        authoritiesIterator);
10317                if (intentListCopy.size() == 0) {
10318                    // no more intents to match; we're not equivalent
10319                    if (DEBUG_FILTERS) {
10320                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10321                                + " package: " + applicationInfo.packageName
10322                                + " activity: " + intent.activity.className
10323                                + " origPrio: " + intent.getPriority());
10324                    }
10325                    intent.setPriority(0);
10326                    return;
10327                }
10328            }
10329
10330            // we found matching filter(s); app gets the max priority of all intents
10331            int cappedPriority = 0;
10332            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10333                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10334            }
10335            if (intent.getPriority() > cappedPriority) {
10336                if (DEBUG_FILTERS) {
10337                    Slog.i(TAG, "Found matching filter(s);"
10338                            + " cap priority to " + cappedPriority + ";"
10339                            + " package: " + applicationInfo.packageName
10340                            + " activity: " + intent.activity.className
10341                            + " origPrio: " + intent.getPriority());
10342                }
10343                intent.setPriority(cappedPriority);
10344                return;
10345            }
10346            // all this for nothing; the requested priority was <= what was on the system
10347        }
10348
10349        public final void addActivity(PackageParser.Activity a, String type) {
10350            mActivities.put(a.getComponentName(), a);
10351            if (DEBUG_SHOW_INFO)
10352                Log.v(
10353                TAG, "  " + type + " " +
10354                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10355            if (DEBUG_SHOW_INFO)
10356                Log.v(TAG, "    Class=" + a.info.name);
10357            final int NI = a.intents.size();
10358            for (int j=0; j<NI; j++) {
10359                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10360                if ("activity".equals(type)) {
10361                    final PackageSetting ps =
10362                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10363                    final List<PackageParser.Activity> systemActivities =
10364                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10365                    adjustPriority(systemActivities, intent);
10366                }
10367                if (DEBUG_SHOW_INFO) {
10368                    Log.v(TAG, "    IntentFilter:");
10369                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10370                }
10371                if (!intent.debugCheck()) {
10372                    Log.w(TAG, "==> For Activity " + a.info.name);
10373                }
10374                addFilter(intent);
10375            }
10376        }
10377
10378        public final void removeActivity(PackageParser.Activity a, String type) {
10379            mActivities.remove(a.getComponentName());
10380            if (DEBUG_SHOW_INFO) {
10381                Log.v(TAG, "  " + type + " "
10382                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10383                                : a.info.name) + ":");
10384                Log.v(TAG, "    Class=" + a.info.name);
10385            }
10386            final int NI = a.intents.size();
10387            for (int j=0; j<NI; j++) {
10388                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10389                if (DEBUG_SHOW_INFO) {
10390                    Log.v(TAG, "    IntentFilter:");
10391                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10392                }
10393                removeFilter(intent);
10394            }
10395        }
10396
10397        @Override
10398        protected boolean allowFilterResult(
10399                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10400            ActivityInfo filterAi = filter.activity.info;
10401            for (int i=dest.size()-1; i>=0; i--) {
10402                ActivityInfo destAi = dest.get(i).activityInfo;
10403                if (destAi.name == filterAi.name
10404                        && destAi.packageName == filterAi.packageName) {
10405                    return false;
10406                }
10407            }
10408            return true;
10409        }
10410
10411        @Override
10412        protected ActivityIntentInfo[] newArray(int size) {
10413            return new ActivityIntentInfo[size];
10414        }
10415
10416        @Override
10417        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10418            if (!sUserManager.exists(userId)) return true;
10419            PackageParser.Package p = filter.activity.owner;
10420            if (p != null) {
10421                PackageSetting ps = (PackageSetting)p.mExtras;
10422                if (ps != null) {
10423                    // System apps are never considered stopped for purposes of
10424                    // filtering, because there may be no way for the user to
10425                    // actually re-launch them.
10426                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10427                            && ps.getStopped(userId);
10428                }
10429            }
10430            return false;
10431        }
10432
10433        @Override
10434        protected boolean isPackageForFilter(String packageName,
10435                PackageParser.ActivityIntentInfo info) {
10436            return packageName.equals(info.activity.owner.packageName);
10437        }
10438
10439        @Override
10440        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10441                int match, int userId) {
10442            if (!sUserManager.exists(userId)) return null;
10443            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10444                return null;
10445            }
10446            final PackageParser.Activity activity = info.activity;
10447            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10448            if (ps == null) {
10449                return null;
10450            }
10451            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10452                    ps.readUserState(userId), userId);
10453            if (ai == null) {
10454                return null;
10455            }
10456            final ResolveInfo res = new ResolveInfo();
10457            res.activityInfo = ai;
10458            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10459                res.filter = info;
10460            }
10461            if (info != null) {
10462                res.handleAllWebDataURI = info.handleAllWebDataURI();
10463            }
10464            res.priority = info.getPriority();
10465            res.preferredOrder = activity.owner.mPreferredOrder;
10466            //System.out.println("Result: " + res.activityInfo.className +
10467            //                   " = " + res.priority);
10468            res.match = match;
10469            res.isDefault = info.hasDefault;
10470            res.labelRes = info.labelRes;
10471            res.nonLocalizedLabel = info.nonLocalizedLabel;
10472            if (userNeedsBadging(userId)) {
10473                res.noResourceId = true;
10474            } else {
10475                res.icon = info.icon;
10476            }
10477            res.iconResourceId = info.icon;
10478            res.system = res.activityInfo.applicationInfo.isSystemApp();
10479            return res;
10480        }
10481
10482        @Override
10483        protected void sortResults(List<ResolveInfo> results) {
10484            Collections.sort(results, mResolvePrioritySorter);
10485        }
10486
10487        @Override
10488        protected void dumpFilter(PrintWriter out, String prefix,
10489                PackageParser.ActivityIntentInfo filter) {
10490            out.print(prefix); out.print(
10491                    Integer.toHexString(System.identityHashCode(filter.activity)));
10492                    out.print(' ');
10493                    filter.activity.printComponentShortName(out);
10494                    out.print(" filter ");
10495                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10496        }
10497
10498        @Override
10499        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10500            return filter.activity;
10501        }
10502
10503        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10504            PackageParser.Activity activity = (PackageParser.Activity)label;
10505            out.print(prefix); out.print(
10506                    Integer.toHexString(System.identityHashCode(activity)));
10507                    out.print(' ');
10508                    activity.printComponentShortName(out);
10509            if (count > 1) {
10510                out.print(" ("); out.print(count); out.print(" filters)");
10511            }
10512            out.println();
10513        }
10514
10515        // Keys are String (activity class name), values are Activity.
10516        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10517                = new ArrayMap<ComponentName, PackageParser.Activity>();
10518        private int mFlags;
10519    }
10520
10521    private final class ServiceIntentResolver
10522            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10523        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10524                boolean defaultOnly, int userId) {
10525            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10526            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10527        }
10528
10529        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10530                int userId) {
10531            if (!sUserManager.exists(userId)) return null;
10532            mFlags = flags;
10533            return super.queryIntent(intent, resolvedType,
10534                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10535        }
10536
10537        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10538                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10539            if (!sUserManager.exists(userId)) return null;
10540            if (packageServices == null) {
10541                return null;
10542            }
10543            mFlags = flags;
10544            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10545            final int N = packageServices.size();
10546            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10547                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10548
10549            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10550            for (int i = 0; i < N; ++i) {
10551                intentFilters = packageServices.get(i).intents;
10552                if (intentFilters != null && intentFilters.size() > 0) {
10553                    PackageParser.ServiceIntentInfo[] array =
10554                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10555                    intentFilters.toArray(array);
10556                    listCut.add(array);
10557                }
10558            }
10559            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10560        }
10561
10562        public final void addService(PackageParser.Service s) {
10563            mServices.put(s.getComponentName(), s);
10564            if (DEBUG_SHOW_INFO) {
10565                Log.v(TAG, "  "
10566                        + (s.info.nonLocalizedLabel != null
10567                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10568                Log.v(TAG, "    Class=" + s.info.name);
10569            }
10570            final int NI = s.intents.size();
10571            int j;
10572            for (j=0; j<NI; j++) {
10573                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10574                if (DEBUG_SHOW_INFO) {
10575                    Log.v(TAG, "    IntentFilter:");
10576                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10577                }
10578                if (!intent.debugCheck()) {
10579                    Log.w(TAG, "==> For Service " + s.info.name);
10580                }
10581                addFilter(intent);
10582            }
10583        }
10584
10585        public final void removeService(PackageParser.Service s) {
10586            mServices.remove(s.getComponentName());
10587            if (DEBUG_SHOW_INFO) {
10588                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10589                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10590                Log.v(TAG, "    Class=" + s.info.name);
10591            }
10592            final int NI = s.intents.size();
10593            int j;
10594            for (j=0; j<NI; j++) {
10595                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10596                if (DEBUG_SHOW_INFO) {
10597                    Log.v(TAG, "    IntentFilter:");
10598                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10599                }
10600                removeFilter(intent);
10601            }
10602        }
10603
10604        @Override
10605        protected boolean allowFilterResult(
10606                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10607            ServiceInfo filterSi = filter.service.info;
10608            for (int i=dest.size()-1; i>=0; i--) {
10609                ServiceInfo destAi = dest.get(i).serviceInfo;
10610                if (destAi.name == filterSi.name
10611                        && destAi.packageName == filterSi.packageName) {
10612                    return false;
10613                }
10614            }
10615            return true;
10616        }
10617
10618        @Override
10619        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10620            return new PackageParser.ServiceIntentInfo[size];
10621        }
10622
10623        @Override
10624        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10625            if (!sUserManager.exists(userId)) return true;
10626            PackageParser.Package p = filter.service.owner;
10627            if (p != null) {
10628                PackageSetting ps = (PackageSetting)p.mExtras;
10629                if (ps != null) {
10630                    // System apps are never considered stopped for purposes of
10631                    // filtering, because there may be no way for the user to
10632                    // actually re-launch them.
10633                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10634                            && ps.getStopped(userId);
10635                }
10636            }
10637            return false;
10638        }
10639
10640        @Override
10641        protected boolean isPackageForFilter(String packageName,
10642                PackageParser.ServiceIntentInfo info) {
10643            return packageName.equals(info.service.owner.packageName);
10644        }
10645
10646        @Override
10647        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10648                int match, int userId) {
10649            if (!sUserManager.exists(userId)) return null;
10650            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10651            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10652                return null;
10653            }
10654            final PackageParser.Service service = info.service;
10655            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10656            if (ps == null) {
10657                return null;
10658            }
10659            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10660                    ps.readUserState(userId), userId);
10661            if (si == null) {
10662                return null;
10663            }
10664            final ResolveInfo res = new ResolveInfo();
10665            res.serviceInfo = si;
10666            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10667                res.filter = filter;
10668            }
10669            res.priority = info.getPriority();
10670            res.preferredOrder = service.owner.mPreferredOrder;
10671            res.match = match;
10672            res.isDefault = info.hasDefault;
10673            res.labelRes = info.labelRes;
10674            res.nonLocalizedLabel = info.nonLocalizedLabel;
10675            res.icon = info.icon;
10676            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10677            return res;
10678        }
10679
10680        @Override
10681        protected void sortResults(List<ResolveInfo> results) {
10682            Collections.sort(results, mResolvePrioritySorter);
10683        }
10684
10685        @Override
10686        protected void dumpFilter(PrintWriter out, String prefix,
10687                PackageParser.ServiceIntentInfo filter) {
10688            out.print(prefix); out.print(
10689                    Integer.toHexString(System.identityHashCode(filter.service)));
10690                    out.print(' ');
10691                    filter.service.printComponentShortName(out);
10692                    out.print(" filter ");
10693                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10694        }
10695
10696        @Override
10697        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10698            return filter.service;
10699        }
10700
10701        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10702            PackageParser.Service service = (PackageParser.Service)label;
10703            out.print(prefix); out.print(
10704                    Integer.toHexString(System.identityHashCode(service)));
10705                    out.print(' ');
10706                    service.printComponentShortName(out);
10707            if (count > 1) {
10708                out.print(" ("); out.print(count); out.print(" filters)");
10709            }
10710            out.println();
10711        }
10712
10713//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10714//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10715//            final List<ResolveInfo> retList = Lists.newArrayList();
10716//            while (i.hasNext()) {
10717//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10718//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10719//                    retList.add(resolveInfo);
10720//                }
10721//            }
10722//            return retList;
10723//        }
10724
10725        // Keys are String (activity class name), values are Activity.
10726        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10727                = new ArrayMap<ComponentName, PackageParser.Service>();
10728        private int mFlags;
10729    };
10730
10731    private final class ProviderIntentResolver
10732            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10733        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10734                boolean defaultOnly, int userId) {
10735            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10736            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10737        }
10738
10739        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10740                int userId) {
10741            if (!sUserManager.exists(userId))
10742                return null;
10743            mFlags = flags;
10744            return super.queryIntent(intent, resolvedType,
10745                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10746        }
10747
10748        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10749                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10750            if (!sUserManager.exists(userId))
10751                return null;
10752            if (packageProviders == null) {
10753                return null;
10754            }
10755            mFlags = flags;
10756            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10757            final int N = packageProviders.size();
10758            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10759                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10760
10761            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10762            for (int i = 0; i < N; ++i) {
10763                intentFilters = packageProviders.get(i).intents;
10764                if (intentFilters != null && intentFilters.size() > 0) {
10765                    PackageParser.ProviderIntentInfo[] array =
10766                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10767                    intentFilters.toArray(array);
10768                    listCut.add(array);
10769                }
10770            }
10771            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10772        }
10773
10774        public final void addProvider(PackageParser.Provider p) {
10775            if (mProviders.containsKey(p.getComponentName())) {
10776                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10777                return;
10778            }
10779
10780            mProviders.put(p.getComponentName(), p);
10781            if (DEBUG_SHOW_INFO) {
10782                Log.v(TAG, "  "
10783                        + (p.info.nonLocalizedLabel != null
10784                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10785                Log.v(TAG, "    Class=" + p.info.name);
10786            }
10787            final int NI = p.intents.size();
10788            int j;
10789            for (j = 0; j < NI; j++) {
10790                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10791                if (DEBUG_SHOW_INFO) {
10792                    Log.v(TAG, "    IntentFilter:");
10793                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10794                }
10795                if (!intent.debugCheck()) {
10796                    Log.w(TAG, "==> For Provider " + p.info.name);
10797                }
10798                addFilter(intent);
10799            }
10800        }
10801
10802        public final void removeProvider(PackageParser.Provider p) {
10803            mProviders.remove(p.getComponentName());
10804            if (DEBUG_SHOW_INFO) {
10805                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10806                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10807                Log.v(TAG, "    Class=" + p.info.name);
10808            }
10809            final int NI = p.intents.size();
10810            int j;
10811            for (j = 0; j < NI; j++) {
10812                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10813                if (DEBUG_SHOW_INFO) {
10814                    Log.v(TAG, "    IntentFilter:");
10815                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10816                }
10817                removeFilter(intent);
10818            }
10819        }
10820
10821        @Override
10822        protected boolean allowFilterResult(
10823                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10824            ProviderInfo filterPi = filter.provider.info;
10825            for (int i = dest.size() - 1; i >= 0; i--) {
10826                ProviderInfo destPi = dest.get(i).providerInfo;
10827                if (destPi.name == filterPi.name
10828                        && destPi.packageName == filterPi.packageName) {
10829                    return false;
10830                }
10831            }
10832            return true;
10833        }
10834
10835        @Override
10836        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10837            return new PackageParser.ProviderIntentInfo[size];
10838        }
10839
10840        @Override
10841        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10842            if (!sUserManager.exists(userId))
10843                return true;
10844            PackageParser.Package p = filter.provider.owner;
10845            if (p != null) {
10846                PackageSetting ps = (PackageSetting) p.mExtras;
10847                if (ps != null) {
10848                    // System apps are never considered stopped for purposes of
10849                    // filtering, because there may be no way for the user to
10850                    // actually re-launch them.
10851                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10852                            && ps.getStopped(userId);
10853                }
10854            }
10855            return false;
10856        }
10857
10858        @Override
10859        protected boolean isPackageForFilter(String packageName,
10860                PackageParser.ProviderIntentInfo info) {
10861            return packageName.equals(info.provider.owner.packageName);
10862        }
10863
10864        @Override
10865        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10866                int match, int userId) {
10867            if (!sUserManager.exists(userId))
10868                return null;
10869            final PackageParser.ProviderIntentInfo info = filter;
10870            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10871                return null;
10872            }
10873            final PackageParser.Provider provider = info.provider;
10874            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10875            if (ps == null) {
10876                return null;
10877            }
10878            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10879                    ps.readUserState(userId), userId);
10880            if (pi == null) {
10881                return null;
10882            }
10883            final ResolveInfo res = new ResolveInfo();
10884            res.providerInfo = pi;
10885            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10886                res.filter = filter;
10887            }
10888            res.priority = info.getPriority();
10889            res.preferredOrder = provider.owner.mPreferredOrder;
10890            res.match = match;
10891            res.isDefault = info.hasDefault;
10892            res.labelRes = info.labelRes;
10893            res.nonLocalizedLabel = info.nonLocalizedLabel;
10894            res.icon = info.icon;
10895            res.system = res.providerInfo.applicationInfo.isSystemApp();
10896            return res;
10897        }
10898
10899        @Override
10900        protected void sortResults(List<ResolveInfo> results) {
10901            Collections.sort(results, mResolvePrioritySorter);
10902        }
10903
10904        @Override
10905        protected void dumpFilter(PrintWriter out, String prefix,
10906                PackageParser.ProviderIntentInfo filter) {
10907            out.print(prefix);
10908            out.print(
10909                    Integer.toHexString(System.identityHashCode(filter.provider)));
10910            out.print(' ');
10911            filter.provider.printComponentShortName(out);
10912            out.print(" filter ");
10913            out.println(Integer.toHexString(System.identityHashCode(filter)));
10914        }
10915
10916        @Override
10917        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10918            return filter.provider;
10919        }
10920
10921        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10922            PackageParser.Provider provider = (PackageParser.Provider)label;
10923            out.print(prefix); out.print(
10924                    Integer.toHexString(System.identityHashCode(provider)));
10925                    out.print(' ');
10926                    provider.printComponentShortName(out);
10927            if (count > 1) {
10928                out.print(" ("); out.print(count); out.print(" filters)");
10929            }
10930            out.println();
10931        }
10932
10933        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10934                = new ArrayMap<ComponentName, PackageParser.Provider>();
10935        private int mFlags;
10936    }
10937
10938    private static final class EphemeralIntentResolver
10939            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10940        @Override
10941        protected EphemeralResolveIntentInfo[] newArray(int size) {
10942            return new EphemeralResolveIntentInfo[size];
10943        }
10944
10945        @Override
10946        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10947            return true;
10948        }
10949
10950        @Override
10951        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10952                int userId) {
10953            if (!sUserManager.exists(userId)) {
10954                return null;
10955            }
10956            return info.getEphemeralResolveInfo();
10957        }
10958    }
10959
10960    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10961            new Comparator<ResolveInfo>() {
10962        public int compare(ResolveInfo r1, ResolveInfo r2) {
10963            int v1 = r1.priority;
10964            int v2 = r2.priority;
10965            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10966            if (v1 != v2) {
10967                return (v1 > v2) ? -1 : 1;
10968            }
10969            v1 = r1.preferredOrder;
10970            v2 = r2.preferredOrder;
10971            if (v1 != v2) {
10972                return (v1 > v2) ? -1 : 1;
10973            }
10974            if (r1.isDefault != r2.isDefault) {
10975                return r1.isDefault ? -1 : 1;
10976            }
10977            v1 = r1.match;
10978            v2 = r2.match;
10979            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10980            if (v1 != v2) {
10981                return (v1 > v2) ? -1 : 1;
10982            }
10983            if (r1.system != r2.system) {
10984                return r1.system ? -1 : 1;
10985            }
10986            if (r1.activityInfo != null) {
10987                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10988            }
10989            if (r1.serviceInfo != null) {
10990                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10991            }
10992            if (r1.providerInfo != null) {
10993                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10994            }
10995            return 0;
10996        }
10997    };
10998
10999    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11000            new Comparator<ProviderInfo>() {
11001        public int compare(ProviderInfo p1, ProviderInfo p2) {
11002            final int v1 = p1.initOrder;
11003            final int v2 = p2.initOrder;
11004            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11005        }
11006    };
11007
11008    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11009            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11010            final int[] userIds) {
11011        mHandler.post(new Runnable() {
11012            @Override
11013            public void run() {
11014                try {
11015                    final IActivityManager am = ActivityManagerNative.getDefault();
11016                    if (am == null) return;
11017                    final int[] resolvedUserIds;
11018                    if (userIds == null) {
11019                        resolvedUserIds = am.getRunningUserIds();
11020                    } else {
11021                        resolvedUserIds = userIds;
11022                    }
11023                    for (int id : resolvedUserIds) {
11024                        final Intent intent = new Intent(action,
11025                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11026                        if (extras != null) {
11027                            intent.putExtras(extras);
11028                        }
11029                        if (targetPkg != null) {
11030                            intent.setPackage(targetPkg);
11031                        }
11032                        // Modify the UID when posting to other users
11033                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11034                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11035                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11036                            intent.putExtra(Intent.EXTRA_UID, uid);
11037                        }
11038                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11039                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11040                        if (DEBUG_BROADCASTS) {
11041                            RuntimeException here = new RuntimeException("here");
11042                            here.fillInStackTrace();
11043                            Slog.d(TAG, "Sending to user " + id + ": "
11044                                    + intent.toShortString(false, true, false, false)
11045                                    + " " + intent.getExtras(), here);
11046                        }
11047                        am.broadcastIntent(null, intent, null, finishedReceiver,
11048                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11049                                null, finishedReceiver != null, false, id);
11050                    }
11051                } catch (RemoteException ex) {
11052                }
11053            }
11054        });
11055    }
11056
11057    /**
11058     * Check if the external storage media is available. This is true if there
11059     * is a mounted external storage medium or if the external storage is
11060     * emulated.
11061     */
11062    private boolean isExternalMediaAvailable() {
11063        return mMediaMounted || Environment.isExternalStorageEmulated();
11064    }
11065
11066    @Override
11067    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11068        // writer
11069        synchronized (mPackages) {
11070            if (!isExternalMediaAvailable()) {
11071                // If the external storage is no longer mounted at this point,
11072                // the caller may not have been able to delete all of this
11073                // packages files and can not delete any more.  Bail.
11074                return null;
11075            }
11076            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11077            if (lastPackage != null) {
11078                pkgs.remove(lastPackage);
11079            }
11080            if (pkgs.size() > 0) {
11081                return pkgs.get(0);
11082            }
11083        }
11084        return null;
11085    }
11086
11087    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11088        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11089                userId, andCode ? 1 : 0, packageName);
11090        if (mSystemReady) {
11091            msg.sendToTarget();
11092        } else {
11093            if (mPostSystemReadyMessages == null) {
11094                mPostSystemReadyMessages = new ArrayList<>();
11095            }
11096            mPostSystemReadyMessages.add(msg);
11097        }
11098    }
11099
11100    void startCleaningPackages() {
11101        // reader
11102        if (!isExternalMediaAvailable()) {
11103            return;
11104        }
11105        synchronized (mPackages) {
11106            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11107                return;
11108            }
11109        }
11110        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11111        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11112        IActivityManager am = ActivityManagerNative.getDefault();
11113        if (am != null) {
11114            try {
11115                am.startService(null, intent, null, mContext.getOpPackageName(),
11116                        UserHandle.USER_SYSTEM);
11117            } catch (RemoteException e) {
11118            }
11119        }
11120    }
11121
11122    @Override
11123    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11124            int installFlags, String installerPackageName, int userId) {
11125        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11126
11127        final int callingUid = Binder.getCallingUid();
11128        enforceCrossUserPermission(callingUid, userId,
11129                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11130
11131        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11132            try {
11133                if (observer != null) {
11134                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11135                }
11136            } catch (RemoteException re) {
11137            }
11138            return;
11139        }
11140
11141        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11142            installFlags |= PackageManager.INSTALL_FROM_ADB;
11143
11144        } else {
11145            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11146            // about installerPackageName.
11147
11148            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11149            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11150        }
11151
11152        UserHandle user;
11153        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11154            user = UserHandle.ALL;
11155        } else {
11156            user = new UserHandle(userId);
11157        }
11158
11159        // Only system components can circumvent runtime permissions when installing.
11160        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11161                && mContext.checkCallingOrSelfPermission(Manifest.permission
11162                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11163            throw new SecurityException("You need the "
11164                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11165                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11166        }
11167
11168        final File originFile = new File(originPath);
11169        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11170
11171        final Message msg = mHandler.obtainMessage(INIT_COPY);
11172        final VerificationInfo verificationInfo = new VerificationInfo(
11173                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11174        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11175                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11176                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11177                null /*certificates*/);
11178        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11179        msg.obj = params;
11180
11181        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11182                System.identityHashCode(msg.obj));
11183        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11184                System.identityHashCode(msg.obj));
11185
11186        mHandler.sendMessage(msg);
11187    }
11188
11189    void installStage(String packageName, File stagedDir, String stagedCid,
11190            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11191            String installerPackageName, int installerUid, UserHandle user,
11192            Certificate[][] certificates) {
11193        if (DEBUG_EPHEMERAL) {
11194            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11195                Slog.d(TAG, "Ephemeral install of " + packageName);
11196            }
11197        }
11198        final VerificationInfo verificationInfo = new VerificationInfo(
11199                sessionParams.originatingUri, sessionParams.referrerUri,
11200                sessionParams.originatingUid, installerUid);
11201
11202        final OriginInfo origin;
11203        if (stagedDir != null) {
11204            origin = OriginInfo.fromStagedFile(stagedDir);
11205        } else {
11206            origin = OriginInfo.fromStagedContainer(stagedCid);
11207        }
11208
11209        final Message msg = mHandler.obtainMessage(INIT_COPY);
11210        final InstallParams params = new InstallParams(origin, null, observer,
11211                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11212                verificationInfo, user, sessionParams.abiOverride,
11213                sessionParams.grantedRuntimePermissions, certificates);
11214        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11215        msg.obj = params;
11216
11217        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11218                System.identityHashCode(msg.obj));
11219        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11220                System.identityHashCode(msg.obj));
11221
11222        mHandler.sendMessage(msg);
11223    }
11224
11225    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11226            int userId) {
11227        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11228        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11229    }
11230
11231    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11232            int appId, int userId) {
11233        Bundle extras = new Bundle(1);
11234        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11235
11236        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11237                packageName, extras, 0, null, null, new int[] {userId});
11238        try {
11239            IActivityManager am = ActivityManagerNative.getDefault();
11240            if (isSystem && am.isUserRunning(userId, 0)) {
11241                // The just-installed/enabled app is bundled on the system, so presumed
11242                // to be able to run automatically without needing an explicit launch.
11243                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11244                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11245                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11246                        .setPackage(packageName);
11247                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11248                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11249            }
11250        } catch (RemoteException e) {
11251            // shouldn't happen
11252            Slog.w(TAG, "Unable to bootstrap installed package", e);
11253        }
11254    }
11255
11256    @Override
11257    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11258            int userId) {
11259        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11260        PackageSetting pkgSetting;
11261        final int uid = Binder.getCallingUid();
11262        enforceCrossUserPermission(uid, userId,
11263                true /* requireFullPermission */, true /* checkShell */,
11264                "setApplicationHiddenSetting for user " + userId);
11265
11266        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11267            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11268            return false;
11269        }
11270
11271        long callingId = Binder.clearCallingIdentity();
11272        try {
11273            boolean sendAdded = false;
11274            boolean sendRemoved = false;
11275            // writer
11276            synchronized (mPackages) {
11277                pkgSetting = mSettings.mPackages.get(packageName);
11278                if (pkgSetting == null) {
11279                    return false;
11280                }
11281                if (pkgSetting.getHidden(userId) != hidden) {
11282                    pkgSetting.setHidden(hidden, userId);
11283                    mSettings.writePackageRestrictionsLPr(userId);
11284                    if (hidden) {
11285                        sendRemoved = true;
11286                    } else {
11287                        sendAdded = true;
11288                    }
11289                }
11290            }
11291            if (sendAdded) {
11292                sendPackageAddedForUser(packageName, pkgSetting, userId);
11293                return true;
11294            }
11295            if (sendRemoved) {
11296                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11297                        "hiding pkg");
11298                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11299                return true;
11300            }
11301        } finally {
11302            Binder.restoreCallingIdentity(callingId);
11303        }
11304        return false;
11305    }
11306
11307    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11308            int userId) {
11309        final PackageRemovedInfo info = new PackageRemovedInfo();
11310        info.removedPackage = packageName;
11311        info.removedUsers = new int[] {userId};
11312        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11313        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11314    }
11315
11316    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11317        if (pkgList.length > 0) {
11318            Bundle extras = new Bundle(1);
11319            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11320
11321            sendPackageBroadcast(
11322                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11323                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11324                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11325                    new int[] {userId});
11326        }
11327    }
11328
11329    /**
11330     * Returns true if application is not found or there was an error. Otherwise it returns
11331     * the hidden state of the package for the given user.
11332     */
11333    @Override
11334    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11335        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11337                true /* requireFullPermission */, false /* checkShell */,
11338                "getApplicationHidden for user " + userId);
11339        PackageSetting pkgSetting;
11340        long callingId = Binder.clearCallingIdentity();
11341        try {
11342            // writer
11343            synchronized (mPackages) {
11344                pkgSetting = mSettings.mPackages.get(packageName);
11345                if (pkgSetting == null) {
11346                    return true;
11347                }
11348                return pkgSetting.getHidden(userId);
11349            }
11350        } finally {
11351            Binder.restoreCallingIdentity(callingId);
11352        }
11353    }
11354
11355    /**
11356     * @hide
11357     */
11358    @Override
11359    public int installExistingPackageAsUser(String packageName, int userId) {
11360        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11361                null);
11362        PackageSetting pkgSetting;
11363        final int uid = Binder.getCallingUid();
11364        enforceCrossUserPermission(uid, userId,
11365                true /* requireFullPermission */, true /* checkShell */,
11366                "installExistingPackage for user " + userId);
11367        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11368            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11369        }
11370
11371        long callingId = Binder.clearCallingIdentity();
11372        try {
11373            boolean installed = false;
11374
11375            // writer
11376            synchronized (mPackages) {
11377                pkgSetting = mSettings.mPackages.get(packageName);
11378                if (pkgSetting == null) {
11379                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11380                }
11381                if (!pkgSetting.getInstalled(userId)) {
11382                    pkgSetting.setInstalled(true, userId);
11383                    pkgSetting.setHidden(false, userId);
11384                    mSettings.writePackageRestrictionsLPr(userId);
11385                    installed = true;
11386                }
11387            }
11388
11389            if (installed) {
11390                if (pkgSetting.pkg != null) {
11391                    synchronized (mInstallLock) {
11392                        // We don't need to freeze for a brand new install
11393                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11394                    }
11395                }
11396                sendPackageAddedForUser(packageName, pkgSetting, userId);
11397            }
11398        } finally {
11399            Binder.restoreCallingIdentity(callingId);
11400        }
11401
11402        return PackageManager.INSTALL_SUCCEEDED;
11403    }
11404
11405    boolean isUserRestricted(int userId, String restrictionKey) {
11406        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11407        if (restrictions.getBoolean(restrictionKey, false)) {
11408            Log.w(TAG, "User is restricted: " + restrictionKey);
11409            return true;
11410        }
11411        return false;
11412    }
11413
11414    @Override
11415    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11416            int userId) {
11417        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11418        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11419                true /* requireFullPermission */, true /* checkShell */,
11420                "setPackagesSuspended for user " + userId);
11421
11422        if (ArrayUtils.isEmpty(packageNames)) {
11423            return packageNames;
11424        }
11425
11426        // List of package names for whom the suspended state has changed.
11427        List<String> changedPackages = new ArrayList<>(packageNames.length);
11428        // List of package names for whom the suspended state is not set as requested in this
11429        // method.
11430        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11431        for (int i = 0; i < packageNames.length; i++) {
11432            String packageName = packageNames[i];
11433            long callingId = Binder.clearCallingIdentity();
11434            try {
11435                boolean changed = false;
11436                final int appId;
11437                synchronized (mPackages) {
11438                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11439                    if (pkgSetting == null) {
11440                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11441                                + "\". Skipping suspending/un-suspending.");
11442                        unactionedPackages.add(packageName);
11443                        continue;
11444                    }
11445                    appId = pkgSetting.appId;
11446                    if (pkgSetting.getSuspended(userId) != suspended) {
11447                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11448                            unactionedPackages.add(packageName);
11449                            continue;
11450                        }
11451                        pkgSetting.setSuspended(suspended, userId);
11452                        mSettings.writePackageRestrictionsLPr(userId);
11453                        changed = true;
11454                        changedPackages.add(packageName);
11455                    }
11456                }
11457
11458                if (changed && suspended) {
11459                    killApplication(packageName, UserHandle.getUid(userId, appId),
11460                            "suspending package");
11461                }
11462            } finally {
11463                Binder.restoreCallingIdentity(callingId);
11464            }
11465        }
11466
11467        if (!changedPackages.isEmpty()) {
11468            sendPackagesSuspendedForUser(changedPackages.toArray(
11469                    new String[changedPackages.size()]), userId, suspended);
11470        }
11471
11472        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11473    }
11474
11475    @Override
11476    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11477        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11478                true /* requireFullPermission */, false /* checkShell */,
11479                "isPackageSuspendedForUser for user " + userId);
11480        synchronized (mPackages) {
11481            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11482            if (pkgSetting == null) {
11483                throw new IllegalArgumentException("Unknown target package: " + packageName);
11484            }
11485            return pkgSetting.getSuspended(userId);
11486        }
11487    }
11488
11489    /**
11490     * TODO: cache and disallow blocking the active dialer.
11491     *
11492     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11493     */
11494    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11495        if (isPackageDeviceAdmin(packageName, userId)) {
11496            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11497                    + "\": has an active device admin");
11498            return false;
11499        }
11500
11501        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11502        if (packageName.equals(activeLauncherPackageName)) {
11503            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11504                    + "\": contains the active launcher");
11505            return false;
11506        }
11507
11508        if (packageName.equals(mRequiredInstallerPackage)) {
11509            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11510                    + "\": required for package installation");
11511            return false;
11512        }
11513
11514        if (packageName.equals(mRequiredVerifierPackage)) {
11515            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11516                    + "\": required for package verification");
11517            return false;
11518        }
11519
11520        final PackageParser.Package pkg = mPackages.get(packageName);
11521        if (pkg != null && isPrivilegedApp(pkg)) {
11522            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11523                    + "\": is a privileged app");
11524            return false;
11525        }
11526
11527        return true;
11528    }
11529
11530    private String getActiveLauncherPackageName(int userId) {
11531        Intent intent = new Intent(Intent.ACTION_MAIN);
11532        intent.addCategory(Intent.CATEGORY_HOME);
11533        ResolveInfo resolveInfo = resolveIntent(
11534                intent,
11535                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11536                PackageManager.MATCH_DEFAULT_ONLY,
11537                userId);
11538
11539        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11540    }
11541
11542    @Override
11543    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11544        mContext.enforceCallingOrSelfPermission(
11545                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11546                "Only package verification agents can verify applications");
11547
11548        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11549        final PackageVerificationResponse response = new PackageVerificationResponse(
11550                verificationCode, Binder.getCallingUid());
11551        msg.arg1 = id;
11552        msg.obj = response;
11553        mHandler.sendMessage(msg);
11554    }
11555
11556    @Override
11557    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11558            long millisecondsToDelay) {
11559        mContext.enforceCallingOrSelfPermission(
11560                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11561                "Only package verification agents can extend verification timeouts");
11562
11563        final PackageVerificationState state = mPendingVerification.get(id);
11564        final PackageVerificationResponse response = new PackageVerificationResponse(
11565                verificationCodeAtTimeout, Binder.getCallingUid());
11566
11567        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11568            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11569        }
11570        if (millisecondsToDelay < 0) {
11571            millisecondsToDelay = 0;
11572        }
11573        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11574                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11575            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11576        }
11577
11578        if ((state != null) && !state.timeoutExtended()) {
11579            state.extendTimeout();
11580
11581            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11582            msg.arg1 = id;
11583            msg.obj = response;
11584            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11585        }
11586    }
11587
11588    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11589            int verificationCode, UserHandle user) {
11590        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11591        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11592        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11593        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11594        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11595
11596        mContext.sendBroadcastAsUser(intent, user,
11597                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11598    }
11599
11600    private ComponentName matchComponentForVerifier(String packageName,
11601            List<ResolveInfo> receivers) {
11602        ActivityInfo targetReceiver = null;
11603
11604        final int NR = receivers.size();
11605        for (int i = 0; i < NR; i++) {
11606            final ResolveInfo info = receivers.get(i);
11607            if (info.activityInfo == null) {
11608                continue;
11609            }
11610
11611            if (packageName.equals(info.activityInfo.packageName)) {
11612                targetReceiver = info.activityInfo;
11613                break;
11614            }
11615        }
11616
11617        if (targetReceiver == null) {
11618            return null;
11619        }
11620
11621        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11622    }
11623
11624    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11625            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11626        if (pkgInfo.verifiers.length == 0) {
11627            return null;
11628        }
11629
11630        final int N = pkgInfo.verifiers.length;
11631        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11632        for (int i = 0; i < N; i++) {
11633            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11634
11635            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11636                    receivers);
11637            if (comp == null) {
11638                continue;
11639            }
11640
11641            final int verifierUid = getUidForVerifier(verifierInfo);
11642            if (verifierUid == -1) {
11643                continue;
11644            }
11645
11646            if (DEBUG_VERIFY) {
11647                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11648                        + " with the correct signature");
11649            }
11650            sufficientVerifiers.add(comp);
11651            verificationState.addSufficientVerifier(verifierUid);
11652        }
11653
11654        return sufficientVerifiers;
11655    }
11656
11657    private int getUidForVerifier(VerifierInfo verifierInfo) {
11658        synchronized (mPackages) {
11659            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11660            if (pkg == null) {
11661                return -1;
11662            } else if (pkg.mSignatures.length != 1) {
11663                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11664                        + " has more than one signature; ignoring");
11665                return -1;
11666            }
11667
11668            /*
11669             * If the public key of the package's signature does not match
11670             * our expected public key, then this is a different package and
11671             * we should skip.
11672             */
11673
11674            final byte[] expectedPublicKey;
11675            try {
11676                final Signature verifierSig = pkg.mSignatures[0];
11677                final PublicKey publicKey = verifierSig.getPublicKey();
11678                expectedPublicKey = publicKey.getEncoded();
11679            } catch (CertificateException e) {
11680                return -1;
11681            }
11682
11683            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11684
11685            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11686                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11687                        + " does not have the expected public key; ignoring");
11688                return -1;
11689            }
11690
11691            return pkg.applicationInfo.uid;
11692        }
11693    }
11694
11695    @Override
11696    public void finishPackageInstall(int token) {
11697        enforceSystemOrRoot("Only the system is allowed to finish installs");
11698
11699        if (DEBUG_INSTALL) {
11700            Slog.v(TAG, "BM finishing package install for " + token);
11701        }
11702        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11703
11704        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11705        mHandler.sendMessage(msg);
11706    }
11707
11708    /**
11709     * Get the verification agent timeout.
11710     *
11711     * @return verification timeout in milliseconds
11712     */
11713    private long getVerificationTimeout() {
11714        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11715                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11716                DEFAULT_VERIFICATION_TIMEOUT);
11717    }
11718
11719    /**
11720     * Get the default verification agent response code.
11721     *
11722     * @return default verification response code
11723     */
11724    private int getDefaultVerificationResponse() {
11725        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11726                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11727                DEFAULT_VERIFICATION_RESPONSE);
11728    }
11729
11730    /**
11731     * Check whether or not package verification has been enabled.
11732     *
11733     * @return true if verification should be performed
11734     */
11735    private boolean isVerificationEnabled(int userId, int installFlags) {
11736        if (!DEFAULT_VERIFY_ENABLE) {
11737            return false;
11738        }
11739        // Ephemeral apps don't get the full verification treatment
11740        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11741            if (DEBUG_EPHEMERAL) {
11742                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11743            }
11744            return false;
11745        }
11746
11747        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11748
11749        // Check if installing from ADB
11750        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11751            // Do not run verification in a test harness environment
11752            if (ActivityManager.isRunningInTestHarness()) {
11753                return false;
11754            }
11755            if (ensureVerifyAppsEnabled) {
11756                return true;
11757            }
11758            // Check if the developer does not want package verification for ADB installs
11759            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11760                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11761                return false;
11762            }
11763        }
11764
11765        if (ensureVerifyAppsEnabled) {
11766            return true;
11767        }
11768
11769        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11770                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11771    }
11772
11773    @Override
11774    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11775            throws RemoteException {
11776        mContext.enforceCallingOrSelfPermission(
11777                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11778                "Only intentfilter verification agents can verify applications");
11779
11780        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11781        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11782                Binder.getCallingUid(), verificationCode, failedDomains);
11783        msg.arg1 = id;
11784        msg.obj = response;
11785        mHandler.sendMessage(msg);
11786    }
11787
11788    @Override
11789    public int getIntentVerificationStatus(String packageName, int userId) {
11790        synchronized (mPackages) {
11791            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11792        }
11793    }
11794
11795    @Override
11796    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11797        mContext.enforceCallingOrSelfPermission(
11798                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11799
11800        boolean result = false;
11801        synchronized (mPackages) {
11802            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11803        }
11804        if (result) {
11805            scheduleWritePackageRestrictionsLocked(userId);
11806        }
11807        return result;
11808    }
11809
11810    @Override
11811    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11812            String packageName) {
11813        synchronized (mPackages) {
11814            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11815        }
11816    }
11817
11818    @Override
11819    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11820        if (TextUtils.isEmpty(packageName)) {
11821            return ParceledListSlice.emptyList();
11822        }
11823        synchronized (mPackages) {
11824            PackageParser.Package pkg = mPackages.get(packageName);
11825            if (pkg == null || pkg.activities == null) {
11826                return ParceledListSlice.emptyList();
11827            }
11828            final int count = pkg.activities.size();
11829            ArrayList<IntentFilter> result = new ArrayList<>();
11830            for (int n=0; n<count; n++) {
11831                PackageParser.Activity activity = pkg.activities.get(n);
11832                if (activity.intents != null && activity.intents.size() > 0) {
11833                    result.addAll(activity.intents);
11834                }
11835            }
11836            return new ParceledListSlice<>(result);
11837        }
11838    }
11839
11840    @Override
11841    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11842        mContext.enforceCallingOrSelfPermission(
11843                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11844
11845        synchronized (mPackages) {
11846            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11847            if (packageName != null) {
11848                result |= updateIntentVerificationStatus(packageName,
11849                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11850                        userId);
11851                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11852                        packageName, userId);
11853            }
11854            return result;
11855        }
11856    }
11857
11858    @Override
11859    public String getDefaultBrowserPackageName(int userId) {
11860        synchronized (mPackages) {
11861            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11862        }
11863    }
11864
11865    /**
11866     * Get the "allow unknown sources" setting.
11867     *
11868     * @return the current "allow unknown sources" setting
11869     */
11870    private int getUnknownSourcesSettings() {
11871        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11872                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11873                -1);
11874    }
11875
11876    @Override
11877    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11878        final int uid = Binder.getCallingUid();
11879        // writer
11880        synchronized (mPackages) {
11881            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11882            if (targetPackageSetting == null) {
11883                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11884            }
11885
11886            PackageSetting installerPackageSetting;
11887            if (installerPackageName != null) {
11888                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11889                if (installerPackageSetting == null) {
11890                    throw new IllegalArgumentException("Unknown installer package: "
11891                            + installerPackageName);
11892                }
11893            } else {
11894                installerPackageSetting = null;
11895            }
11896
11897            Signature[] callerSignature;
11898            Object obj = mSettings.getUserIdLPr(uid);
11899            if (obj != null) {
11900                if (obj instanceof SharedUserSetting) {
11901                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11902                } else if (obj instanceof PackageSetting) {
11903                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11904                } else {
11905                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11906                }
11907            } else {
11908                throw new SecurityException("Unknown calling UID: " + uid);
11909            }
11910
11911            // Verify: can't set installerPackageName to a package that is
11912            // not signed with the same cert as the caller.
11913            if (installerPackageSetting != null) {
11914                if (compareSignatures(callerSignature,
11915                        installerPackageSetting.signatures.mSignatures)
11916                        != PackageManager.SIGNATURE_MATCH) {
11917                    throw new SecurityException(
11918                            "Caller does not have same cert as new installer package "
11919                            + installerPackageName);
11920                }
11921            }
11922
11923            // Verify: if target already has an installer package, it must
11924            // be signed with the same cert as the caller.
11925            if (targetPackageSetting.installerPackageName != null) {
11926                PackageSetting setting = mSettings.mPackages.get(
11927                        targetPackageSetting.installerPackageName);
11928                // If the currently set package isn't valid, then it's always
11929                // okay to change it.
11930                if (setting != null) {
11931                    if (compareSignatures(callerSignature,
11932                            setting.signatures.mSignatures)
11933                            != PackageManager.SIGNATURE_MATCH) {
11934                        throw new SecurityException(
11935                                "Caller does not have same cert as old installer package "
11936                                + targetPackageSetting.installerPackageName);
11937                    }
11938                }
11939            }
11940
11941            // Okay!
11942            targetPackageSetting.installerPackageName = installerPackageName;
11943            if (installerPackageName != null) {
11944                mSettings.mInstallerPackages.add(installerPackageName);
11945            }
11946            scheduleWriteSettingsLocked();
11947        }
11948    }
11949
11950    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11951        // Queue up an async operation since the package installation may take a little while.
11952        mHandler.post(new Runnable() {
11953            public void run() {
11954                mHandler.removeCallbacks(this);
11955                 // Result object to be returned
11956                PackageInstalledInfo res = new PackageInstalledInfo();
11957                res.setReturnCode(currentStatus);
11958                res.uid = -1;
11959                res.pkg = null;
11960                res.removedInfo = null;
11961                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11962                    args.doPreInstall(res.returnCode);
11963                    synchronized (mInstallLock) {
11964                        installPackageTracedLI(args, res);
11965                    }
11966                    args.doPostInstall(res.returnCode, res.uid);
11967                }
11968
11969                // A restore should be performed at this point if (a) the install
11970                // succeeded, (b) the operation is not an update, and (c) the new
11971                // package has not opted out of backup participation.
11972                final boolean update = res.removedInfo != null
11973                        && res.removedInfo.removedPackage != null;
11974                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11975                boolean doRestore = !update
11976                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11977
11978                // Set up the post-install work request bookkeeping.  This will be used
11979                // and cleaned up by the post-install event handling regardless of whether
11980                // there's a restore pass performed.  Token values are >= 1.
11981                int token;
11982                if (mNextInstallToken < 0) mNextInstallToken = 1;
11983                token = mNextInstallToken++;
11984
11985                PostInstallData data = new PostInstallData(args, res);
11986                mRunningInstalls.put(token, data);
11987                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11988
11989                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11990                    // Pass responsibility to the Backup Manager.  It will perform a
11991                    // restore if appropriate, then pass responsibility back to the
11992                    // Package Manager to run the post-install observer callbacks
11993                    // and broadcasts.
11994                    IBackupManager bm = IBackupManager.Stub.asInterface(
11995                            ServiceManager.getService(Context.BACKUP_SERVICE));
11996                    if (bm != null) {
11997                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11998                                + " to BM for possible restore");
11999                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12000                        try {
12001                            // TODO: http://b/22388012
12002                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12003                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12004                            } else {
12005                                doRestore = false;
12006                            }
12007                        } catch (RemoteException e) {
12008                            // can't happen; the backup manager is local
12009                        } catch (Exception e) {
12010                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12011                            doRestore = false;
12012                        }
12013                    } else {
12014                        Slog.e(TAG, "Backup Manager not found!");
12015                        doRestore = false;
12016                    }
12017                }
12018
12019                if (!doRestore) {
12020                    // No restore possible, or the Backup Manager was mysteriously not
12021                    // available -- just fire the post-install work request directly.
12022                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12023
12024                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12025
12026                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12027                    mHandler.sendMessage(msg);
12028                }
12029            }
12030        });
12031    }
12032
12033    private abstract class HandlerParams {
12034        private static final int MAX_RETRIES = 4;
12035
12036        /**
12037         * Number of times startCopy() has been attempted and had a non-fatal
12038         * error.
12039         */
12040        private int mRetries = 0;
12041
12042        /** User handle for the user requesting the information or installation. */
12043        private final UserHandle mUser;
12044        String traceMethod;
12045        int traceCookie;
12046
12047        HandlerParams(UserHandle user) {
12048            mUser = user;
12049        }
12050
12051        UserHandle getUser() {
12052            return mUser;
12053        }
12054
12055        HandlerParams setTraceMethod(String traceMethod) {
12056            this.traceMethod = traceMethod;
12057            return this;
12058        }
12059
12060        HandlerParams setTraceCookie(int traceCookie) {
12061            this.traceCookie = traceCookie;
12062            return this;
12063        }
12064
12065        final boolean startCopy() {
12066            boolean res;
12067            try {
12068                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12069
12070                if (++mRetries > MAX_RETRIES) {
12071                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12072                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12073                    handleServiceError();
12074                    return false;
12075                } else {
12076                    handleStartCopy();
12077                    res = true;
12078                }
12079            } catch (RemoteException e) {
12080                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12081                mHandler.sendEmptyMessage(MCS_RECONNECT);
12082                res = false;
12083            }
12084            handleReturnCode();
12085            return res;
12086        }
12087
12088        final void serviceError() {
12089            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12090            handleServiceError();
12091            handleReturnCode();
12092        }
12093
12094        abstract void handleStartCopy() throws RemoteException;
12095        abstract void handleServiceError();
12096        abstract void handleReturnCode();
12097    }
12098
12099    class MeasureParams extends HandlerParams {
12100        private final PackageStats mStats;
12101        private boolean mSuccess;
12102
12103        private final IPackageStatsObserver mObserver;
12104
12105        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12106            super(new UserHandle(stats.userHandle));
12107            mObserver = observer;
12108            mStats = stats;
12109        }
12110
12111        @Override
12112        public String toString() {
12113            return "MeasureParams{"
12114                + Integer.toHexString(System.identityHashCode(this))
12115                + " " + mStats.packageName + "}";
12116        }
12117
12118        @Override
12119        void handleStartCopy() throws RemoteException {
12120            synchronized (mInstallLock) {
12121                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12122            }
12123
12124            if (mSuccess) {
12125                final boolean mounted;
12126                if (Environment.isExternalStorageEmulated()) {
12127                    mounted = true;
12128                } else {
12129                    final String status = Environment.getExternalStorageState();
12130                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12131                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12132                }
12133
12134                if (mounted) {
12135                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12136
12137                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12138                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12139
12140                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12141                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12142
12143                    // Always subtract cache size, since it's a subdirectory
12144                    mStats.externalDataSize -= mStats.externalCacheSize;
12145
12146                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12147                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12148
12149                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12150                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12151                }
12152            }
12153        }
12154
12155        @Override
12156        void handleReturnCode() {
12157            if (mObserver != null) {
12158                try {
12159                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12160                } catch (RemoteException e) {
12161                    Slog.i(TAG, "Observer no longer exists.");
12162                }
12163            }
12164        }
12165
12166        @Override
12167        void handleServiceError() {
12168            Slog.e(TAG, "Could not measure application " + mStats.packageName
12169                            + " external storage");
12170        }
12171    }
12172
12173    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12174            throws RemoteException {
12175        long result = 0;
12176        for (File path : paths) {
12177            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12178        }
12179        return result;
12180    }
12181
12182    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12183        for (File path : paths) {
12184            try {
12185                mcs.clearDirectory(path.getAbsolutePath());
12186            } catch (RemoteException e) {
12187            }
12188        }
12189    }
12190
12191    static class OriginInfo {
12192        /**
12193         * Location where install is coming from, before it has been
12194         * copied/renamed into place. This could be a single monolithic APK
12195         * file, or a cluster directory. This location may be untrusted.
12196         */
12197        final File file;
12198        final String cid;
12199
12200        /**
12201         * Flag indicating that {@link #file} or {@link #cid} has already been
12202         * staged, meaning downstream users don't need to defensively copy the
12203         * contents.
12204         */
12205        final boolean staged;
12206
12207        /**
12208         * Flag indicating that {@link #file} or {@link #cid} is an already
12209         * installed app that is being moved.
12210         */
12211        final boolean existing;
12212
12213        final String resolvedPath;
12214        final File resolvedFile;
12215
12216        static OriginInfo fromNothing() {
12217            return new OriginInfo(null, null, false, false);
12218        }
12219
12220        static OriginInfo fromUntrustedFile(File file) {
12221            return new OriginInfo(file, null, false, false);
12222        }
12223
12224        static OriginInfo fromExistingFile(File file) {
12225            return new OriginInfo(file, null, false, true);
12226        }
12227
12228        static OriginInfo fromStagedFile(File file) {
12229            return new OriginInfo(file, null, true, false);
12230        }
12231
12232        static OriginInfo fromStagedContainer(String cid) {
12233            return new OriginInfo(null, cid, true, false);
12234        }
12235
12236        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12237            this.file = file;
12238            this.cid = cid;
12239            this.staged = staged;
12240            this.existing = existing;
12241
12242            if (cid != null) {
12243                resolvedPath = PackageHelper.getSdDir(cid);
12244                resolvedFile = new File(resolvedPath);
12245            } else if (file != null) {
12246                resolvedPath = file.getAbsolutePath();
12247                resolvedFile = file;
12248            } else {
12249                resolvedPath = null;
12250                resolvedFile = null;
12251            }
12252        }
12253    }
12254
12255    static class MoveInfo {
12256        final int moveId;
12257        final String fromUuid;
12258        final String toUuid;
12259        final String packageName;
12260        final String dataAppName;
12261        final int appId;
12262        final String seinfo;
12263        final int targetSdkVersion;
12264
12265        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12266                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12267            this.moveId = moveId;
12268            this.fromUuid = fromUuid;
12269            this.toUuid = toUuid;
12270            this.packageName = packageName;
12271            this.dataAppName = dataAppName;
12272            this.appId = appId;
12273            this.seinfo = seinfo;
12274            this.targetSdkVersion = targetSdkVersion;
12275        }
12276    }
12277
12278    static class VerificationInfo {
12279        /** A constant used to indicate that a uid value is not present. */
12280        public static final int NO_UID = -1;
12281
12282        /** URI referencing where the package was downloaded from. */
12283        final Uri originatingUri;
12284
12285        /** HTTP referrer URI associated with the originatingURI. */
12286        final Uri referrer;
12287
12288        /** UID of the application that the install request originated from. */
12289        final int originatingUid;
12290
12291        /** UID of application requesting the install */
12292        final int installerUid;
12293
12294        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12295            this.originatingUri = originatingUri;
12296            this.referrer = referrer;
12297            this.originatingUid = originatingUid;
12298            this.installerUid = installerUid;
12299        }
12300    }
12301
12302    class InstallParams extends HandlerParams {
12303        final OriginInfo origin;
12304        final MoveInfo move;
12305        final IPackageInstallObserver2 observer;
12306        int installFlags;
12307        final String installerPackageName;
12308        final String volumeUuid;
12309        private InstallArgs mArgs;
12310        private int mRet;
12311        final String packageAbiOverride;
12312        final String[] grantedRuntimePermissions;
12313        final VerificationInfo verificationInfo;
12314        final Certificate[][] certificates;
12315
12316        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12317                int installFlags, String installerPackageName, String volumeUuid,
12318                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12319                String[] grantedPermissions, Certificate[][] certificates) {
12320            super(user);
12321            this.origin = origin;
12322            this.move = move;
12323            this.observer = observer;
12324            this.installFlags = installFlags;
12325            this.installerPackageName = installerPackageName;
12326            this.volumeUuid = volumeUuid;
12327            this.verificationInfo = verificationInfo;
12328            this.packageAbiOverride = packageAbiOverride;
12329            this.grantedRuntimePermissions = grantedPermissions;
12330            this.certificates = certificates;
12331        }
12332
12333        @Override
12334        public String toString() {
12335            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12336                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12337        }
12338
12339        private int installLocationPolicy(PackageInfoLite pkgLite) {
12340            String packageName = pkgLite.packageName;
12341            int installLocation = pkgLite.installLocation;
12342            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12343            // reader
12344            synchronized (mPackages) {
12345                // Currently installed package which the new package is attempting to replace or
12346                // null if no such package is installed.
12347                PackageParser.Package installedPkg = mPackages.get(packageName);
12348                // Package which currently owns the data which the new package will own if installed.
12349                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12350                // will be null whereas dataOwnerPkg will contain information about the package
12351                // which was uninstalled while keeping its data.
12352                PackageParser.Package dataOwnerPkg = installedPkg;
12353                if (dataOwnerPkg  == null) {
12354                    PackageSetting ps = mSettings.mPackages.get(packageName);
12355                    if (ps != null) {
12356                        dataOwnerPkg = ps.pkg;
12357                    }
12358                }
12359
12360                if (dataOwnerPkg != null) {
12361                    // If installed, the package will get access to data left on the device by its
12362                    // predecessor. As a security measure, this is permited only if this is not a
12363                    // version downgrade or if the predecessor package is marked as debuggable and
12364                    // a downgrade is explicitly requested.
12365                    //
12366                    // On debuggable platform builds, downgrades are permitted even for
12367                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12368                    // not offer security guarantees and thus it's OK to disable some security
12369                    // mechanisms to make debugging/testing easier on those builds. However, even on
12370                    // debuggable builds downgrades of packages are permitted only if requested via
12371                    // installFlags. This is because we aim to keep the behavior of debuggable
12372                    // platform builds as close as possible to the behavior of non-debuggable
12373                    // platform builds.
12374                    final boolean downgradeRequested =
12375                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12376                    final boolean packageDebuggable =
12377                                (dataOwnerPkg.applicationInfo.flags
12378                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12379                    final boolean downgradePermitted =
12380                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12381                    if (!downgradePermitted) {
12382                        try {
12383                            checkDowngrade(dataOwnerPkg, pkgLite);
12384                        } catch (PackageManagerException e) {
12385                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12386                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12387                        }
12388                    }
12389                }
12390
12391                if (installedPkg != null) {
12392                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12393                        // Check for updated system application.
12394                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12395                            if (onSd) {
12396                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12397                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12398                            }
12399                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12400                        } else {
12401                            if (onSd) {
12402                                // Install flag overrides everything.
12403                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12404                            }
12405                            // If current upgrade specifies particular preference
12406                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12407                                // Application explicitly specified internal.
12408                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12409                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12410                                // App explictly prefers external. Let policy decide
12411                            } else {
12412                                // Prefer previous location
12413                                if (isExternal(installedPkg)) {
12414                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12415                                }
12416                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12417                            }
12418                        }
12419                    } else {
12420                        // Invalid install. Return error code
12421                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12422                    }
12423                }
12424            }
12425            // All the special cases have been taken care of.
12426            // Return result based on recommended install location.
12427            if (onSd) {
12428                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12429            }
12430            return pkgLite.recommendedInstallLocation;
12431        }
12432
12433        /*
12434         * Invoke remote method to get package information and install
12435         * location values. Override install location based on default
12436         * policy if needed and then create install arguments based
12437         * on the install location.
12438         */
12439        public void handleStartCopy() throws RemoteException {
12440            int ret = PackageManager.INSTALL_SUCCEEDED;
12441
12442            // If we're already staged, we've firmly committed to an install location
12443            if (origin.staged) {
12444                if (origin.file != null) {
12445                    installFlags |= PackageManager.INSTALL_INTERNAL;
12446                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12447                } else if (origin.cid != null) {
12448                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12449                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12450                } else {
12451                    throw new IllegalStateException("Invalid stage location");
12452                }
12453            }
12454
12455            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12456            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12457            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12458            PackageInfoLite pkgLite = null;
12459
12460            if (onInt && onSd) {
12461                // Check if both bits are set.
12462                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12463                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12464            } else if (onSd && ephemeral) {
12465                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12466                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12467            } else {
12468                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12469                        packageAbiOverride);
12470
12471                if (DEBUG_EPHEMERAL && ephemeral) {
12472                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12473                }
12474
12475                /*
12476                 * If we have too little free space, try to free cache
12477                 * before giving up.
12478                 */
12479                if (!origin.staged && pkgLite.recommendedInstallLocation
12480                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12481                    // TODO: focus freeing disk space on the target device
12482                    final StorageManager storage = StorageManager.from(mContext);
12483                    final long lowThreshold = storage.getStorageLowBytes(
12484                            Environment.getDataDirectory());
12485
12486                    final long sizeBytes = mContainerService.calculateInstalledSize(
12487                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12488
12489                    try {
12490                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12491                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12492                                installFlags, packageAbiOverride);
12493                    } catch (InstallerException e) {
12494                        Slog.w(TAG, "Failed to free cache", e);
12495                    }
12496
12497                    /*
12498                     * The cache free must have deleted the file we
12499                     * downloaded to install.
12500                     *
12501                     * TODO: fix the "freeCache" call to not delete
12502                     *       the file we care about.
12503                     */
12504                    if (pkgLite.recommendedInstallLocation
12505                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12506                        pkgLite.recommendedInstallLocation
12507                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12508                    }
12509                }
12510            }
12511
12512            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12513                int loc = pkgLite.recommendedInstallLocation;
12514                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12515                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12516                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12517                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12518                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12519                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12520                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12521                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12522                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12523                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12524                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12525                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12526                } else {
12527                    // Override with defaults if needed.
12528                    loc = installLocationPolicy(pkgLite);
12529                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12530                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12531                    } else if (!onSd && !onInt) {
12532                        // Override install location with flags
12533                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12534                            // Set the flag to install on external media.
12535                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12536                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12537                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12538                            if (DEBUG_EPHEMERAL) {
12539                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12540                            }
12541                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12542                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12543                                    |PackageManager.INSTALL_INTERNAL);
12544                        } else {
12545                            // Make sure the flag for installing on external
12546                            // media is unset
12547                            installFlags |= PackageManager.INSTALL_INTERNAL;
12548                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12549                        }
12550                    }
12551                }
12552            }
12553
12554            final InstallArgs args = createInstallArgs(this);
12555            mArgs = args;
12556
12557            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12558                // TODO: http://b/22976637
12559                // Apps installed for "all" users use the device owner to verify the app
12560                UserHandle verifierUser = getUser();
12561                if (verifierUser == UserHandle.ALL) {
12562                    verifierUser = UserHandle.SYSTEM;
12563                }
12564
12565                /*
12566                 * Determine if we have any installed package verifiers. If we
12567                 * do, then we'll defer to them to verify the packages.
12568                 */
12569                final int requiredUid = mRequiredVerifierPackage == null ? -1
12570                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12571                                verifierUser.getIdentifier());
12572                if (!origin.existing && requiredUid != -1
12573                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12574                    final Intent verification = new Intent(
12575                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12576                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12577                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12578                            PACKAGE_MIME_TYPE);
12579                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12580
12581                    // Query all live verifiers based on current user state
12582                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12583                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12584
12585                    if (DEBUG_VERIFY) {
12586                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12587                                + verification.toString() + " with " + pkgLite.verifiers.length
12588                                + " optional verifiers");
12589                    }
12590
12591                    final int verificationId = mPendingVerificationToken++;
12592
12593                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12594
12595                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12596                            installerPackageName);
12597
12598                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12599                            installFlags);
12600
12601                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12602                            pkgLite.packageName);
12603
12604                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12605                            pkgLite.versionCode);
12606
12607                    if (verificationInfo != null) {
12608                        if (verificationInfo.originatingUri != null) {
12609                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12610                                    verificationInfo.originatingUri);
12611                        }
12612                        if (verificationInfo.referrer != null) {
12613                            verification.putExtra(Intent.EXTRA_REFERRER,
12614                                    verificationInfo.referrer);
12615                        }
12616                        if (verificationInfo.originatingUid >= 0) {
12617                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12618                                    verificationInfo.originatingUid);
12619                        }
12620                        if (verificationInfo.installerUid >= 0) {
12621                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12622                                    verificationInfo.installerUid);
12623                        }
12624                    }
12625
12626                    final PackageVerificationState verificationState = new PackageVerificationState(
12627                            requiredUid, args);
12628
12629                    mPendingVerification.append(verificationId, verificationState);
12630
12631                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12632                            receivers, verificationState);
12633
12634                    /*
12635                     * If any sufficient verifiers were listed in the package
12636                     * manifest, attempt to ask them.
12637                     */
12638                    if (sufficientVerifiers != null) {
12639                        final int N = sufficientVerifiers.size();
12640                        if (N == 0) {
12641                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12642                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12643                        } else {
12644                            for (int i = 0; i < N; i++) {
12645                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12646
12647                                final Intent sufficientIntent = new Intent(verification);
12648                                sufficientIntent.setComponent(verifierComponent);
12649                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12650                            }
12651                        }
12652                    }
12653
12654                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12655                            mRequiredVerifierPackage, receivers);
12656                    if (ret == PackageManager.INSTALL_SUCCEEDED
12657                            && mRequiredVerifierPackage != null) {
12658                        Trace.asyncTraceBegin(
12659                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12660                        /*
12661                         * Send the intent to the required verification agent,
12662                         * but only start the verification timeout after the
12663                         * target BroadcastReceivers have run.
12664                         */
12665                        verification.setComponent(requiredVerifierComponent);
12666                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12667                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12668                                new BroadcastReceiver() {
12669                                    @Override
12670                                    public void onReceive(Context context, Intent intent) {
12671                                        final Message msg = mHandler
12672                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12673                                        msg.arg1 = verificationId;
12674                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12675                                    }
12676                                }, null, 0, null, null);
12677
12678                        /*
12679                         * We don't want the copy to proceed until verification
12680                         * succeeds, so null out this field.
12681                         */
12682                        mArgs = null;
12683                    }
12684                } else {
12685                    /*
12686                     * No package verification is enabled, so immediately start
12687                     * the remote call to initiate copy using temporary file.
12688                     */
12689                    ret = args.copyApk(mContainerService, true);
12690                }
12691            }
12692
12693            mRet = ret;
12694        }
12695
12696        @Override
12697        void handleReturnCode() {
12698            // If mArgs is null, then MCS couldn't be reached. When it
12699            // reconnects, it will try again to install. At that point, this
12700            // will succeed.
12701            if (mArgs != null) {
12702                processPendingInstall(mArgs, mRet);
12703            }
12704        }
12705
12706        @Override
12707        void handleServiceError() {
12708            mArgs = createInstallArgs(this);
12709            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12710        }
12711
12712        public boolean isForwardLocked() {
12713            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12714        }
12715    }
12716
12717    /**
12718     * Used during creation of InstallArgs
12719     *
12720     * @param installFlags package installation flags
12721     * @return true if should be installed on external storage
12722     */
12723    private static boolean installOnExternalAsec(int installFlags) {
12724        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12725            return false;
12726        }
12727        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12728            return true;
12729        }
12730        return false;
12731    }
12732
12733    /**
12734     * Used during creation of InstallArgs
12735     *
12736     * @param installFlags package installation flags
12737     * @return true if should be installed as forward locked
12738     */
12739    private static boolean installForwardLocked(int installFlags) {
12740        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12741    }
12742
12743    private InstallArgs createInstallArgs(InstallParams params) {
12744        if (params.move != null) {
12745            return new MoveInstallArgs(params);
12746        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12747            return new AsecInstallArgs(params);
12748        } else {
12749            return new FileInstallArgs(params);
12750        }
12751    }
12752
12753    /**
12754     * Create args that describe an existing installed package. Typically used
12755     * when cleaning up old installs, or used as a move source.
12756     */
12757    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12758            String resourcePath, String[] instructionSets) {
12759        final boolean isInAsec;
12760        if (installOnExternalAsec(installFlags)) {
12761            /* Apps on SD card are always in ASEC containers. */
12762            isInAsec = true;
12763        } else if (installForwardLocked(installFlags)
12764                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12765            /*
12766             * Forward-locked apps are only in ASEC containers if they're the
12767             * new style
12768             */
12769            isInAsec = true;
12770        } else {
12771            isInAsec = false;
12772        }
12773
12774        if (isInAsec) {
12775            return new AsecInstallArgs(codePath, instructionSets,
12776                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12777        } else {
12778            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12779        }
12780    }
12781
12782    static abstract class InstallArgs {
12783        /** @see InstallParams#origin */
12784        final OriginInfo origin;
12785        /** @see InstallParams#move */
12786        final MoveInfo move;
12787
12788        final IPackageInstallObserver2 observer;
12789        // Always refers to PackageManager flags only
12790        final int installFlags;
12791        final String installerPackageName;
12792        final String volumeUuid;
12793        final UserHandle user;
12794        final String abiOverride;
12795        final String[] installGrantPermissions;
12796        /** If non-null, drop an async trace when the install completes */
12797        final String traceMethod;
12798        final int traceCookie;
12799        final Certificate[][] certificates;
12800
12801        // The list of instruction sets supported by this app. This is currently
12802        // only used during the rmdex() phase to clean up resources. We can get rid of this
12803        // if we move dex files under the common app path.
12804        /* nullable */ String[] instructionSets;
12805
12806        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12807                int installFlags, String installerPackageName, String volumeUuid,
12808                UserHandle user, String[] instructionSets,
12809                String abiOverride, String[] installGrantPermissions,
12810                String traceMethod, int traceCookie, Certificate[][] certificates) {
12811            this.origin = origin;
12812            this.move = move;
12813            this.installFlags = installFlags;
12814            this.observer = observer;
12815            this.installerPackageName = installerPackageName;
12816            this.volumeUuid = volumeUuid;
12817            this.user = user;
12818            this.instructionSets = instructionSets;
12819            this.abiOverride = abiOverride;
12820            this.installGrantPermissions = installGrantPermissions;
12821            this.traceMethod = traceMethod;
12822            this.traceCookie = traceCookie;
12823            this.certificates = certificates;
12824        }
12825
12826        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12827        abstract int doPreInstall(int status);
12828
12829        /**
12830         * Rename package into final resting place. All paths on the given
12831         * scanned package should be updated to reflect the rename.
12832         */
12833        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12834        abstract int doPostInstall(int status, int uid);
12835
12836        /** @see PackageSettingBase#codePathString */
12837        abstract String getCodePath();
12838        /** @see PackageSettingBase#resourcePathString */
12839        abstract String getResourcePath();
12840
12841        // Need installer lock especially for dex file removal.
12842        abstract void cleanUpResourcesLI();
12843        abstract boolean doPostDeleteLI(boolean delete);
12844
12845        /**
12846         * Called before the source arguments are copied. This is used mostly
12847         * for MoveParams when it needs to read the source file to put it in the
12848         * destination.
12849         */
12850        int doPreCopy() {
12851            return PackageManager.INSTALL_SUCCEEDED;
12852        }
12853
12854        /**
12855         * Called after the source arguments are copied. This is used mostly for
12856         * MoveParams when it needs to read the source file to put it in the
12857         * destination.
12858         */
12859        int doPostCopy(int uid) {
12860            return PackageManager.INSTALL_SUCCEEDED;
12861        }
12862
12863        protected boolean isFwdLocked() {
12864            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12865        }
12866
12867        protected boolean isExternalAsec() {
12868            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12869        }
12870
12871        protected boolean isEphemeral() {
12872            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12873        }
12874
12875        UserHandle getUser() {
12876            return user;
12877        }
12878    }
12879
12880    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12881        if (!allCodePaths.isEmpty()) {
12882            if (instructionSets == null) {
12883                throw new IllegalStateException("instructionSet == null");
12884            }
12885            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12886            for (String codePath : allCodePaths) {
12887                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12888                    try {
12889                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12890                    } catch (InstallerException ignored) {
12891                    }
12892                }
12893            }
12894        }
12895    }
12896
12897    /**
12898     * Logic to handle installation of non-ASEC applications, including copying
12899     * and renaming logic.
12900     */
12901    class FileInstallArgs extends InstallArgs {
12902        private File codeFile;
12903        private File resourceFile;
12904
12905        // Example topology:
12906        // /data/app/com.example/base.apk
12907        // /data/app/com.example/split_foo.apk
12908        // /data/app/com.example/lib/arm/libfoo.so
12909        // /data/app/com.example/lib/arm64/libfoo.so
12910        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12911
12912        /** New install */
12913        FileInstallArgs(InstallParams params) {
12914            super(params.origin, params.move, params.observer, params.installFlags,
12915                    params.installerPackageName, params.volumeUuid,
12916                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12917                    params.grantedRuntimePermissions,
12918                    params.traceMethod, params.traceCookie, params.certificates);
12919            if (isFwdLocked()) {
12920                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12921            }
12922        }
12923
12924        /** Existing install */
12925        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12926            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12927                    null, null, null, 0, null /*certificates*/);
12928            this.codeFile = (codePath != null) ? new File(codePath) : null;
12929            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12930        }
12931
12932        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12933            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12934            try {
12935                return doCopyApk(imcs, temp);
12936            } finally {
12937                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12938            }
12939        }
12940
12941        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12942            if (origin.staged) {
12943                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12944                codeFile = origin.file;
12945                resourceFile = origin.file;
12946                return PackageManager.INSTALL_SUCCEEDED;
12947            }
12948
12949            try {
12950                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12951                final File tempDir =
12952                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12953                codeFile = tempDir;
12954                resourceFile = tempDir;
12955            } catch (IOException e) {
12956                Slog.w(TAG, "Failed to create copy file: " + e);
12957                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12958            }
12959
12960            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12961                @Override
12962                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12963                    if (!FileUtils.isValidExtFilename(name)) {
12964                        throw new IllegalArgumentException("Invalid filename: " + name);
12965                    }
12966                    try {
12967                        final File file = new File(codeFile, name);
12968                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12969                                O_RDWR | O_CREAT, 0644);
12970                        Os.chmod(file.getAbsolutePath(), 0644);
12971                        return new ParcelFileDescriptor(fd);
12972                    } catch (ErrnoException e) {
12973                        throw new RemoteException("Failed to open: " + e.getMessage());
12974                    }
12975                }
12976            };
12977
12978            int ret = PackageManager.INSTALL_SUCCEEDED;
12979            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12980            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12981                Slog.e(TAG, "Failed to copy package");
12982                return ret;
12983            }
12984
12985            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12986            NativeLibraryHelper.Handle handle = null;
12987            try {
12988                handle = NativeLibraryHelper.Handle.create(codeFile);
12989                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12990                        abiOverride);
12991            } catch (IOException e) {
12992                Slog.e(TAG, "Copying native libraries failed", e);
12993                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12994            } finally {
12995                IoUtils.closeQuietly(handle);
12996            }
12997
12998            return ret;
12999        }
13000
13001        int doPreInstall(int status) {
13002            if (status != PackageManager.INSTALL_SUCCEEDED) {
13003                cleanUp();
13004            }
13005            return status;
13006        }
13007
13008        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13009            if (status != PackageManager.INSTALL_SUCCEEDED) {
13010                cleanUp();
13011                return false;
13012            }
13013
13014            final File targetDir = codeFile.getParentFile();
13015            final File beforeCodeFile = codeFile;
13016            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13017
13018            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13019            try {
13020                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13021            } catch (ErrnoException e) {
13022                Slog.w(TAG, "Failed to rename", e);
13023                return false;
13024            }
13025
13026            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13027                Slog.w(TAG, "Failed to restorecon");
13028                return false;
13029            }
13030
13031            // Reflect the rename internally
13032            codeFile = afterCodeFile;
13033            resourceFile = afterCodeFile;
13034
13035            // Reflect the rename in scanned details
13036            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13037            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13038                    afterCodeFile, pkg.baseCodePath));
13039            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13040                    afterCodeFile, pkg.splitCodePaths));
13041
13042            // Reflect the rename in app info
13043            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13044            pkg.setApplicationInfoCodePath(pkg.codePath);
13045            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13046            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13047            pkg.setApplicationInfoResourcePath(pkg.codePath);
13048            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13049            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13050
13051            return true;
13052        }
13053
13054        int doPostInstall(int status, int uid) {
13055            if (status != PackageManager.INSTALL_SUCCEEDED) {
13056                cleanUp();
13057            }
13058            return status;
13059        }
13060
13061        @Override
13062        String getCodePath() {
13063            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13064        }
13065
13066        @Override
13067        String getResourcePath() {
13068            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13069        }
13070
13071        private boolean cleanUp() {
13072            if (codeFile == null || !codeFile.exists()) {
13073                return false;
13074            }
13075
13076            removeCodePathLI(codeFile);
13077
13078            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13079                resourceFile.delete();
13080            }
13081
13082            return true;
13083        }
13084
13085        void cleanUpResourcesLI() {
13086            // Try enumerating all code paths before deleting
13087            List<String> allCodePaths = Collections.EMPTY_LIST;
13088            if (codeFile != null && codeFile.exists()) {
13089                try {
13090                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13091                    allCodePaths = pkg.getAllCodePaths();
13092                } catch (PackageParserException e) {
13093                    // Ignored; we tried our best
13094                }
13095            }
13096
13097            cleanUp();
13098            removeDexFiles(allCodePaths, instructionSets);
13099        }
13100
13101        boolean doPostDeleteLI(boolean delete) {
13102            // XXX err, shouldn't we respect the delete flag?
13103            cleanUpResourcesLI();
13104            return true;
13105        }
13106    }
13107
13108    private boolean isAsecExternal(String cid) {
13109        final String asecPath = PackageHelper.getSdFilesystem(cid);
13110        return !asecPath.startsWith(mAsecInternalPath);
13111    }
13112
13113    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13114            PackageManagerException {
13115        if (copyRet < 0) {
13116            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13117                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13118                throw new PackageManagerException(copyRet, message);
13119            }
13120        }
13121    }
13122
13123    /**
13124     * Extract the MountService "container ID" from the full code path of an
13125     * .apk.
13126     */
13127    static String cidFromCodePath(String fullCodePath) {
13128        int eidx = fullCodePath.lastIndexOf("/");
13129        String subStr1 = fullCodePath.substring(0, eidx);
13130        int sidx = subStr1.lastIndexOf("/");
13131        return subStr1.substring(sidx+1, eidx);
13132    }
13133
13134    /**
13135     * Logic to handle installation of ASEC applications, including copying and
13136     * renaming logic.
13137     */
13138    class AsecInstallArgs extends InstallArgs {
13139        static final String RES_FILE_NAME = "pkg.apk";
13140        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13141
13142        String cid;
13143        String packagePath;
13144        String resourcePath;
13145
13146        /** New install */
13147        AsecInstallArgs(InstallParams params) {
13148            super(params.origin, params.move, params.observer, params.installFlags,
13149                    params.installerPackageName, params.volumeUuid,
13150                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13151                    params.grantedRuntimePermissions,
13152                    params.traceMethod, params.traceCookie, params.certificates);
13153        }
13154
13155        /** Existing install */
13156        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13157                        boolean isExternal, boolean isForwardLocked) {
13158            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13159              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13160                    instructionSets, null, null, null, 0, null /*certificates*/);
13161            // Hackily pretend we're still looking at a full code path
13162            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13163                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13164            }
13165
13166            // Extract cid from fullCodePath
13167            int eidx = fullCodePath.lastIndexOf("/");
13168            String subStr1 = fullCodePath.substring(0, eidx);
13169            int sidx = subStr1.lastIndexOf("/");
13170            cid = subStr1.substring(sidx+1, eidx);
13171            setMountPath(subStr1);
13172        }
13173
13174        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13175            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13176              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13177                    instructionSets, null, null, null, 0, null /*certificates*/);
13178            this.cid = cid;
13179            setMountPath(PackageHelper.getSdDir(cid));
13180        }
13181
13182        void createCopyFile() {
13183            cid = mInstallerService.allocateExternalStageCidLegacy();
13184        }
13185
13186        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13187            if (origin.staged && origin.cid != null) {
13188                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13189                cid = origin.cid;
13190                setMountPath(PackageHelper.getSdDir(cid));
13191                return PackageManager.INSTALL_SUCCEEDED;
13192            }
13193
13194            if (temp) {
13195                createCopyFile();
13196            } else {
13197                /*
13198                 * Pre-emptively destroy the container since it's destroyed if
13199                 * copying fails due to it existing anyway.
13200                 */
13201                PackageHelper.destroySdDir(cid);
13202            }
13203
13204            final String newMountPath = imcs.copyPackageToContainer(
13205                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13206                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13207
13208            if (newMountPath != null) {
13209                setMountPath(newMountPath);
13210                return PackageManager.INSTALL_SUCCEEDED;
13211            } else {
13212                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13213            }
13214        }
13215
13216        @Override
13217        String getCodePath() {
13218            return packagePath;
13219        }
13220
13221        @Override
13222        String getResourcePath() {
13223            return resourcePath;
13224        }
13225
13226        int doPreInstall(int status) {
13227            if (status != PackageManager.INSTALL_SUCCEEDED) {
13228                // Destroy container
13229                PackageHelper.destroySdDir(cid);
13230            } else {
13231                boolean mounted = PackageHelper.isContainerMounted(cid);
13232                if (!mounted) {
13233                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13234                            Process.SYSTEM_UID);
13235                    if (newMountPath != null) {
13236                        setMountPath(newMountPath);
13237                    } else {
13238                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13239                    }
13240                }
13241            }
13242            return status;
13243        }
13244
13245        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13246            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13247            String newMountPath = null;
13248            if (PackageHelper.isContainerMounted(cid)) {
13249                // Unmount the container
13250                if (!PackageHelper.unMountSdDir(cid)) {
13251                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13252                    return false;
13253                }
13254            }
13255            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13256                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13257                        " which might be stale. Will try to clean up.");
13258                // Clean up the stale container and proceed to recreate.
13259                if (!PackageHelper.destroySdDir(newCacheId)) {
13260                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13261                    return false;
13262                }
13263                // Successfully cleaned up stale container. Try to rename again.
13264                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13265                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13266                            + " inspite of cleaning it up.");
13267                    return false;
13268                }
13269            }
13270            if (!PackageHelper.isContainerMounted(newCacheId)) {
13271                Slog.w(TAG, "Mounting container " + newCacheId);
13272                newMountPath = PackageHelper.mountSdDir(newCacheId,
13273                        getEncryptKey(), Process.SYSTEM_UID);
13274            } else {
13275                newMountPath = PackageHelper.getSdDir(newCacheId);
13276            }
13277            if (newMountPath == null) {
13278                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13279                return false;
13280            }
13281            Log.i(TAG, "Succesfully renamed " + cid +
13282                    " to " + newCacheId +
13283                    " at new path: " + newMountPath);
13284            cid = newCacheId;
13285
13286            final File beforeCodeFile = new File(packagePath);
13287            setMountPath(newMountPath);
13288            final File afterCodeFile = new File(packagePath);
13289
13290            // Reflect the rename in scanned details
13291            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13292            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13293                    afterCodeFile, pkg.baseCodePath));
13294            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13295                    afterCodeFile, pkg.splitCodePaths));
13296
13297            // Reflect the rename in app info
13298            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13299            pkg.setApplicationInfoCodePath(pkg.codePath);
13300            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13301            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13302            pkg.setApplicationInfoResourcePath(pkg.codePath);
13303            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13304            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13305
13306            return true;
13307        }
13308
13309        private void setMountPath(String mountPath) {
13310            final File mountFile = new File(mountPath);
13311
13312            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13313            if (monolithicFile.exists()) {
13314                packagePath = monolithicFile.getAbsolutePath();
13315                if (isFwdLocked()) {
13316                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13317                } else {
13318                    resourcePath = packagePath;
13319                }
13320            } else {
13321                packagePath = mountFile.getAbsolutePath();
13322                resourcePath = packagePath;
13323            }
13324        }
13325
13326        int doPostInstall(int status, int uid) {
13327            if (status != PackageManager.INSTALL_SUCCEEDED) {
13328                cleanUp();
13329            } else {
13330                final int groupOwner;
13331                final String protectedFile;
13332                if (isFwdLocked()) {
13333                    groupOwner = UserHandle.getSharedAppGid(uid);
13334                    protectedFile = RES_FILE_NAME;
13335                } else {
13336                    groupOwner = -1;
13337                    protectedFile = null;
13338                }
13339
13340                if (uid < Process.FIRST_APPLICATION_UID
13341                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13342                    Slog.e(TAG, "Failed to finalize " + cid);
13343                    PackageHelper.destroySdDir(cid);
13344                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13345                }
13346
13347                boolean mounted = PackageHelper.isContainerMounted(cid);
13348                if (!mounted) {
13349                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13350                }
13351            }
13352            return status;
13353        }
13354
13355        private void cleanUp() {
13356            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13357
13358            // Destroy secure container
13359            PackageHelper.destroySdDir(cid);
13360        }
13361
13362        private List<String> getAllCodePaths() {
13363            final File codeFile = new File(getCodePath());
13364            if (codeFile != null && codeFile.exists()) {
13365                try {
13366                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13367                    return pkg.getAllCodePaths();
13368                } catch (PackageParserException e) {
13369                    // Ignored; we tried our best
13370                }
13371            }
13372            return Collections.EMPTY_LIST;
13373        }
13374
13375        void cleanUpResourcesLI() {
13376            // Enumerate all code paths before deleting
13377            cleanUpResourcesLI(getAllCodePaths());
13378        }
13379
13380        private void cleanUpResourcesLI(List<String> allCodePaths) {
13381            cleanUp();
13382            removeDexFiles(allCodePaths, instructionSets);
13383        }
13384
13385        String getPackageName() {
13386            return getAsecPackageName(cid);
13387        }
13388
13389        boolean doPostDeleteLI(boolean delete) {
13390            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13391            final List<String> allCodePaths = getAllCodePaths();
13392            boolean mounted = PackageHelper.isContainerMounted(cid);
13393            if (mounted) {
13394                // Unmount first
13395                if (PackageHelper.unMountSdDir(cid)) {
13396                    mounted = false;
13397                }
13398            }
13399            if (!mounted && delete) {
13400                cleanUpResourcesLI(allCodePaths);
13401            }
13402            return !mounted;
13403        }
13404
13405        @Override
13406        int doPreCopy() {
13407            if (isFwdLocked()) {
13408                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13409                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13410                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13411                }
13412            }
13413
13414            return PackageManager.INSTALL_SUCCEEDED;
13415        }
13416
13417        @Override
13418        int doPostCopy(int uid) {
13419            if (isFwdLocked()) {
13420                if (uid < Process.FIRST_APPLICATION_UID
13421                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13422                                RES_FILE_NAME)) {
13423                    Slog.e(TAG, "Failed to finalize " + cid);
13424                    PackageHelper.destroySdDir(cid);
13425                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13426                }
13427            }
13428
13429            return PackageManager.INSTALL_SUCCEEDED;
13430        }
13431    }
13432
13433    /**
13434     * Logic to handle movement of existing installed applications.
13435     */
13436    class MoveInstallArgs extends InstallArgs {
13437        private File codeFile;
13438        private File resourceFile;
13439
13440        /** New install */
13441        MoveInstallArgs(InstallParams params) {
13442            super(params.origin, params.move, params.observer, params.installFlags,
13443                    params.installerPackageName, params.volumeUuid,
13444                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13445                    params.grantedRuntimePermissions,
13446                    params.traceMethod, params.traceCookie, params.certificates);
13447        }
13448
13449        int copyApk(IMediaContainerService imcs, boolean temp) {
13450            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13451                    + move.fromUuid + " to " + move.toUuid);
13452            synchronized (mInstaller) {
13453                try {
13454                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13455                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13456                } catch (InstallerException e) {
13457                    Slog.w(TAG, "Failed to move app", e);
13458                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13459                }
13460            }
13461
13462            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13463            resourceFile = codeFile;
13464            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13465
13466            return PackageManager.INSTALL_SUCCEEDED;
13467        }
13468
13469        int doPreInstall(int status) {
13470            if (status != PackageManager.INSTALL_SUCCEEDED) {
13471                cleanUp(move.toUuid);
13472            }
13473            return status;
13474        }
13475
13476        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13477            if (status != PackageManager.INSTALL_SUCCEEDED) {
13478                cleanUp(move.toUuid);
13479                return false;
13480            }
13481
13482            // Reflect the move in app info
13483            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13484            pkg.setApplicationInfoCodePath(pkg.codePath);
13485            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13486            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13487            pkg.setApplicationInfoResourcePath(pkg.codePath);
13488            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13489            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13490
13491            return true;
13492        }
13493
13494        int doPostInstall(int status, int uid) {
13495            if (status == PackageManager.INSTALL_SUCCEEDED) {
13496                cleanUp(move.fromUuid);
13497            } else {
13498                cleanUp(move.toUuid);
13499            }
13500            return status;
13501        }
13502
13503        @Override
13504        String getCodePath() {
13505            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13506        }
13507
13508        @Override
13509        String getResourcePath() {
13510            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13511        }
13512
13513        private boolean cleanUp(String volumeUuid) {
13514            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13515                    move.dataAppName);
13516            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13517            final int[] userIds = sUserManager.getUserIds();
13518            synchronized (mInstallLock) {
13519                // Clean up both app data and code
13520                // All package moves are frozen until finished
13521                for (int userId : userIds) {
13522                    try {
13523                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13524                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13525                    } catch (InstallerException e) {
13526                        Slog.w(TAG, String.valueOf(e));
13527                    }
13528                }
13529                removeCodePathLI(codeFile);
13530            }
13531            return true;
13532        }
13533
13534        void cleanUpResourcesLI() {
13535            throw new UnsupportedOperationException();
13536        }
13537
13538        boolean doPostDeleteLI(boolean delete) {
13539            throw new UnsupportedOperationException();
13540        }
13541    }
13542
13543    static String getAsecPackageName(String packageCid) {
13544        int idx = packageCid.lastIndexOf("-");
13545        if (idx == -1) {
13546            return packageCid;
13547        }
13548        return packageCid.substring(0, idx);
13549    }
13550
13551    // Utility method used to create code paths based on package name and available index.
13552    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13553        String idxStr = "";
13554        int idx = 1;
13555        // Fall back to default value of idx=1 if prefix is not
13556        // part of oldCodePath
13557        if (oldCodePath != null) {
13558            String subStr = oldCodePath;
13559            // Drop the suffix right away
13560            if (suffix != null && subStr.endsWith(suffix)) {
13561                subStr = subStr.substring(0, subStr.length() - suffix.length());
13562            }
13563            // If oldCodePath already contains prefix find out the
13564            // ending index to either increment or decrement.
13565            int sidx = subStr.lastIndexOf(prefix);
13566            if (sidx != -1) {
13567                subStr = subStr.substring(sidx + prefix.length());
13568                if (subStr != null) {
13569                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13570                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13571                    }
13572                    try {
13573                        idx = Integer.parseInt(subStr);
13574                        if (idx <= 1) {
13575                            idx++;
13576                        } else {
13577                            idx--;
13578                        }
13579                    } catch(NumberFormatException e) {
13580                    }
13581                }
13582            }
13583        }
13584        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13585        return prefix + idxStr;
13586    }
13587
13588    private File getNextCodePath(File targetDir, String packageName) {
13589        int suffix = 1;
13590        File result;
13591        do {
13592            result = new File(targetDir, packageName + "-" + suffix);
13593            suffix++;
13594        } while (result.exists());
13595        return result;
13596    }
13597
13598    // Utility method that returns the relative package path with respect
13599    // to the installation directory. Like say for /data/data/com.test-1.apk
13600    // string com.test-1 is returned.
13601    static String deriveCodePathName(String codePath) {
13602        if (codePath == null) {
13603            return null;
13604        }
13605        final File codeFile = new File(codePath);
13606        final String name = codeFile.getName();
13607        if (codeFile.isDirectory()) {
13608            return name;
13609        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13610            final int lastDot = name.lastIndexOf('.');
13611            return name.substring(0, lastDot);
13612        } else {
13613            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13614            return null;
13615        }
13616    }
13617
13618    static class PackageInstalledInfo {
13619        String name;
13620        int uid;
13621        // The set of users that originally had this package installed.
13622        int[] origUsers;
13623        // The set of users that now have this package installed.
13624        int[] newUsers;
13625        PackageParser.Package pkg;
13626        int returnCode;
13627        String returnMsg;
13628        PackageRemovedInfo removedInfo;
13629        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13630
13631        public void setError(int code, String msg) {
13632            setReturnCode(code);
13633            setReturnMessage(msg);
13634            Slog.w(TAG, msg);
13635        }
13636
13637        public void setError(String msg, PackageParserException e) {
13638            setReturnCode(e.error);
13639            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13640            Slog.w(TAG, msg, e);
13641        }
13642
13643        public void setError(String msg, PackageManagerException e) {
13644            returnCode = e.error;
13645            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13646            Slog.w(TAG, msg, e);
13647        }
13648
13649        public void setReturnCode(int returnCode) {
13650            this.returnCode = returnCode;
13651            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13652            for (int i = 0; i < childCount; i++) {
13653                addedChildPackages.valueAt(i).returnCode = returnCode;
13654            }
13655        }
13656
13657        private void setReturnMessage(String returnMsg) {
13658            this.returnMsg = returnMsg;
13659            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13660            for (int i = 0; i < childCount; i++) {
13661                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13662            }
13663        }
13664
13665        // In some error cases we want to convey more info back to the observer
13666        String origPackage;
13667        String origPermission;
13668    }
13669
13670    /*
13671     * Install a non-existing package.
13672     */
13673    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13674            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13675            PackageInstalledInfo res) {
13676        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13677
13678        // Remember this for later, in case we need to rollback this install
13679        String pkgName = pkg.packageName;
13680
13681        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13682
13683        synchronized(mPackages) {
13684            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13685                // A package with the same name is already installed, though
13686                // it has been renamed to an older name.  The package we
13687                // are trying to install should be installed as an update to
13688                // the existing one, but that has not been requested, so bail.
13689                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13690                        + " without first uninstalling package running as "
13691                        + mSettings.mRenamedPackages.get(pkgName));
13692                return;
13693            }
13694            if (mPackages.containsKey(pkgName)) {
13695                // Don't allow installation over an existing package with the same name.
13696                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13697                        + " without first uninstalling.");
13698                return;
13699            }
13700        }
13701
13702        try {
13703            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13704                    System.currentTimeMillis(), user);
13705
13706            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13707
13708            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13709                prepareAppDataAfterInstallLIF(newPackage);
13710
13711            } else {
13712                // Remove package from internal structures, but keep around any
13713                // data that might have already existed
13714                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13715                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13716            }
13717        } catch (PackageManagerException e) {
13718            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13719        }
13720
13721        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13722    }
13723
13724    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13725        // Can't rotate keys during boot or if sharedUser.
13726        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13727                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13728            return false;
13729        }
13730        // app is using upgradeKeySets; make sure all are valid
13731        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13732        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13733        for (int i = 0; i < upgradeKeySets.length; i++) {
13734            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13735                Slog.wtf(TAG, "Package "
13736                         + (oldPs.name != null ? oldPs.name : "<null>")
13737                         + " contains upgrade-key-set reference to unknown key-set: "
13738                         + upgradeKeySets[i]
13739                         + " reverting to signatures check.");
13740                return false;
13741            }
13742        }
13743        return true;
13744    }
13745
13746    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13747        // Upgrade keysets are being used.  Determine if new package has a superset of the
13748        // required keys.
13749        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13750        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13751        for (int i = 0; i < upgradeKeySets.length; i++) {
13752            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13753            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13754                return true;
13755            }
13756        }
13757        return false;
13758    }
13759
13760    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13761            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13762        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13763
13764        final PackageParser.Package oldPackage;
13765        final String pkgName = pkg.packageName;
13766        final int[] allUsers;
13767        final int[] installedUsers;
13768
13769        synchronized(mPackages) {
13770            oldPackage = mPackages.get(pkgName);
13771            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13772
13773            // don't allow upgrade to target a release SDK from a pre-release SDK
13774            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13775                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13776            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13777                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13778            if (oldTargetsPreRelease
13779                    && !newTargetsPreRelease
13780                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13781                Slog.w(TAG, "Can't install package targeting released sdk");
13782                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13783                return;
13784            }
13785
13786            // don't allow an upgrade from full to ephemeral
13787            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13788            if (isEphemeral && !oldIsEphemeral) {
13789                // can't downgrade from full to ephemeral
13790                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13791                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13792                return;
13793            }
13794
13795            // verify signatures are valid
13796            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13797            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13798                if (!checkUpgradeKeySetLP(ps, pkg)) {
13799                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13800                            "New package not signed by keys specified by upgrade-keysets: "
13801                                    + pkgName);
13802                    return;
13803                }
13804            } else {
13805                // default to original signature matching
13806                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13807                        != PackageManager.SIGNATURE_MATCH) {
13808                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13809                            "New package has a different signature: " + pkgName);
13810                    return;
13811                }
13812            }
13813
13814            // Check for shared user id changes
13815            String invalidPackageName =
13816                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13817            if (invalidPackageName != null) {
13818                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13819                        "Package " + invalidPackageName + " tried to change user "
13820                                + oldPackage.mSharedUserId);
13821                return;
13822            }
13823
13824            // In case of rollback, remember per-user/profile install state
13825            allUsers = sUserManager.getUserIds();
13826            installedUsers = ps.queryInstalledUsers(allUsers, true);
13827        }
13828
13829        // Update what is removed
13830        res.removedInfo = new PackageRemovedInfo();
13831        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13832        res.removedInfo.removedPackage = oldPackage.packageName;
13833        res.removedInfo.isUpdate = true;
13834        res.removedInfo.origUsers = installedUsers;
13835        final int childCount = (oldPackage.childPackages != null)
13836                ? oldPackage.childPackages.size() : 0;
13837        for (int i = 0; i < childCount; i++) {
13838            boolean childPackageUpdated = false;
13839            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13840            if (res.addedChildPackages != null) {
13841                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13842                if (childRes != null) {
13843                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13844                    childRes.removedInfo.removedPackage = childPkg.packageName;
13845                    childRes.removedInfo.isUpdate = true;
13846                    childPackageUpdated = true;
13847                }
13848            }
13849            if (!childPackageUpdated) {
13850                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13851                childRemovedRes.removedPackage = childPkg.packageName;
13852                childRemovedRes.isUpdate = false;
13853                childRemovedRes.dataRemoved = true;
13854                synchronized (mPackages) {
13855                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13856                    if (childPs != null) {
13857                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13858                    }
13859                }
13860                if (res.removedInfo.removedChildPackages == null) {
13861                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13862                }
13863                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13864            }
13865        }
13866
13867        boolean sysPkg = (isSystemApp(oldPackage));
13868        if (sysPkg) {
13869            // Set the system/privileged flags as needed
13870            final boolean privileged =
13871                    (oldPackage.applicationInfo.privateFlags
13872                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13873            final int systemPolicyFlags = policyFlags
13874                    | PackageParser.PARSE_IS_SYSTEM
13875                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13876
13877            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13878                    user, allUsers, installerPackageName, res);
13879        } else {
13880            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13881                    user, allUsers, installerPackageName, res);
13882        }
13883    }
13884
13885    public List<String> getPreviousCodePaths(String packageName) {
13886        final PackageSetting ps = mSettings.mPackages.get(packageName);
13887        final List<String> result = new ArrayList<String>();
13888        if (ps != null && ps.oldCodePaths != null) {
13889            result.addAll(ps.oldCodePaths);
13890        }
13891        return result;
13892    }
13893
13894    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13895            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13896            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13897        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13898                + deletedPackage);
13899
13900        String pkgName = deletedPackage.packageName;
13901        boolean deletedPkg = true;
13902        boolean addedPkg = false;
13903        boolean updatedSettings = false;
13904        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13905        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13906                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13907
13908        final long origUpdateTime = (pkg.mExtras != null)
13909                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13910
13911        // First delete the existing package while retaining the data directory
13912        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13913                res.removedInfo, true, pkg)) {
13914            // If the existing package wasn't successfully deleted
13915            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13916            deletedPkg = false;
13917        } else {
13918            // Successfully deleted the old package; proceed with replace.
13919
13920            // If deleted package lived in a container, give users a chance to
13921            // relinquish resources before killing.
13922            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13923                if (DEBUG_INSTALL) {
13924                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13925                }
13926                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13927                final ArrayList<String> pkgList = new ArrayList<String>(1);
13928                pkgList.add(deletedPackage.applicationInfo.packageName);
13929                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13930            }
13931
13932            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13933                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13934            clearAppProfilesLIF(pkg);
13935
13936            try {
13937                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
13938                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13939                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13940
13941                // Update the in-memory copy of the previous code paths.
13942                PackageSetting ps = mSettings.mPackages.get(pkgName);
13943                if (!killApp) {
13944                    if (ps.oldCodePaths == null) {
13945                        ps.oldCodePaths = new ArraySet<>();
13946                    }
13947                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13948                    if (deletedPackage.splitCodePaths != null) {
13949                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13950                    }
13951                } else {
13952                    ps.oldCodePaths = null;
13953                }
13954                if (ps.childPackageNames != null) {
13955                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13956                        final String childPkgName = ps.childPackageNames.get(i);
13957                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13958                        childPs.oldCodePaths = ps.oldCodePaths;
13959                    }
13960                }
13961                prepareAppDataAfterInstallLIF(newPackage);
13962                addedPkg = true;
13963            } catch (PackageManagerException e) {
13964                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13965            }
13966        }
13967
13968        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13969            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13970
13971            // Revert all internal state mutations and added folders for the failed install
13972            if (addedPkg) {
13973                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13974                        res.removedInfo, true, null);
13975            }
13976
13977            // Restore the old package
13978            if (deletedPkg) {
13979                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13980                File restoreFile = new File(deletedPackage.codePath);
13981                // Parse old package
13982                boolean oldExternal = isExternal(deletedPackage);
13983                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13984                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13985                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13986                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13987                try {
13988                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13989                            null);
13990                } catch (PackageManagerException e) {
13991                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13992                            + e.getMessage());
13993                    return;
13994                }
13995
13996                synchronized (mPackages) {
13997                    // Ensure the installer package name up to date
13998                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13999
14000                    // Update permissions for restored package
14001                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14002
14003                    mSettings.writeLPr();
14004                }
14005
14006                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14007            }
14008        } else {
14009            synchronized (mPackages) {
14010                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14011                if (ps != null) {
14012                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14013                    if (res.removedInfo.removedChildPackages != null) {
14014                        final int childCount = res.removedInfo.removedChildPackages.size();
14015                        // Iterate in reverse as we may modify the collection
14016                        for (int i = childCount - 1; i >= 0; i--) {
14017                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14018                            if (res.addedChildPackages.containsKey(childPackageName)) {
14019                                res.removedInfo.removedChildPackages.removeAt(i);
14020                            } else {
14021                                PackageRemovedInfo childInfo = res.removedInfo
14022                                        .removedChildPackages.valueAt(i);
14023                                childInfo.removedForAllUsers = mPackages.get(
14024                                        childInfo.removedPackage) == null;
14025                            }
14026                        }
14027                    }
14028                }
14029            }
14030        }
14031    }
14032
14033    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14034            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14035            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14036        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14037                + ", old=" + deletedPackage);
14038
14039        final boolean disabledSystem;
14040
14041        // Remove existing system package
14042        removePackageLI(deletedPackage, true);
14043
14044        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14045        if (!disabledSystem) {
14046            // We didn't need to disable the .apk as a current system package,
14047            // which means we are replacing another update that is already
14048            // installed.  We need to make sure to delete the older one's .apk.
14049            res.removedInfo.args = createInstallArgsForExisting(0,
14050                    deletedPackage.applicationInfo.getCodePath(),
14051                    deletedPackage.applicationInfo.getResourcePath(),
14052                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14053        } else {
14054            res.removedInfo.args = null;
14055        }
14056
14057        // Successfully disabled the old package. Now proceed with re-installation
14058        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14059                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14060        clearAppProfilesLIF(pkg);
14061
14062        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14063        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14064                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14065
14066        PackageParser.Package newPackage = null;
14067        try {
14068            // Add the package to the internal data structures
14069            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14070
14071            // Set the update and install times
14072            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14073            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14074                    System.currentTimeMillis());
14075
14076            // Update the package dynamic state if succeeded
14077            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14078                // Now that the install succeeded make sure we remove data
14079                // directories for any child package the update removed.
14080                final int deletedChildCount = (deletedPackage.childPackages != null)
14081                        ? deletedPackage.childPackages.size() : 0;
14082                final int newChildCount = (newPackage.childPackages != null)
14083                        ? newPackage.childPackages.size() : 0;
14084                for (int i = 0; i < deletedChildCount; i++) {
14085                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14086                    boolean childPackageDeleted = true;
14087                    for (int j = 0; j < newChildCount; j++) {
14088                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14089                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14090                            childPackageDeleted = false;
14091                            break;
14092                        }
14093                    }
14094                    if (childPackageDeleted) {
14095                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14096                                deletedChildPkg.packageName);
14097                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14098                            PackageRemovedInfo removedChildRes = res.removedInfo
14099                                    .removedChildPackages.get(deletedChildPkg.packageName);
14100                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14101                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14102                        }
14103                    }
14104                }
14105
14106                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14107                prepareAppDataAfterInstallLIF(newPackage);
14108            }
14109        } catch (PackageManagerException e) {
14110            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14111            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14112        }
14113
14114        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14115            // Re installation failed. Restore old information
14116            // Remove new pkg information
14117            if (newPackage != null) {
14118                removeInstalledPackageLI(newPackage, true);
14119            }
14120            // Add back the old system package
14121            try {
14122                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14123            } catch (PackageManagerException e) {
14124                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14125            }
14126
14127            synchronized (mPackages) {
14128                if (disabledSystem) {
14129                    enableSystemPackageLPw(deletedPackage);
14130                }
14131
14132                // Ensure the installer package name up to date
14133                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14134
14135                // Update permissions for restored package
14136                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14137
14138                mSettings.writeLPr();
14139            }
14140
14141            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14142                    + " after failed upgrade");
14143        }
14144    }
14145
14146    /**
14147     * Checks whether the parent or any of the child packages have a change shared
14148     * user. For a package to be a valid update the shred users of the parent and
14149     * the children should match. We may later support changing child shared users.
14150     * @param oldPkg The updated package.
14151     * @param newPkg The update package.
14152     * @return The shared user that change between the versions.
14153     */
14154    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14155            PackageParser.Package newPkg) {
14156        // Check parent shared user
14157        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14158            return newPkg.packageName;
14159        }
14160        // Check child shared users
14161        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14162        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14163        for (int i = 0; i < newChildCount; i++) {
14164            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14165            // If this child was present, did it have the same shared user?
14166            for (int j = 0; j < oldChildCount; j++) {
14167                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14168                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14169                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14170                    return newChildPkg.packageName;
14171                }
14172            }
14173        }
14174        return null;
14175    }
14176
14177    private void removeNativeBinariesLI(PackageSetting ps) {
14178        // Remove the lib path for the parent package
14179        if (ps != null) {
14180            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14181            // Remove the lib path for the child packages
14182            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14183            for (int i = 0; i < childCount; i++) {
14184                PackageSetting childPs = null;
14185                synchronized (mPackages) {
14186                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14187                }
14188                if (childPs != null) {
14189                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14190                            .legacyNativeLibraryPathString);
14191                }
14192            }
14193        }
14194    }
14195
14196    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14197        // Enable the parent package
14198        mSettings.enableSystemPackageLPw(pkg.packageName);
14199        // Enable the child packages
14200        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14201        for (int i = 0; i < childCount; i++) {
14202            PackageParser.Package childPkg = pkg.childPackages.get(i);
14203            mSettings.enableSystemPackageLPw(childPkg.packageName);
14204        }
14205    }
14206
14207    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14208            PackageParser.Package newPkg) {
14209        // Disable the parent package (parent always replaced)
14210        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14211        // Disable the child packages
14212        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14213        for (int i = 0; i < childCount; i++) {
14214            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14215            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14216            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14217        }
14218        return disabled;
14219    }
14220
14221    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14222            String installerPackageName) {
14223        // Enable the parent package
14224        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14225        // Enable the child packages
14226        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14227        for (int i = 0; i < childCount; i++) {
14228            PackageParser.Package childPkg = pkg.childPackages.get(i);
14229            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14230        }
14231    }
14232
14233    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14234        // Collect all used permissions in the UID
14235        ArraySet<String> usedPermissions = new ArraySet<>();
14236        final int packageCount = su.packages.size();
14237        for (int i = 0; i < packageCount; i++) {
14238            PackageSetting ps = su.packages.valueAt(i);
14239            if (ps.pkg == null) {
14240                continue;
14241            }
14242            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14243            for (int j = 0; j < requestedPermCount; j++) {
14244                String permission = ps.pkg.requestedPermissions.get(j);
14245                BasePermission bp = mSettings.mPermissions.get(permission);
14246                if (bp != null) {
14247                    usedPermissions.add(permission);
14248                }
14249            }
14250        }
14251
14252        PermissionsState permissionsState = su.getPermissionsState();
14253        // Prune install permissions
14254        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14255        final int installPermCount = installPermStates.size();
14256        for (int i = installPermCount - 1; i >= 0;  i--) {
14257            PermissionState permissionState = installPermStates.get(i);
14258            if (!usedPermissions.contains(permissionState.getName())) {
14259                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14260                if (bp != null) {
14261                    permissionsState.revokeInstallPermission(bp);
14262                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14263                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14264                }
14265            }
14266        }
14267
14268        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14269
14270        // Prune runtime permissions
14271        for (int userId : allUserIds) {
14272            List<PermissionState> runtimePermStates = permissionsState
14273                    .getRuntimePermissionStates(userId);
14274            final int runtimePermCount = runtimePermStates.size();
14275            for (int i = runtimePermCount - 1; i >= 0; i--) {
14276                PermissionState permissionState = runtimePermStates.get(i);
14277                if (!usedPermissions.contains(permissionState.getName())) {
14278                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14279                    if (bp != null) {
14280                        permissionsState.revokeRuntimePermission(bp, userId);
14281                        permissionsState.updatePermissionFlags(bp, userId,
14282                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14283                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14284                                runtimePermissionChangedUserIds, userId);
14285                    }
14286                }
14287            }
14288        }
14289
14290        return runtimePermissionChangedUserIds;
14291    }
14292
14293    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14294            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14295        // Update the parent package setting
14296        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14297                res, user);
14298        // Update the child packages setting
14299        final int childCount = (newPackage.childPackages != null)
14300                ? newPackage.childPackages.size() : 0;
14301        for (int i = 0; i < childCount; i++) {
14302            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14303            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14304            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14305                    childRes.origUsers, childRes, user);
14306        }
14307    }
14308
14309    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14310            String installerPackageName, int[] allUsers, int[] installedForUsers,
14311            PackageInstalledInfo res, UserHandle user) {
14312        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14313
14314        String pkgName = newPackage.packageName;
14315        synchronized (mPackages) {
14316            //write settings. the installStatus will be incomplete at this stage.
14317            //note that the new package setting would have already been
14318            //added to mPackages. It hasn't been persisted yet.
14319            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14320            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14321            mSettings.writeLPr();
14322            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14323        }
14324
14325        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14326        synchronized (mPackages) {
14327            updatePermissionsLPw(newPackage.packageName, newPackage,
14328                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14329                            ? UPDATE_PERMISSIONS_ALL : 0));
14330            // For system-bundled packages, we assume that installing an upgraded version
14331            // of the package implies that the user actually wants to run that new code,
14332            // so we enable the package.
14333            PackageSetting ps = mSettings.mPackages.get(pkgName);
14334            final int userId = user.getIdentifier();
14335            if (ps != null) {
14336                if (isSystemApp(newPackage)) {
14337                    if (DEBUG_INSTALL) {
14338                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14339                    }
14340                    // Enable system package for requested users
14341                    if (res.origUsers != null) {
14342                        for (int origUserId : res.origUsers) {
14343                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14344                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14345                                        origUserId, installerPackageName);
14346                            }
14347                        }
14348                    }
14349                    // Also convey the prior install/uninstall state
14350                    if (allUsers != null && installedForUsers != null) {
14351                        for (int currentUserId : allUsers) {
14352                            final boolean installed = ArrayUtils.contains(
14353                                    installedForUsers, currentUserId);
14354                            if (DEBUG_INSTALL) {
14355                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14356                            }
14357                            ps.setInstalled(installed, currentUserId);
14358                        }
14359                        // these install state changes will be persisted in the
14360                        // upcoming call to mSettings.writeLPr().
14361                    }
14362                }
14363                // It's implied that when a user requests installation, they want the app to be
14364                // installed and enabled.
14365                if (userId != UserHandle.USER_ALL) {
14366                    ps.setInstalled(true, userId);
14367                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14368                }
14369            }
14370            res.name = pkgName;
14371            res.uid = newPackage.applicationInfo.uid;
14372            res.pkg = newPackage;
14373            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14374            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14375            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14376            //to update install status
14377            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14378            mSettings.writeLPr();
14379            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14380        }
14381
14382        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14383    }
14384
14385    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14386        try {
14387            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14388            installPackageLI(args, res);
14389        } finally {
14390            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14391        }
14392    }
14393
14394    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14395        final int installFlags = args.installFlags;
14396        final String installerPackageName = args.installerPackageName;
14397        final String volumeUuid = args.volumeUuid;
14398        final File tmpPackageFile = new File(args.getCodePath());
14399        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14400        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14401                || (args.volumeUuid != null));
14402        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14403        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14404        boolean replace = false;
14405        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14406        if (args.move != null) {
14407            // moving a complete application; perform an initial scan on the new install location
14408            scanFlags |= SCAN_INITIAL;
14409        }
14410        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14411            scanFlags |= SCAN_DONT_KILL_APP;
14412        }
14413
14414        // Result object to be returned
14415        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14416
14417        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14418
14419        // Sanity check
14420        if (ephemeral && (forwardLocked || onExternal)) {
14421            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14422                    + " external=" + onExternal);
14423            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14424            return;
14425        }
14426
14427        // Retrieve PackageSettings and parse package
14428        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14429                | PackageParser.PARSE_ENFORCE_CODE
14430                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14431                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14432                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14433                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14434        PackageParser pp = new PackageParser();
14435        pp.setSeparateProcesses(mSeparateProcesses);
14436        pp.setDisplayMetrics(mMetrics);
14437
14438        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14439        final PackageParser.Package pkg;
14440        try {
14441            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14442        } catch (PackageParserException e) {
14443            res.setError("Failed parse during installPackageLI", e);
14444            return;
14445        } finally {
14446            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14447        }
14448
14449        // If we are installing a clustered package add results for the children
14450        if (pkg.childPackages != null) {
14451            synchronized (mPackages) {
14452                final int childCount = pkg.childPackages.size();
14453                for (int i = 0; i < childCount; i++) {
14454                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14455                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14456                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14457                    childRes.pkg = childPkg;
14458                    childRes.name = childPkg.packageName;
14459                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14460                    if (childPs != null) {
14461                        childRes.origUsers = childPs.queryInstalledUsers(
14462                                sUserManager.getUserIds(), true);
14463                    }
14464                    if ((mPackages.containsKey(childPkg.packageName))) {
14465                        childRes.removedInfo = new PackageRemovedInfo();
14466                        childRes.removedInfo.removedPackage = childPkg.packageName;
14467                    }
14468                    if (res.addedChildPackages == null) {
14469                        res.addedChildPackages = new ArrayMap<>();
14470                    }
14471                    res.addedChildPackages.put(childPkg.packageName, childRes);
14472                }
14473            }
14474        }
14475
14476        // If package doesn't declare API override, mark that we have an install
14477        // time CPU ABI override.
14478        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14479            pkg.cpuAbiOverride = args.abiOverride;
14480        }
14481
14482        String pkgName = res.name = pkg.packageName;
14483        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14484            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14485                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14486                return;
14487            }
14488        }
14489
14490        try {
14491            // either use what we've been given or parse directly from the APK
14492            if (args.certificates != null) {
14493                try {
14494                    PackageParser.populateCertificates(pkg, args.certificates);
14495                } catch (PackageParserException e) {
14496                    // there was something wrong with the certificates we were given;
14497                    // try to pull them from the APK
14498                    PackageParser.collectCertificates(pkg, parseFlags);
14499                }
14500            } else {
14501                PackageParser.collectCertificates(pkg, parseFlags);
14502            }
14503        } catch (PackageParserException e) {
14504            res.setError("Failed collect during installPackageLI", e);
14505            return;
14506        }
14507
14508        // Get rid of all references to package scan path via parser.
14509        pp = null;
14510        String oldCodePath = null;
14511        boolean systemApp = false;
14512        synchronized (mPackages) {
14513            // Check if installing already existing package
14514            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14515                String oldName = mSettings.mRenamedPackages.get(pkgName);
14516                if (pkg.mOriginalPackages != null
14517                        && pkg.mOriginalPackages.contains(oldName)
14518                        && mPackages.containsKey(oldName)) {
14519                    // This package is derived from an original package,
14520                    // and this device has been updating from that original
14521                    // name.  We must continue using the original name, so
14522                    // rename the new package here.
14523                    pkg.setPackageName(oldName);
14524                    pkgName = pkg.packageName;
14525                    replace = true;
14526                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14527                            + oldName + " pkgName=" + pkgName);
14528                } else if (mPackages.containsKey(pkgName)) {
14529                    // This package, under its official name, already exists
14530                    // on the device; we should replace it.
14531                    replace = true;
14532                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14533                }
14534
14535                // Child packages are installed through the parent package
14536                if (pkg.parentPackage != null) {
14537                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14538                            "Package " + pkg.packageName + " is child of package "
14539                                    + pkg.parentPackage.parentPackage + ". Child packages "
14540                                    + "can be updated only through the parent package.");
14541                    return;
14542                }
14543
14544                if (replace) {
14545                    // Prevent apps opting out from runtime permissions
14546                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14547                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14548                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14549                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14550                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14551                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14552                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14553                                        + " doesn't support runtime permissions but the old"
14554                                        + " target SDK " + oldTargetSdk + " does.");
14555                        return;
14556                    }
14557
14558                    // Prevent installing of child packages
14559                    if (oldPackage.parentPackage != null) {
14560                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14561                                "Package " + pkg.packageName + " is child of package "
14562                                        + oldPackage.parentPackage + ". Child packages "
14563                                        + "can be updated only through the parent package.");
14564                        return;
14565                    }
14566                }
14567            }
14568
14569            PackageSetting ps = mSettings.mPackages.get(pkgName);
14570            if (ps != null) {
14571                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14572
14573                // Quick sanity check that we're signed correctly if updating;
14574                // we'll check this again later when scanning, but we want to
14575                // bail early here before tripping over redefined permissions.
14576                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14577                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14578                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14579                                + pkg.packageName + " upgrade keys do not match the "
14580                                + "previously installed version");
14581                        return;
14582                    }
14583                } else {
14584                    try {
14585                        verifySignaturesLP(ps, pkg);
14586                    } catch (PackageManagerException e) {
14587                        res.setError(e.error, e.getMessage());
14588                        return;
14589                    }
14590                }
14591
14592                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14593                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14594                    systemApp = (ps.pkg.applicationInfo.flags &
14595                            ApplicationInfo.FLAG_SYSTEM) != 0;
14596                }
14597                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14598            }
14599
14600            // Check whether the newly-scanned package wants to define an already-defined perm
14601            int N = pkg.permissions.size();
14602            for (int i = N-1; i >= 0; i--) {
14603                PackageParser.Permission perm = pkg.permissions.get(i);
14604                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14605                if (bp != null) {
14606                    // If the defining package is signed with our cert, it's okay.  This
14607                    // also includes the "updating the same package" case, of course.
14608                    // "updating same package" could also involve key-rotation.
14609                    final boolean sigsOk;
14610                    if (bp.sourcePackage.equals(pkg.packageName)
14611                            && (bp.packageSetting instanceof PackageSetting)
14612                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14613                                    scanFlags))) {
14614                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14615                    } else {
14616                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14617                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14618                    }
14619                    if (!sigsOk) {
14620                        // If the owning package is the system itself, we log but allow
14621                        // install to proceed; we fail the install on all other permission
14622                        // redefinitions.
14623                        if (!bp.sourcePackage.equals("android")) {
14624                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14625                                    + pkg.packageName + " attempting to redeclare permission "
14626                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14627                            res.origPermission = perm.info.name;
14628                            res.origPackage = bp.sourcePackage;
14629                            return;
14630                        } else {
14631                            Slog.w(TAG, "Package " + pkg.packageName
14632                                    + " attempting to redeclare system permission "
14633                                    + perm.info.name + "; ignoring new declaration");
14634                            pkg.permissions.remove(i);
14635                        }
14636                    }
14637                }
14638            }
14639        }
14640
14641        if (systemApp) {
14642            if (onExternal) {
14643                // Abort update; system app can't be replaced with app on sdcard
14644                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14645                        "Cannot install updates to system apps on sdcard");
14646                return;
14647            } else if (ephemeral) {
14648                // Abort update; system app can't be replaced with an ephemeral app
14649                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14650                        "Cannot update a system app with an ephemeral app");
14651                return;
14652            }
14653        }
14654
14655        if (args.move != null) {
14656            // We did an in-place move, so dex is ready to roll
14657            scanFlags |= SCAN_NO_DEX;
14658            scanFlags |= SCAN_MOVE;
14659
14660            synchronized (mPackages) {
14661                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14662                if (ps == null) {
14663                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14664                            "Missing settings for moved package " + pkgName);
14665                }
14666
14667                // We moved the entire application as-is, so bring over the
14668                // previously derived ABI information.
14669                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14670                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14671            }
14672
14673        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14674            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14675            scanFlags |= SCAN_NO_DEX;
14676
14677            try {
14678                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14679                    args.abiOverride : pkg.cpuAbiOverride);
14680                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14681                        true /* extract libs */);
14682            } catch (PackageManagerException pme) {
14683                Slog.e(TAG, "Error deriving application ABI", pme);
14684                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14685                return;
14686            }
14687
14688            // Shared libraries for the package need to be updated.
14689            synchronized (mPackages) {
14690                try {
14691                    updateSharedLibrariesLPw(pkg, null);
14692                } catch (PackageManagerException e) {
14693                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14694                }
14695            }
14696            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14697            // Do not run PackageDexOptimizer through the local performDexOpt
14698            // method because `pkg` is not in `mPackages` yet.
14699            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14700                    null /* instructionSets */, false /* checkProfiles */,
14701                    getCompilerFilterForReason(REASON_INSTALL));
14702            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14703            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14704                String msg = "Extracting package failed for " + pkgName;
14705                res.setError(INSTALL_FAILED_DEXOPT, msg);
14706                return;
14707            }
14708
14709            // Notify BackgroundDexOptService that the package has been changed.
14710            // If this is an update of a package which used to fail to compile,
14711            // BDOS will remove it from its blacklist.
14712            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14713        }
14714
14715        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14716            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14717            return;
14718        }
14719
14720        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14721
14722        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14723                "installPackageLI")) {
14724            if (replace) {
14725                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14726                        installerPackageName, res);
14727            } else {
14728                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14729                        args.user, installerPackageName, volumeUuid, res);
14730            }
14731        }
14732        synchronized (mPackages) {
14733            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14734            if (ps != null) {
14735                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14736            }
14737
14738            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14739            for (int i = 0; i < childCount; i++) {
14740                PackageParser.Package childPkg = pkg.childPackages.get(i);
14741                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14742                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14743                if (childPs != null) {
14744                    childRes.newUsers = childPs.queryInstalledUsers(
14745                            sUserManager.getUserIds(), true);
14746                }
14747            }
14748        }
14749    }
14750
14751    private void startIntentFilterVerifications(int userId, boolean replacing,
14752            PackageParser.Package pkg) {
14753        if (mIntentFilterVerifierComponent == null) {
14754            Slog.w(TAG, "No IntentFilter verification will not be done as "
14755                    + "there is no IntentFilterVerifier available!");
14756            return;
14757        }
14758
14759        final int verifierUid = getPackageUid(
14760                mIntentFilterVerifierComponent.getPackageName(),
14761                MATCH_DEBUG_TRIAGED_MISSING,
14762                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14763
14764        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14765        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14766        mHandler.sendMessage(msg);
14767
14768        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14769        for (int i = 0; i < childCount; i++) {
14770            PackageParser.Package childPkg = pkg.childPackages.get(i);
14771            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14772            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14773            mHandler.sendMessage(msg);
14774        }
14775    }
14776
14777    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14778            PackageParser.Package pkg) {
14779        int size = pkg.activities.size();
14780        if (size == 0) {
14781            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14782                    "No activity, so no need to verify any IntentFilter!");
14783            return;
14784        }
14785
14786        final boolean hasDomainURLs = hasDomainURLs(pkg);
14787        if (!hasDomainURLs) {
14788            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14789                    "No domain URLs, so no need to verify any IntentFilter!");
14790            return;
14791        }
14792
14793        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14794                + " if any IntentFilter from the " + size
14795                + " Activities needs verification ...");
14796
14797        int count = 0;
14798        final String packageName = pkg.packageName;
14799
14800        synchronized (mPackages) {
14801            // If this is a new install and we see that we've already run verification for this
14802            // package, we have nothing to do: it means the state was restored from backup.
14803            if (!replacing) {
14804                IntentFilterVerificationInfo ivi =
14805                        mSettings.getIntentFilterVerificationLPr(packageName);
14806                if (ivi != null) {
14807                    if (DEBUG_DOMAIN_VERIFICATION) {
14808                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14809                                + ivi.getStatusString());
14810                    }
14811                    return;
14812                }
14813            }
14814
14815            // If any filters need to be verified, then all need to be.
14816            boolean needToVerify = false;
14817            for (PackageParser.Activity a : pkg.activities) {
14818                for (ActivityIntentInfo filter : a.intents) {
14819                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14820                        if (DEBUG_DOMAIN_VERIFICATION) {
14821                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14822                        }
14823                        needToVerify = true;
14824                        break;
14825                    }
14826                }
14827            }
14828
14829            if (needToVerify) {
14830                final int verificationId = mIntentFilterVerificationToken++;
14831                for (PackageParser.Activity a : pkg.activities) {
14832                    for (ActivityIntentInfo filter : a.intents) {
14833                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14834                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14835                                    "Verification needed for IntentFilter:" + filter.toString());
14836                            mIntentFilterVerifier.addOneIntentFilterVerification(
14837                                    verifierUid, userId, verificationId, filter, packageName);
14838                            count++;
14839                        }
14840                    }
14841                }
14842            }
14843        }
14844
14845        if (count > 0) {
14846            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14847                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14848                    +  " for userId:" + userId);
14849            mIntentFilterVerifier.startVerifications(userId);
14850        } else {
14851            if (DEBUG_DOMAIN_VERIFICATION) {
14852                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14853            }
14854        }
14855    }
14856
14857    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14858        final ComponentName cn  = filter.activity.getComponentName();
14859        final String packageName = cn.getPackageName();
14860
14861        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14862                packageName);
14863        if (ivi == null) {
14864            return true;
14865        }
14866        int status = ivi.getStatus();
14867        switch (status) {
14868            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14869            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14870                return true;
14871
14872            default:
14873                // Nothing to do
14874                return false;
14875        }
14876    }
14877
14878    private static boolean isMultiArch(ApplicationInfo info) {
14879        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14880    }
14881
14882    private static boolean isExternal(PackageParser.Package pkg) {
14883        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14884    }
14885
14886    private static boolean isExternal(PackageSetting ps) {
14887        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14888    }
14889
14890    private static boolean isEphemeral(PackageParser.Package pkg) {
14891        return pkg.applicationInfo.isEphemeralApp();
14892    }
14893
14894    private static boolean isEphemeral(PackageSetting ps) {
14895        return ps.pkg != null && isEphemeral(ps.pkg);
14896    }
14897
14898    private static boolean isSystemApp(PackageParser.Package pkg) {
14899        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14900    }
14901
14902    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14903        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14904    }
14905
14906    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14907        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14908    }
14909
14910    private static boolean isSystemApp(PackageSetting ps) {
14911        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14912    }
14913
14914    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14915        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14916    }
14917
14918    private int packageFlagsToInstallFlags(PackageSetting ps) {
14919        int installFlags = 0;
14920        if (isEphemeral(ps)) {
14921            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14922        }
14923        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14924            // This existing package was an external ASEC install when we have
14925            // the external flag without a UUID
14926            installFlags |= PackageManager.INSTALL_EXTERNAL;
14927        }
14928        if (ps.isForwardLocked()) {
14929            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14930        }
14931        return installFlags;
14932    }
14933
14934    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14935        if (isExternal(pkg)) {
14936            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14937                return StorageManager.UUID_PRIMARY_PHYSICAL;
14938            } else {
14939                return pkg.volumeUuid;
14940            }
14941        } else {
14942            return StorageManager.UUID_PRIVATE_INTERNAL;
14943        }
14944    }
14945
14946    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14947        if (isExternal(pkg)) {
14948            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14949                return mSettings.getExternalVersion();
14950            } else {
14951                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14952            }
14953        } else {
14954            return mSettings.getInternalVersion();
14955        }
14956    }
14957
14958    private void deleteTempPackageFiles() {
14959        final FilenameFilter filter = new FilenameFilter() {
14960            public boolean accept(File dir, String name) {
14961                return name.startsWith("vmdl") && name.endsWith(".tmp");
14962            }
14963        };
14964        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14965            file.delete();
14966        }
14967    }
14968
14969    @Override
14970    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14971            int flags) {
14972        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14973                flags);
14974    }
14975
14976    @Override
14977    public void deletePackage(final String packageName,
14978            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
14979        mContext.enforceCallingOrSelfPermission(
14980                android.Manifest.permission.DELETE_PACKAGES, null);
14981        Preconditions.checkNotNull(packageName);
14982        Preconditions.checkNotNull(observer);
14983        final int uid = Binder.getCallingUid();
14984        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
14985        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14986        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14987            mContext.enforceCallingOrSelfPermission(
14988                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14989                    "deletePackage for user " + userId);
14990        }
14991
14992        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14993            try {
14994                observer.onPackageDeleted(packageName,
14995                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14996            } catch (RemoteException re) {
14997            }
14998            return;
14999        }
15000
15001        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15002            try {
15003                observer.onPackageDeleted(packageName,
15004                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15005            } catch (RemoteException re) {
15006            }
15007            return;
15008        }
15009
15010        if (DEBUG_REMOVE) {
15011            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15012                    + " deleteAllUsers: " + deleteAllUsers );
15013        }
15014        // Queue up an async operation since the package deletion may take a little while.
15015        mHandler.post(new Runnable() {
15016            public void run() {
15017                mHandler.removeCallbacks(this);
15018                int returnCode;
15019                if (!deleteAllUsers) {
15020                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15021                } else {
15022                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15023                    // If nobody is blocking uninstall, proceed with delete for all users
15024                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15025                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15026                    } else {
15027                        // Otherwise uninstall individually for users with blockUninstalls=false
15028                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15029                        for (int userId : users) {
15030                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15031                                returnCode = deletePackageX(packageName, userId, userFlags);
15032                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15033                                    Slog.w(TAG, "Package delete failed for user " + userId
15034                                            + ", returnCode " + returnCode);
15035                                }
15036                            }
15037                        }
15038                        // The app has only been marked uninstalled for certain users.
15039                        // We still need to report that delete was blocked
15040                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15041                    }
15042                }
15043                try {
15044                    observer.onPackageDeleted(packageName, returnCode, null);
15045                } catch (RemoteException e) {
15046                    Log.i(TAG, "Observer no longer exists.");
15047                } //end catch
15048            } //end run
15049        });
15050    }
15051
15052    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15053        int[] result = EMPTY_INT_ARRAY;
15054        for (int userId : userIds) {
15055            if (getBlockUninstallForUser(packageName, userId)) {
15056                result = ArrayUtils.appendInt(result, userId);
15057            }
15058        }
15059        return result;
15060    }
15061
15062    @Override
15063    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15064        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15065    }
15066
15067    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15068        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15069                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15070        try {
15071            if (dpm != null) {
15072                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15073                        /* callingUserOnly =*/ false);
15074                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15075                        : deviceOwnerComponentName.getPackageName();
15076                // Does the package contains the device owner?
15077                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15078                // this check is probably not needed, since DO should be registered as a device
15079                // admin on some user too. (Original bug for this: b/17657954)
15080                if (packageName.equals(deviceOwnerPackageName)) {
15081                    return true;
15082                }
15083                // Does it contain a device admin for any user?
15084                int[] users;
15085                if (userId == UserHandle.USER_ALL) {
15086                    users = sUserManager.getUserIds();
15087                } else {
15088                    users = new int[]{userId};
15089                }
15090                for (int i = 0; i < users.length; ++i) {
15091                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15092                        return true;
15093                    }
15094                }
15095            }
15096        } catch (RemoteException e) {
15097        }
15098        return false;
15099    }
15100
15101    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15102        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15103    }
15104
15105    /**
15106     *  This method is an internal method that could be get invoked either
15107     *  to delete an installed package or to clean up a failed installation.
15108     *  After deleting an installed package, a broadcast is sent to notify any
15109     *  listeners that the package has been removed. For cleaning up a failed
15110     *  installation, the broadcast is not necessary since the package's
15111     *  installation wouldn't have sent the initial broadcast either
15112     *  The key steps in deleting a package are
15113     *  deleting the package information in internal structures like mPackages,
15114     *  deleting the packages base directories through installd
15115     *  updating mSettings to reflect current status
15116     *  persisting settings for later use
15117     *  sending a broadcast if necessary
15118     */
15119    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15120        final PackageRemovedInfo info = new PackageRemovedInfo();
15121        final boolean res;
15122
15123        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15124                ? UserHandle.ALL : new UserHandle(userId);
15125
15126        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15127            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15128            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15129        }
15130
15131        PackageSetting uninstalledPs = null;
15132
15133        // for the uninstall-updates case and restricted profiles, remember the per-
15134        // user handle installed state
15135        int[] allUsers;
15136        synchronized (mPackages) {
15137            uninstalledPs = mSettings.mPackages.get(packageName);
15138            if (uninstalledPs == null) {
15139                Slog.w(TAG, "Not removing non-existent package " + packageName);
15140                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15141            }
15142            allUsers = sUserManager.getUserIds();
15143            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15144        }
15145
15146        synchronized (mInstallLock) {
15147            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15148            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15149                    "deletePackageX")) {
15150                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15151                        deleteFlags | REMOVE_CHATTY, info, true, null);
15152            }
15153            synchronized (mPackages) {
15154                if (res) {
15155                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15156                }
15157            }
15158        }
15159
15160        if (res) {
15161            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15162            info.sendPackageRemovedBroadcasts(killApp);
15163            info.sendSystemPackageUpdatedBroadcasts();
15164            info.sendSystemPackageAppearedBroadcasts();
15165        }
15166        // Force a gc here.
15167        Runtime.getRuntime().gc();
15168        // Delete the resources here after sending the broadcast to let
15169        // other processes clean up before deleting resources.
15170        if (info.args != null) {
15171            synchronized (mInstallLock) {
15172                info.args.doPostDeleteLI(true);
15173            }
15174        }
15175
15176        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15177    }
15178
15179    class PackageRemovedInfo {
15180        String removedPackage;
15181        int uid = -1;
15182        int removedAppId = -1;
15183        int[] origUsers;
15184        int[] removedUsers = null;
15185        boolean isRemovedPackageSystemUpdate = false;
15186        boolean isUpdate;
15187        boolean dataRemoved;
15188        boolean removedForAllUsers;
15189        // Clean up resources deleted packages.
15190        InstallArgs args = null;
15191        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15192        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15193
15194        void sendPackageRemovedBroadcasts(boolean killApp) {
15195            sendPackageRemovedBroadcastInternal(killApp);
15196            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15197            for (int i = 0; i < childCount; i++) {
15198                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15199                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15200            }
15201        }
15202
15203        void sendSystemPackageUpdatedBroadcasts() {
15204            if (isRemovedPackageSystemUpdate) {
15205                sendSystemPackageUpdatedBroadcastsInternal();
15206                final int childCount = (removedChildPackages != null)
15207                        ? removedChildPackages.size() : 0;
15208                for (int i = 0; i < childCount; i++) {
15209                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15210                    if (childInfo.isRemovedPackageSystemUpdate) {
15211                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15212                    }
15213                }
15214            }
15215        }
15216
15217        void sendSystemPackageAppearedBroadcasts() {
15218            final int packageCount = (appearedChildPackages != null)
15219                    ? appearedChildPackages.size() : 0;
15220            for (int i = 0; i < packageCount; i++) {
15221                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15222                for (int userId : installedInfo.newUsers) {
15223                    sendPackageAddedForUser(installedInfo.name, true,
15224                            UserHandle.getAppId(installedInfo.uid), userId);
15225                }
15226            }
15227        }
15228
15229        private void sendSystemPackageUpdatedBroadcastsInternal() {
15230            Bundle extras = new Bundle(2);
15231            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15232            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15233            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15234                    extras, 0, null, null, null);
15235            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15236                    extras, 0, null, null, null);
15237            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15238                    null, 0, removedPackage, null, null);
15239        }
15240
15241        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15242            Bundle extras = new Bundle(2);
15243            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15244            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15245            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15246            if (isUpdate || isRemovedPackageSystemUpdate) {
15247                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15248            }
15249            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15250            if (removedPackage != null) {
15251                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15252                        extras, 0, null, null, removedUsers);
15253                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15254                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15255                            removedPackage, extras, 0, null, null, removedUsers);
15256                }
15257            }
15258            if (removedAppId >= 0) {
15259                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15260                        removedUsers);
15261            }
15262        }
15263    }
15264
15265    /*
15266     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15267     * flag is not set, the data directory is removed as well.
15268     * make sure this flag is set for partially installed apps. If not its meaningless to
15269     * delete a partially installed application.
15270     */
15271    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15272            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15273        String packageName = ps.name;
15274        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15275        // Retrieve object to delete permissions for shared user later on
15276        final PackageParser.Package deletedPkg;
15277        final PackageSetting deletedPs;
15278        // reader
15279        synchronized (mPackages) {
15280            deletedPkg = mPackages.get(packageName);
15281            deletedPs = mSettings.mPackages.get(packageName);
15282            if (outInfo != null) {
15283                outInfo.removedPackage = packageName;
15284                outInfo.removedUsers = deletedPs != null
15285                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15286                        : null;
15287            }
15288        }
15289
15290        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15291
15292        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15293            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15294                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15295            destroyAppProfilesLIF(deletedPkg);
15296            if (outInfo != null) {
15297                outInfo.dataRemoved = true;
15298            }
15299            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15300        }
15301
15302        // writer
15303        synchronized (mPackages) {
15304            if (deletedPs != null) {
15305                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15306                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15307                    clearDefaultBrowserIfNeeded(packageName);
15308                    if (outInfo != null) {
15309                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15310                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15311                    }
15312                    updatePermissionsLPw(deletedPs.name, null, 0);
15313                    if (deletedPs.sharedUser != null) {
15314                        // Remove permissions associated with package. Since runtime
15315                        // permissions are per user we have to kill the removed package
15316                        // or packages running under the shared user of the removed
15317                        // package if revoking the permissions requested only by the removed
15318                        // package is successful and this causes a change in gids.
15319                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15320                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15321                                    userId);
15322                            if (userIdToKill == UserHandle.USER_ALL
15323                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15324                                // If gids changed for this user, kill all affected packages.
15325                                mHandler.post(new Runnable() {
15326                                    @Override
15327                                    public void run() {
15328                                        // This has to happen with no lock held.
15329                                        killApplication(deletedPs.name, deletedPs.appId,
15330                                                KILL_APP_REASON_GIDS_CHANGED);
15331                                    }
15332                                });
15333                                break;
15334                            }
15335                        }
15336                    }
15337                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15338                }
15339                // make sure to preserve per-user disabled state if this removal was just
15340                // a downgrade of a system app to the factory package
15341                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15342                    if (DEBUG_REMOVE) {
15343                        Slog.d(TAG, "Propagating install state across downgrade");
15344                    }
15345                    for (int userId : allUserHandles) {
15346                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15347                        if (DEBUG_REMOVE) {
15348                            Slog.d(TAG, "    user " + userId + " => " + installed);
15349                        }
15350                        ps.setInstalled(installed, userId);
15351                    }
15352                }
15353            }
15354            // can downgrade to reader
15355            if (writeSettings) {
15356                // Save settings now
15357                mSettings.writeLPr();
15358            }
15359        }
15360        if (outInfo != null) {
15361            // A user ID was deleted here. Go through all users and remove it
15362            // from KeyStore.
15363            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15364        }
15365    }
15366
15367    static boolean locationIsPrivileged(File path) {
15368        try {
15369            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15370                    .getCanonicalPath();
15371            return path.getCanonicalPath().startsWith(privilegedAppDir);
15372        } catch (IOException e) {
15373            Slog.e(TAG, "Unable to access code path " + path);
15374        }
15375        return false;
15376    }
15377
15378    /*
15379     * Tries to delete system package.
15380     */
15381    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15382            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15383            boolean writeSettings) {
15384        if (deletedPs.parentPackageName != null) {
15385            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15386            return false;
15387        }
15388
15389        final boolean applyUserRestrictions
15390                = (allUserHandles != null) && (outInfo.origUsers != null);
15391        final PackageSetting disabledPs;
15392        // Confirm if the system package has been updated
15393        // An updated system app can be deleted. This will also have to restore
15394        // the system pkg from system partition
15395        // reader
15396        synchronized (mPackages) {
15397            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15398        }
15399
15400        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15401                + " disabledPs=" + disabledPs);
15402
15403        if (disabledPs == null) {
15404            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15405            return false;
15406        } else if (DEBUG_REMOVE) {
15407            Slog.d(TAG, "Deleting system pkg from data partition");
15408        }
15409
15410        if (DEBUG_REMOVE) {
15411            if (applyUserRestrictions) {
15412                Slog.d(TAG, "Remembering install states:");
15413                for (int userId : allUserHandles) {
15414                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15415                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15416                }
15417            }
15418        }
15419
15420        // Delete the updated package
15421        outInfo.isRemovedPackageSystemUpdate = true;
15422        if (outInfo.removedChildPackages != null) {
15423            final int childCount = (deletedPs.childPackageNames != null)
15424                    ? deletedPs.childPackageNames.size() : 0;
15425            for (int i = 0; i < childCount; i++) {
15426                String childPackageName = deletedPs.childPackageNames.get(i);
15427                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15428                        .contains(childPackageName)) {
15429                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15430                            childPackageName);
15431                    if (childInfo != null) {
15432                        childInfo.isRemovedPackageSystemUpdate = true;
15433                    }
15434                }
15435            }
15436        }
15437
15438        if (disabledPs.versionCode < deletedPs.versionCode) {
15439            // Delete data for downgrades
15440            flags &= ~PackageManager.DELETE_KEEP_DATA;
15441        } else {
15442            // Preserve data by setting flag
15443            flags |= PackageManager.DELETE_KEEP_DATA;
15444        }
15445
15446        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15447                outInfo, writeSettings, disabledPs.pkg);
15448        if (!ret) {
15449            return false;
15450        }
15451
15452        // writer
15453        synchronized (mPackages) {
15454            // Reinstate the old system package
15455            enableSystemPackageLPw(disabledPs.pkg);
15456            // Remove any native libraries from the upgraded package.
15457            removeNativeBinariesLI(deletedPs);
15458        }
15459
15460        // Install the system package
15461        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15462        int parseFlags = mDefParseFlags
15463                | PackageParser.PARSE_MUST_BE_APK
15464                | PackageParser.PARSE_IS_SYSTEM
15465                | PackageParser.PARSE_IS_SYSTEM_DIR;
15466        if (locationIsPrivileged(disabledPs.codePath)) {
15467            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15468        }
15469
15470        final PackageParser.Package newPkg;
15471        try {
15472            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15473        } catch (PackageManagerException e) {
15474            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15475                    + e.getMessage());
15476            return false;
15477        }
15478
15479        prepareAppDataAfterInstallLIF(newPkg);
15480
15481        // writer
15482        synchronized (mPackages) {
15483            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15484
15485            // Propagate the permissions state as we do not want to drop on the floor
15486            // runtime permissions. The update permissions method below will take
15487            // care of removing obsolete permissions and grant install permissions.
15488            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15489            updatePermissionsLPw(newPkg.packageName, newPkg,
15490                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15491
15492            if (applyUserRestrictions) {
15493                if (DEBUG_REMOVE) {
15494                    Slog.d(TAG, "Propagating install state across reinstall");
15495                }
15496                for (int userId : allUserHandles) {
15497                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15498                    if (DEBUG_REMOVE) {
15499                        Slog.d(TAG, "    user " + userId + " => " + installed);
15500                    }
15501                    ps.setInstalled(installed, userId);
15502
15503                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15504                }
15505                // Regardless of writeSettings we need to ensure that this restriction
15506                // state propagation is persisted
15507                mSettings.writeAllUsersPackageRestrictionsLPr();
15508            }
15509            // can downgrade to reader here
15510            if (writeSettings) {
15511                mSettings.writeLPr();
15512            }
15513        }
15514        return true;
15515    }
15516
15517    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15518            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15519            PackageRemovedInfo outInfo, boolean writeSettings,
15520            PackageParser.Package replacingPackage) {
15521        synchronized (mPackages) {
15522            if (outInfo != null) {
15523                outInfo.uid = ps.appId;
15524            }
15525
15526            if (outInfo != null && outInfo.removedChildPackages != null) {
15527                final int childCount = (ps.childPackageNames != null)
15528                        ? ps.childPackageNames.size() : 0;
15529                for (int i = 0; i < childCount; i++) {
15530                    String childPackageName = ps.childPackageNames.get(i);
15531                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15532                    if (childPs == null) {
15533                        return false;
15534                    }
15535                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15536                            childPackageName);
15537                    if (childInfo != null) {
15538                        childInfo.uid = childPs.appId;
15539                    }
15540                }
15541            }
15542        }
15543
15544        // Delete package data from internal structures and also remove data if flag is set
15545        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15546
15547        // Delete the child packages data
15548        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15549        for (int i = 0; i < childCount; i++) {
15550            PackageSetting childPs;
15551            synchronized (mPackages) {
15552                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15553            }
15554            if (childPs != null) {
15555                PackageRemovedInfo childOutInfo = (outInfo != null
15556                        && outInfo.removedChildPackages != null)
15557                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15558                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15559                        && (replacingPackage != null
15560                        && !replacingPackage.hasChildPackage(childPs.name))
15561                        ? flags & ~DELETE_KEEP_DATA : flags;
15562                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15563                        deleteFlags, writeSettings);
15564            }
15565        }
15566
15567        // Delete application code and resources only for parent packages
15568        if (ps.parentPackageName == null) {
15569            if (deleteCodeAndResources && (outInfo != null)) {
15570                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15571                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15572                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15573            }
15574        }
15575
15576        return true;
15577    }
15578
15579    @Override
15580    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15581            int userId) {
15582        mContext.enforceCallingOrSelfPermission(
15583                android.Manifest.permission.DELETE_PACKAGES, null);
15584        synchronized (mPackages) {
15585            PackageSetting ps = mSettings.mPackages.get(packageName);
15586            if (ps == null) {
15587                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15588                return false;
15589            }
15590            if (!ps.getInstalled(userId)) {
15591                // Can't block uninstall for an app that is not installed or enabled.
15592                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15593                return false;
15594            }
15595            ps.setBlockUninstall(blockUninstall, userId);
15596            mSettings.writePackageRestrictionsLPr(userId);
15597        }
15598        return true;
15599    }
15600
15601    @Override
15602    public boolean getBlockUninstallForUser(String packageName, int userId) {
15603        synchronized (mPackages) {
15604            PackageSetting ps = mSettings.mPackages.get(packageName);
15605            if (ps == null) {
15606                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15607                return false;
15608            }
15609            return ps.getBlockUninstall(userId);
15610        }
15611    }
15612
15613    @Override
15614    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15615        int callingUid = Binder.getCallingUid();
15616        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15617            throw new SecurityException(
15618                    "setRequiredForSystemUser can only be run by the system or root");
15619        }
15620        synchronized (mPackages) {
15621            PackageSetting ps = mSettings.mPackages.get(packageName);
15622            if (ps == null) {
15623                Log.w(TAG, "Package doesn't exist: " + packageName);
15624                return false;
15625            }
15626            if (systemUserApp) {
15627                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15628            } else {
15629                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15630            }
15631            mSettings.writeLPr();
15632        }
15633        return true;
15634    }
15635
15636    /*
15637     * This method handles package deletion in general
15638     */
15639    private boolean deletePackageLIF(String packageName, UserHandle user,
15640            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15641            PackageRemovedInfo outInfo, boolean writeSettings,
15642            PackageParser.Package replacingPackage) {
15643        if (packageName == null) {
15644            Slog.w(TAG, "Attempt to delete null packageName.");
15645            return false;
15646        }
15647
15648        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15649
15650        PackageSetting ps;
15651
15652        synchronized (mPackages) {
15653            ps = mSettings.mPackages.get(packageName);
15654            if (ps == null) {
15655                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15656                return false;
15657            }
15658
15659            if (ps.parentPackageName != null && (!isSystemApp(ps)
15660                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15661                if (DEBUG_REMOVE) {
15662                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15663                            + ((user == null) ? UserHandle.USER_ALL : user));
15664                }
15665                final int removedUserId = (user != null) ? user.getIdentifier()
15666                        : UserHandle.USER_ALL;
15667                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15668                    return false;
15669                }
15670                markPackageUninstalledForUserLPw(ps, user);
15671                scheduleWritePackageRestrictionsLocked(user);
15672                return true;
15673            }
15674        }
15675
15676        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15677                && user.getIdentifier() != UserHandle.USER_ALL)) {
15678            // The caller is asking that the package only be deleted for a single
15679            // user.  To do this, we just mark its uninstalled state and delete
15680            // its data. If this is a system app, we only allow this to happen if
15681            // they have set the special DELETE_SYSTEM_APP which requests different
15682            // semantics than normal for uninstalling system apps.
15683            markPackageUninstalledForUserLPw(ps, user);
15684
15685            if (!isSystemApp(ps)) {
15686                // Do not uninstall the APK if an app should be cached
15687                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15688                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15689                    // Other user still have this package installed, so all
15690                    // we need to do is clear this user's data and save that
15691                    // it is uninstalled.
15692                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15693                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15694                        return false;
15695                    }
15696                    scheduleWritePackageRestrictionsLocked(user);
15697                    return true;
15698                } else {
15699                    // We need to set it back to 'installed' so the uninstall
15700                    // broadcasts will be sent correctly.
15701                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15702                    ps.setInstalled(true, user.getIdentifier());
15703                }
15704            } else {
15705                // This is a system app, so we assume that the
15706                // other users still have this package installed, so all
15707                // we need to do is clear this user's data and save that
15708                // it is uninstalled.
15709                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15710                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15711                    return false;
15712                }
15713                scheduleWritePackageRestrictionsLocked(user);
15714                return true;
15715            }
15716        }
15717
15718        // If we are deleting a composite package for all users, keep track
15719        // of result for each child.
15720        if (ps.childPackageNames != null && outInfo != null) {
15721            synchronized (mPackages) {
15722                final int childCount = ps.childPackageNames.size();
15723                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15724                for (int i = 0; i < childCount; i++) {
15725                    String childPackageName = ps.childPackageNames.get(i);
15726                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15727                    childInfo.removedPackage = childPackageName;
15728                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15729                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15730                    if (childPs != null) {
15731                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15732                    }
15733                }
15734            }
15735        }
15736
15737        boolean ret = false;
15738        if (isSystemApp(ps)) {
15739            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15740            // When an updated system application is deleted we delete the existing resources
15741            // as well and fall back to existing code in system partition
15742            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15743        } else {
15744            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15745            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15746                    outInfo, writeSettings, replacingPackage);
15747        }
15748
15749        // Take a note whether we deleted the package for all users
15750        if (outInfo != null) {
15751            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15752            if (outInfo.removedChildPackages != null) {
15753                synchronized (mPackages) {
15754                    final int childCount = outInfo.removedChildPackages.size();
15755                    for (int i = 0; i < childCount; i++) {
15756                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15757                        if (childInfo != null) {
15758                            childInfo.removedForAllUsers = mPackages.get(
15759                                    childInfo.removedPackage) == null;
15760                        }
15761                    }
15762                }
15763            }
15764            // If we uninstalled an update to a system app there may be some
15765            // child packages that appeared as they are declared in the system
15766            // app but were not declared in the update.
15767            if (isSystemApp(ps)) {
15768                synchronized (mPackages) {
15769                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15770                    final int childCount = (updatedPs.childPackageNames != null)
15771                            ? updatedPs.childPackageNames.size() : 0;
15772                    for (int i = 0; i < childCount; i++) {
15773                        String childPackageName = updatedPs.childPackageNames.get(i);
15774                        if (outInfo.removedChildPackages == null
15775                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15776                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15777                            if (childPs == null) {
15778                                continue;
15779                            }
15780                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15781                            installRes.name = childPackageName;
15782                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15783                            installRes.pkg = mPackages.get(childPackageName);
15784                            installRes.uid = childPs.pkg.applicationInfo.uid;
15785                            if (outInfo.appearedChildPackages == null) {
15786                                outInfo.appearedChildPackages = new ArrayMap<>();
15787                            }
15788                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15789                        }
15790                    }
15791                }
15792            }
15793        }
15794
15795        return ret;
15796    }
15797
15798    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15799        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15800                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15801        for (int nextUserId : userIds) {
15802            if (DEBUG_REMOVE) {
15803                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15804            }
15805            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15806                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15807                    false /*hidden*/, false /*suspended*/, null, null, null,
15808                    false /*blockUninstall*/,
15809                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15810        }
15811    }
15812
15813    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15814            PackageRemovedInfo outInfo) {
15815        final PackageParser.Package pkg;
15816        synchronized (mPackages) {
15817            pkg = mPackages.get(ps.name);
15818        }
15819
15820        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15821                : new int[] {userId};
15822        for (int nextUserId : userIds) {
15823            if (DEBUG_REMOVE) {
15824                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15825                        + nextUserId);
15826            }
15827
15828            destroyAppDataLIF(pkg, userId,
15829                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15830            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15831            schedulePackageCleaning(ps.name, nextUserId, false);
15832            synchronized (mPackages) {
15833                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15834                    scheduleWritePackageRestrictionsLocked(nextUserId);
15835                }
15836                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15837            }
15838        }
15839
15840        if (outInfo != null) {
15841            outInfo.removedPackage = ps.name;
15842            outInfo.removedAppId = ps.appId;
15843            outInfo.removedUsers = userIds;
15844        }
15845
15846        return true;
15847    }
15848
15849    private final class ClearStorageConnection implements ServiceConnection {
15850        IMediaContainerService mContainerService;
15851
15852        @Override
15853        public void onServiceConnected(ComponentName name, IBinder service) {
15854            synchronized (this) {
15855                mContainerService = IMediaContainerService.Stub.asInterface(service);
15856                notifyAll();
15857            }
15858        }
15859
15860        @Override
15861        public void onServiceDisconnected(ComponentName name) {
15862        }
15863    }
15864
15865    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15866        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15867
15868        final boolean mounted;
15869        if (Environment.isExternalStorageEmulated()) {
15870            mounted = true;
15871        } else {
15872            final String status = Environment.getExternalStorageState();
15873
15874            mounted = status.equals(Environment.MEDIA_MOUNTED)
15875                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15876        }
15877
15878        if (!mounted) {
15879            return;
15880        }
15881
15882        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15883        int[] users;
15884        if (userId == UserHandle.USER_ALL) {
15885            users = sUserManager.getUserIds();
15886        } else {
15887            users = new int[] { userId };
15888        }
15889        final ClearStorageConnection conn = new ClearStorageConnection();
15890        if (mContext.bindServiceAsUser(
15891                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15892            try {
15893                for (int curUser : users) {
15894                    long timeout = SystemClock.uptimeMillis() + 5000;
15895                    synchronized (conn) {
15896                        long now = SystemClock.uptimeMillis();
15897                        while (conn.mContainerService == null && now < timeout) {
15898                            try {
15899                                conn.wait(timeout - now);
15900                            } catch (InterruptedException e) {
15901                            }
15902                        }
15903                    }
15904                    if (conn.mContainerService == null) {
15905                        return;
15906                    }
15907
15908                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15909                    clearDirectory(conn.mContainerService,
15910                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15911                    if (allData) {
15912                        clearDirectory(conn.mContainerService,
15913                                userEnv.buildExternalStorageAppDataDirs(packageName));
15914                        clearDirectory(conn.mContainerService,
15915                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15916                    }
15917                }
15918            } finally {
15919                mContext.unbindService(conn);
15920            }
15921        }
15922    }
15923
15924    @Override
15925    public void clearApplicationProfileData(String packageName) {
15926        enforceSystemOrRoot("Only the system can clear all profile data");
15927
15928        final PackageParser.Package pkg;
15929        synchronized (mPackages) {
15930            pkg = mPackages.get(packageName);
15931        }
15932
15933        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
15934            synchronized (mInstallLock) {
15935                clearAppProfilesLIF(pkg);
15936            }
15937        }
15938    }
15939
15940    @Override
15941    public void clearApplicationUserData(final String packageName,
15942            final IPackageDataObserver observer, final int userId) {
15943        mContext.enforceCallingOrSelfPermission(
15944                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15945
15946        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15947                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15948
15949        final DevicePolicyManagerInternal dpmi = LocalServices
15950                .getService(DevicePolicyManagerInternal.class);
15951        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15952            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15953        }
15954        // Queue up an async operation since the package deletion may take a little while.
15955        mHandler.post(new Runnable() {
15956            public void run() {
15957                mHandler.removeCallbacks(this);
15958                final boolean succeeded;
15959                try (PackageFreezer freezer = freezePackage(packageName,
15960                        "clearApplicationUserData")) {
15961                    synchronized (mInstallLock) {
15962                        succeeded = clearApplicationUserDataLIF(packageName, userId);
15963                    }
15964                    clearExternalStorageDataSync(packageName, userId, true);
15965                }
15966                if (succeeded) {
15967                    // invoke DeviceStorageMonitor's update method to clear any notifications
15968                    DeviceStorageMonitorInternal dsm = LocalServices
15969                            .getService(DeviceStorageMonitorInternal.class);
15970                    if (dsm != null) {
15971                        dsm.checkMemory();
15972                    }
15973                }
15974                if(observer != null) {
15975                    try {
15976                        observer.onRemoveCompleted(packageName, succeeded);
15977                    } catch (RemoteException e) {
15978                        Log.i(TAG, "Observer no longer exists.");
15979                    }
15980                } //end if observer
15981            } //end run
15982        });
15983    }
15984
15985    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
15986        if (packageName == null) {
15987            Slog.w(TAG, "Attempt to delete null packageName.");
15988            return false;
15989        }
15990
15991        // Try finding details about the requested package
15992        PackageParser.Package pkg;
15993        synchronized (mPackages) {
15994            pkg = mPackages.get(packageName);
15995            if (pkg == null) {
15996                final PackageSetting ps = mSettings.mPackages.get(packageName);
15997                if (ps != null) {
15998                    pkg = ps.pkg;
15999                }
16000            }
16001
16002            if (pkg == null) {
16003                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16004                return false;
16005            }
16006
16007            PackageSetting ps = (PackageSetting) pkg.mExtras;
16008            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16009        }
16010
16011        clearAppDataLIF(pkg, userId,
16012                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16013
16014        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16015        removeKeystoreDataIfNeeded(userId, appId);
16016
16017        final UserManager um = mContext.getSystemService(UserManager.class);
16018        final int flags;
16019        if (um.isUserUnlockingOrUnlocked(userId)) {
16020            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16021        } else if (um.isUserRunning(userId)) {
16022            flags = StorageManager.FLAG_STORAGE_DE;
16023        } else {
16024            flags = 0;
16025        }
16026        prepareAppDataContentsLIF(pkg, userId, flags);
16027
16028        return true;
16029    }
16030
16031    /**
16032     * Reverts user permission state changes (permissions and flags) in
16033     * all packages for a given user.
16034     *
16035     * @param userId The device user for which to do a reset.
16036     */
16037    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16038        final int packageCount = mPackages.size();
16039        for (int i = 0; i < packageCount; i++) {
16040            PackageParser.Package pkg = mPackages.valueAt(i);
16041            PackageSetting ps = (PackageSetting) pkg.mExtras;
16042            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16043        }
16044    }
16045
16046    /**
16047     * Reverts user permission state changes (permissions and flags).
16048     *
16049     * @param ps The package for which to reset.
16050     * @param userId The device user for which to do a reset.
16051     */
16052    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16053            final PackageSetting ps, final int userId) {
16054        if (ps.pkg == null) {
16055            return;
16056        }
16057
16058        // These are flags that can change base on user actions.
16059        final int userSettableMask = FLAG_PERMISSION_USER_SET
16060                | FLAG_PERMISSION_USER_FIXED
16061                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16062                | FLAG_PERMISSION_REVIEW_REQUIRED;
16063
16064        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16065                | FLAG_PERMISSION_POLICY_FIXED;
16066
16067        boolean writeInstallPermissions = false;
16068        boolean writeRuntimePermissions = false;
16069
16070        final int permissionCount = ps.pkg.requestedPermissions.size();
16071        for (int i = 0; i < permissionCount; i++) {
16072            String permission = ps.pkg.requestedPermissions.get(i);
16073
16074            BasePermission bp = mSettings.mPermissions.get(permission);
16075            if (bp == null) {
16076                continue;
16077            }
16078
16079            // If shared user we just reset the state to which only this app contributed.
16080            if (ps.sharedUser != null) {
16081                boolean used = false;
16082                final int packageCount = ps.sharedUser.packages.size();
16083                for (int j = 0; j < packageCount; j++) {
16084                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16085                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16086                            && pkg.pkg.requestedPermissions.contains(permission)) {
16087                        used = true;
16088                        break;
16089                    }
16090                }
16091                if (used) {
16092                    continue;
16093                }
16094            }
16095
16096            PermissionsState permissionsState = ps.getPermissionsState();
16097
16098            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16099
16100            // Always clear the user settable flags.
16101            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16102                    bp.name) != null;
16103            // If permission review is enabled and this is a legacy app, mark the
16104            // permission as requiring a review as this is the initial state.
16105            int flags = 0;
16106            if (Build.PERMISSIONS_REVIEW_REQUIRED
16107                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16108                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16109            }
16110            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16111                if (hasInstallState) {
16112                    writeInstallPermissions = true;
16113                } else {
16114                    writeRuntimePermissions = true;
16115                }
16116            }
16117
16118            // Below is only runtime permission handling.
16119            if (!bp.isRuntime()) {
16120                continue;
16121            }
16122
16123            // Never clobber system or policy.
16124            if ((oldFlags & policyOrSystemFlags) != 0) {
16125                continue;
16126            }
16127
16128            // If this permission was granted by default, make sure it is.
16129            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16130                if (permissionsState.grantRuntimePermission(bp, userId)
16131                        != PERMISSION_OPERATION_FAILURE) {
16132                    writeRuntimePermissions = true;
16133                }
16134            // If permission review is enabled the permissions for a legacy apps
16135            // are represented as constantly granted runtime ones, so don't revoke.
16136            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16137                // Otherwise, reset the permission.
16138                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16139                switch (revokeResult) {
16140                    case PERMISSION_OPERATION_SUCCESS:
16141                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16142                        writeRuntimePermissions = true;
16143                        final int appId = ps.appId;
16144                        mHandler.post(new Runnable() {
16145                            @Override
16146                            public void run() {
16147                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16148                            }
16149                        });
16150                    } break;
16151                }
16152            }
16153        }
16154
16155        // Synchronously write as we are taking permissions away.
16156        if (writeRuntimePermissions) {
16157            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16158        }
16159
16160        // Synchronously write as we are taking permissions away.
16161        if (writeInstallPermissions) {
16162            mSettings.writeLPr();
16163        }
16164    }
16165
16166    /**
16167     * Remove entries from the keystore daemon. Will only remove it if the
16168     * {@code appId} is valid.
16169     */
16170    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16171        if (appId < 0) {
16172            return;
16173        }
16174
16175        final KeyStore keyStore = KeyStore.getInstance();
16176        if (keyStore != null) {
16177            if (userId == UserHandle.USER_ALL) {
16178                for (final int individual : sUserManager.getUserIds()) {
16179                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16180                }
16181            } else {
16182                keyStore.clearUid(UserHandle.getUid(userId, appId));
16183            }
16184        } else {
16185            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16186        }
16187    }
16188
16189    @Override
16190    public void deleteApplicationCacheFiles(final String packageName,
16191            final IPackageDataObserver observer) {
16192        final int userId = UserHandle.getCallingUserId();
16193        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16194    }
16195
16196    @Override
16197    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16198            final IPackageDataObserver observer) {
16199        mContext.enforceCallingOrSelfPermission(
16200                android.Manifest.permission.DELETE_CACHE_FILES, null);
16201        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16202                /* requireFullPermission= */ true, /* checkShell= */ false,
16203                "delete application cache files");
16204
16205        final PackageParser.Package pkg;
16206        synchronized (mPackages) {
16207            pkg = mPackages.get(packageName);
16208        }
16209
16210        // Queue up an async operation since the package deletion may take a little while.
16211        mHandler.post(new Runnable() {
16212            public void run() {
16213                synchronized (mInstallLock) {
16214                    final int flags = StorageManager.FLAG_STORAGE_DE
16215                            | StorageManager.FLAG_STORAGE_CE;
16216                    // We're only clearing cache files, so we don't care if the
16217                    // app is unfrozen and still able to run
16218                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16219                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16220                }
16221                clearExternalStorageDataSync(packageName, userId, false);
16222                if (observer != null) {
16223                    try {
16224                        observer.onRemoveCompleted(packageName, true);
16225                    } catch (RemoteException e) {
16226                        Log.i(TAG, "Observer no longer exists.");
16227                    }
16228                }
16229            }
16230        });
16231    }
16232
16233    @Override
16234    public void getPackageSizeInfo(final String packageName, int userHandle,
16235            final IPackageStatsObserver observer) {
16236        mContext.enforceCallingOrSelfPermission(
16237                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16238        if (packageName == null) {
16239            throw new IllegalArgumentException("Attempt to get size of null packageName");
16240        }
16241
16242        PackageStats stats = new PackageStats(packageName, userHandle);
16243
16244        /*
16245         * Queue up an async operation since the package measurement may take a
16246         * little while.
16247         */
16248        Message msg = mHandler.obtainMessage(INIT_COPY);
16249        msg.obj = new MeasureParams(stats, observer);
16250        mHandler.sendMessage(msg);
16251    }
16252
16253    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16254        final PackageSetting ps;
16255        synchronized (mPackages) {
16256            ps = mSettings.mPackages.get(packageName);
16257            if (ps == null) {
16258                Slog.w(TAG, "Failed to find settings for " + packageName);
16259                return false;
16260            }
16261        }
16262        try {
16263            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16264                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16265                    ps.getCeDataInode(userId), ps.codePathString, stats);
16266        } catch (InstallerException e) {
16267            Slog.w(TAG, String.valueOf(e));
16268            return false;
16269        }
16270
16271        // For now, ignore code size of packages on system partition
16272        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16273            stats.codeSize = 0;
16274        }
16275
16276        return true;
16277    }
16278
16279    private int getUidTargetSdkVersionLockedLPr(int uid) {
16280        Object obj = mSettings.getUserIdLPr(uid);
16281        if (obj instanceof SharedUserSetting) {
16282            final SharedUserSetting sus = (SharedUserSetting) obj;
16283            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16284            final Iterator<PackageSetting> it = sus.packages.iterator();
16285            while (it.hasNext()) {
16286                final PackageSetting ps = it.next();
16287                if (ps.pkg != null) {
16288                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16289                    if (v < vers) vers = v;
16290                }
16291            }
16292            return vers;
16293        } else if (obj instanceof PackageSetting) {
16294            final PackageSetting ps = (PackageSetting) obj;
16295            if (ps.pkg != null) {
16296                return ps.pkg.applicationInfo.targetSdkVersion;
16297            }
16298        }
16299        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16300    }
16301
16302    @Override
16303    public void addPreferredActivity(IntentFilter filter, int match,
16304            ComponentName[] set, ComponentName activity, int userId) {
16305        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16306                "Adding preferred");
16307    }
16308
16309    private void addPreferredActivityInternal(IntentFilter filter, int match,
16310            ComponentName[] set, ComponentName activity, boolean always, int userId,
16311            String opname) {
16312        // writer
16313        int callingUid = Binder.getCallingUid();
16314        enforceCrossUserPermission(callingUid, userId,
16315                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16316        if (filter.countActions() == 0) {
16317            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16318            return;
16319        }
16320        synchronized (mPackages) {
16321            if (mContext.checkCallingOrSelfPermission(
16322                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16323                    != PackageManager.PERMISSION_GRANTED) {
16324                if (getUidTargetSdkVersionLockedLPr(callingUid)
16325                        < Build.VERSION_CODES.FROYO) {
16326                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16327                            + callingUid);
16328                    return;
16329                }
16330                mContext.enforceCallingOrSelfPermission(
16331                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16332            }
16333
16334            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16335            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16336                    + userId + ":");
16337            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16338            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16339            scheduleWritePackageRestrictionsLocked(userId);
16340        }
16341    }
16342
16343    @Override
16344    public void replacePreferredActivity(IntentFilter filter, int match,
16345            ComponentName[] set, ComponentName activity, int userId) {
16346        if (filter.countActions() != 1) {
16347            throw new IllegalArgumentException(
16348                    "replacePreferredActivity expects filter to have only 1 action.");
16349        }
16350        if (filter.countDataAuthorities() != 0
16351                || filter.countDataPaths() != 0
16352                || filter.countDataSchemes() > 1
16353                || filter.countDataTypes() != 0) {
16354            throw new IllegalArgumentException(
16355                    "replacePreferredActivity expects filter to have no data authorities, " +
16356                    "paths, or types; and at most one scheme.");
16357        }
16358
16359        final int callingUid = Binder.getCallingUid();
16360        enforceCrossUserPermission(callingUid, userId,
16361                true /* requireFullPermission */, false /* checkShell */,
16362                "replace preferred activity");
16363        synchronized (mPackages) {
16364            if (mContext.checkCallingOrSelfPermission(
16365                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16366                    != PackageManager.PERMISSION_GRANTED) {
16367                if (getUidTargetSdkVersionLockedLPr(callingUid)
16368                        < Build.VERSION_CODES.FROYO) {
16369                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16370                            + Binder.getCallingUid());
16371                    return;
16372                }
16373                mContext.enforceCallingOrSelfPermission(
16374                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16375            }
16376
16377            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16378            if (pir != null) {
16379                // Get all of the existing entries that exactly match this filter.
16380                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16381                if (existing != null && existing.size() == 1) {
16382                    PreferredActivity cur = existing.get(0);
16383                    if (DEBUG_PREFERRED) {
16384                        Slog.i(TAG, "Checking replace of preferred:");
16385                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16386                        if (!cur.mPref.mAlways) {
16387                            Slog.i(TAG, "  -- CUR; not mAlways!");
16388                        } else {
16389                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16390                            Slog.i(TAG, "  -- CUR: mSet="
16391                                    + Arrays.toString(cur.mPref.mSetComponents));
16392                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16393                            Slog.i(TAG, "  -- NEW: mMatch="
16394                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16395                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16396                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16397                        }
16398                    }
16399                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16400                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16401                            && cur.mPref.sameSet(set)) {
16402                        // Setting the preferred activity to what it happens to be already
16403                        if (DEBUG_PREFERRED) {
16404                            Slog.i(TAG, "Replacing with same preferred activity "
16405                                    + cur.mPref.mShortComponent + " for user "
16406                                    + userId + ":");
16407                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16408                        }
16409                        return;
16410                    }
16411                }
16412
16413                if (existing != null) {
16414                    if (DEBUG_PREFERRED) {
16415                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16416                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16417                    }
16418                    for (int i = 0; i < existing.size(); i++) {
16419                        PreferredActivity pa = existing.get(i);
16420                        if (DEBUG_PREFERRED) {
16421                            Slog.i(TAG, "Removing existing preferred activity "
16422                                    + pa.mPref.mComponent + ":");
16423                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16424                        }
16425                        pir.removeFilter(pa);
16426                    }
16427                }
16428            }
16429            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16430                    "Replacing preferred");
16431        }
16432    }
16433
16434    @Override
16435    public void clearPackagePreferredActivities(String packageName) {
16436        final int uid = Binder.getCallingUid();
16437        // writer
16438        synchronized (mPackages) {
16439            PackageParser.Package pkg = mPackages.get(packageName);
16440            if (pkg == null || pkg.applicationInfo.uid != uid) {
16441                if (mContext.checkCallingOrSelfPermission(
16442                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16443                        != PackageManager.PERMISSION_GRANTED) {
16444                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16445                            < Build.VERSION_CODES.FROYO) {
16446                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16447                                + Binder.getCallingUid());
16448                        return;
16449                    }
16450                    mContext.enforceCallingOrSelfPermission(
16451                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16452                }
16453            }
16454
16455            int user = UserHandle.getCallingUserId();
16456            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16457                scheduleWritePackageRestrictionsLocked(user);
16458            }
16459        }
16460    }
16461
16462    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16463    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16464        ArrayList<PreferredActivity> removed = null;
16465        boolean changed = false;
16466        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16467            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16468            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16469            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16470                continue;
16471            }
16472            Iterator<PreferredActivity> it = pir.filterIterator();
16473            while (it.hasNext()) {
16474                PreferredActivity pa = it.next();
16475                // Mark entry for removal only if it matches the package name
16476                // and the entry is of type "always".
16477                if (packageName == null ||
16478                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16479                                && pa.mPref.mAlways)) {
16480                    if (removed == null) {
16481                        removed = new ArrayList<PreferredActivity>();
16482                    }
16483                    removed.add(pa);
16484                }
16485            }
16486            if (removed != null) {
16487                for (int j=0; j<removed.size(); j++) {
16488                    PreferredActivity pa = removed.get(j);
16489                    pir.removeFilter(pa);
16490                }
16491                changed = true;
16492            }
16493        }
16494        return changed;
16495    }
16496
16497    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16498    private void clearIntentFilterVerificationsLPw(int userId) {
16499        final int packageCount = mPackages.size();
16500        for (int i = 0; i < packageCount; i++) {
16501            PackageParser.Package pkg = mPackages.valueAt(i);
16502            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16503        }
16504    }
16505
16506    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16507    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16508        if (userId == UserHandle.USER_ALL) {
16509            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16510                    sUserManager.getUserIds())) {
16511                for (int oneUserId : sUserManager.getUserIds()) {
16512                    scheduleWritePackageRestrictionsLocked(oneUserId);
16513                }
16514            }
16515        } else {
16516            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16517                scheduleWritePackageRestrictionsLocked(userId);
16518            }
16519        }
16520    }
16521
16522    void clearDefaultBrowserIfNeeded(String packageName) {
16523        for (int oneUserId : sUserManager.getUserIds()) {
16524            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16525            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16526            if (packageName.equals(defaultBrowserPackageName)) {
16527                setDefaultBrowserPackageName(null, oneUserId);
16528            }
16529        }
16530    }
16531
16532    @Override
16533    public void resetApplicationPreferences(int userId) {
16534        mContext.enforceCallingOrSelfPermission(
16535                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16536        // writer
16537        synchronized (mPackages) {
16538            final long identity = Binder.clearCallingIdentity();
16539            try {
16540                clearPackagePreferredActivitiesLPw(null, userId);
16541                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16542                // TODO: We have to reset the default SMS and Phone. This requires
16543                // significant refactoring to keep all default apps in the package
16544                // manager (cleaner but more work) or have the services provide
16545                // callbacks to the package manager to request a default app reset.
16546                applyFactoryDefaultBrowserLPw(userId);
16547                clearIntentFilterVerificationsLPw(userId);
16548                primeDomainVerificationsLPw(userId);
16549                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16550                scheduleWritePackageRestrictionsLocked(userId);
16551            } finally {
16552                Binder.restoreCallingIdentity(identity);
16553            }
16554        }
16555    }
16556
16557    @Override
16558    public int getPreferredActivities(List<IntentFilter> outFilters,
16559            List<ComponentName> outActivities, String packageName) {
16560
16561        int num = 0;
16562        final int userId = UserHandle.getCallingUserId();
16563        // reader
16564        synchronized (mPackages) {
16565            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16566            if (pir != null) {
16567                final Iterator<PreferredActivity> it = pir.filterIterator();
16568                while (it.hasNext()) {
16569                    final PreferredActivity pa = it.next();
16570                    if (packageName == null
16571                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16572                                    && pa.mPref.mAlways)) {
16573                        if (outFilters != null) {
16574                            outFilters.add(new IntentFilter(pa));
16575                        }
16576                        if (outActivities != null) {
16577                            outActivities.add(pa.mPref.mComponent);
16578                        }
16579                    }
16580                }
16581            }
16582        }
16583
16584        return num;
16585    }
16586
16587    @Override
16588    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16589            int userId) {
16590        int callingUid = Binder.getCallingUid();
16591        if (callingUid != Process.SYSTEM_UID) {
16592            throw new SecurityException(
16593                    "addPersistentPreferredActivity can only be run by the system");
16594        }
16595        if (filter.countActions() == 0) {
16596            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16597            return;
16598        }
16599        synchronized (mPackages) {
16600            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16601                    ":");
16602            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16603            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16604                    new PersistentPreferredActivity(filter, activity));
16605            scheduleWritePackageRestrictionsLocked(userId);
16606        }
16607    }
16608
16609    @Override
16610    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16611        int callingUid = Binder.getCallingUid();
16612        if (callingUid != Process.SYSTEM_UID) {
16613            throw new SecurityException(
16614                    "clearPackagePersistentPreferredActivities can only be run by the system");
16615        }
16616        ArrayList<PersistentPreferredActivity> removed = null;
16617        boolean changed = false;
16618        synchronized (mPackages) {
16619            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16620                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16621                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16622                        .valueAt(i);
16623                if (userId != thisUserId) {
16624                    continue;
16625                }
16626                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16627                while (it.hasNext()) {
16628                    PersistentPreferredActivity ppa = it.next();
16629                    // Mark entry for removal only if it matches the package name.
16630                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16631                        if (removed == null) {
16632                            removed = new ArrayList<PersistentPreferredActivity>();
16633                        }
16634                        removed.add(ppa);
16635                    }
16636                }
16637                if (removed != null) {
16638                    for (int j=0; j<removed.size(); j++) {
16639                        PersistentPreferredActivity ppa = removed.get(j);
16640                        ppir.removeFilter(ppa);
16641                    }
16642                    changed = true;
16643                }
16644            }
16645
16646            if (changed) {
16647                scheduleWritePackageRestrictionsLocked(userId);
16648            }
16649        }
16650    }
16651
16652    /**
16653     * Common machinery for picking apart a restored XML blob and passing
16654     * it to a caller-supplied functor to be applied to the running system.
16655     */
16656    private void restoreFromXml(XmlPullParser parser, int userId,
16657            String expectedStartTag, BlobXmlRestorer functor)
16658            throws IOException, XmlPullParserException {
16659        int type;
16660        while ((type = parser.next()) != XmlPullParser.START_TAG
16661                && type != XmlPullParser.END_DOCUMENT) {
16662        }
16663        if (type != XmlPullParser.START_TAG) {
16664            // oops didn't find a start tag?!
16665            if (DEBUG_BACKUP) {
16666                Slog.e(TAG, "Didn't find start tag during restore");
16667            }
16668            return;
16669        }
16670Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16671        // this is supposed to be TAG_PREFERRED_BACKUP
16672        if (!expectedStartTag.equals(parser.getName())) {
16673            if (DEBUG_BACKUP) {
16674                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16675            }
16676            return;
16677        }
16678
16679        // skip interfering stuff, then we're aligned with the backing implementation
16680        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16681Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16682        functor.apply(parser, userId);
16683    }
16684
16685    private interface BlobXmlRestorer {
16686        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16687    }
16688
16689    /**
16690     * Non-Binder method, support for the backup/restore mechanism: write the
16691     * full set of preferred activities in its canonical XML format.  Returns the
16692     * XML output as a byte array, or null if there is none.
16693     */
16694    @Override
16695    public byte[] getPreferredActivityBackup(int userId) {
16696        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16697            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16698        }
16699
16700        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16701        try {
16702            final XmlSerializer serializer = new FastXmlSerializer();
16703            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16704            serializer.startDocument(null, true);
16705            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16706
16707            synchronized (mPackages) {
16708                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16709            }
16710
16711            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16712            serializer.endDocument();
16713            serializer.flush();
16714        } catch (Exception e) {
16715            if (DEBUG_BACKUP) {
16716                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16717            }
16718            return null;
16719        }
16720
16721        return dataStream.toByteArray();
16722    }
16723
16724    @Override
16725    public void restorePreferredActivities(byte[] backup, int userId) {
16726        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16727            throw new SecurityException("Only the system may call restorePreferredActivities()");
16728        }
16729
16730        try {
16731            final XmlPullParser parser = Xml.newPullParser();
16732            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16733            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16734                    new BlobXmlRestorer() {
16735                        @Override
16736                        public void apply(XmlPullParser parser, int userId)
16737                                throws XmlPullParserException, IOException {
16738                            synchronized (mPackages) {
16739                                mSettings.readPreferredActivitiesLPw(parser, userId);
16740                            }
16741                        }
16742                    } );
16743        } catch (Exception e) {
16744            if (DEBUG_BACKUP) {
16745                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16746            }
16747        }
16748    }
16749
16750    /**
16751     * Non-Binder method, support for the backup/restore mechanism: write the
16752     * default browser (etc) settings in its canonical XML format.  Returns the default
16753     * browser XML representation as a byte array, or null if there is none.
16754     */
16755    @Override
16756    public byte[] getDefaultAppsBackup(int userId) {
16757        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16758            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16759        }
16760
16761        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16762        try {
16763            final XmlSerializer serializer = new FastXmlSerializer();
16764            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16765            serializer.startDocument(null, true);
16766            serializer.startTag(null, TAG_DEFAULT_APPS);
16767
16768            synchronized (mPackages) {
16769                mSettings.writeDefaultAppsLPr(serializer, userId);
16770            }
16771
16772            serializer.endTag(null, TAG_DEFAULT_APPS);
16773            serializer.endDocument();
16774            serializer.flush();
16775        } catch (Exception e) {
16776            if (DEBUG_BACKUP) {
16777                Slog.e(TAG, "Unable to write default apps for backup", e);
16778            }
16779            return null;
16780        }
16781
16782        return dataStream.toByteArray();
16783    }
16784
16785    @Override
16786    public void restoreDefaultApps(byte[] backup, int userId) {
16787        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16788            throw new SecurityException("Only the system may call restoreDefaultApps()");
16789        }
16790
16791        try {
16792            final XmlPullParser parser = Xml.newPullParser();
16793            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16794            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16795                    new BlobXmlRestorer() {
16796                        @Override
16797                        public void apply(XmlPullParser parser, int userId)
16798                                throws XmlPullParserException, IOException {
16799                            synchronized (mPackages) {
16800                                mSettings.readDefaultAppsLPw(parser, userId);
16801                            }
16802                        }
16803                    } );
16804        } catch (Exception e) {
16805            if (DEBUG_BACKUP) {
16806                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16807            }
16808        }
16809    }
16810
16811    @Override
16812    public byte[] getIntentFilterVerificationBackup(int userId) {
16813        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16814            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16815        }
16816
16817        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16818        try {
16819            final XmlSerializer serializer = new FastXmlSerializer();
16820            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16821            serializer.startDocument(null, true);
16822            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16823
16824            synchronized (mPackages) {
16825                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16826            }
16827
16828            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16829            serializer.endDocument();
16830            serializer.flush();
16831        } catch (Exception e) {
16832            if (DEBUG_BACKUP) {
16833                Slog.e(TAG, "Unable to write default apps for backup", e);
16834            }
16835            return null;
16836        }
16837
16838        return dataStream.toByteArray();
16839    }
16840
16841    @Override
16842    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16843        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16844            throw new SecurityException("Only the system may call restorePreferredActivities()");
16845        }
16846
16847        try {
16848            final XmlPullParser parser = Xml.newPullParser();
16849            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16850            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16851                    new BlobXmlRestorer() {
16852                        @Override
16853                        public void apply(XmlPullParser parser, int userId)
16854                                throws XmlPullParserException, IOException {
16855                            synchronized (mPackages) {
16856                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16857                                mSettings.writeLPr();
16858                            }
16859                        }
16860                    } );
16861        } catch (Exception e) {
16862            if (DEBUG_BACKUP) {
16863                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16864            }
16865        }
16866    }
16867
16868    @Override
16869    public byte[] getPermissionGrantBackup(int userId) {
16870        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16871            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16872        }
16873
16874        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16875        try {
16876            final XmlSerializer serializer = new FastXmlSerializer();
16877            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16878            serializer.startDocument(null, true);
16879            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16880
16881            synchronized (mPackages) {
16882                serializeRuntimePermissionGrantsLPr(serializer, userId);
16883            }
16884
16885            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16886            serializer.endDocument();
16887            serializer.flush();
16888        } catch (Exception e) {
16889            if (DEBUG_BACKUP) {
16890                Slog.e(TAG, "Unable to write default apps for backup", e);
16891            }
16892            return null;
16893        }
16894
16895        return dataStream.toByteArray();
16896    }
16897
16898    @Override
16899    public void restorePermissionGrants(byte[] backup, int userId) {
16900        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16901            throw new SecurityException("Only the system may call restorePermissionGrants()");
16902        }
16903
16904        try {
16905            final XmlPullParser parser = Xml.newPullParser();
16906            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16907            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16908                    new BlobXmlRestorer() {
16909                        @Override
16910                        public void apply(XmlPullParser parser, int userId)
16911                                throws XmlPullParserException, IOException {
16912                            synchronized (mPackages) {
16913                                processRestoredPermissionGrantsLPr(parser, userId);
16914                            }
16915                        }
16916                    } );
16917        } catch (Exception e) {
16918            if (DEBUG_BACKUP) {
16919                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16920            }
16921        }
16922    }
16923
16924    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16925            throws IOException {
16926        serializer.startTag(null, TAG_ALL_GRANTS);
16927
16928        final int N = mSettings.mPackages.size();
16929        for (int i = 0; i < N; i++) {
16930            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16931            boolean pkgGrantsKnown = false;
16932
16933            PermissionsState packagePerms = ps.getPermissionsState();
16934
16935            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16936                final int grantFlags = state.getFlags();
16937                // only look at grants that are not system/policy fixed
16938                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16939                    final boolean isGranted = state.isGranted();
16940                    // And only back up the user-twiddled state bits
16941                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16942                        final String packageName = mSettings.mPackages.keyAt(i);
16943                        if (!pkgGrantsKnown) {
16944                            serializer.startTag(null, TAG_GRANT);
16945                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16946                            pkgGrantsKnown = true;
16947                        }
16948
16949                        final boolean userSet =
16950                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16951                        final boolean userFixed =
16952                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16953                        final boolean revoke =
16954                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16955
16956                        serializer.startTag(null, TAG_PERMISSION);
16957                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16958                        if (isGranted) {
16959                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16960                        }
16961                        if (userSet) {
16962                            serializer.attribute(null, ATTR_USER_SET, "true");
16963                        }
16964                        if (userFixed) {
16965                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16966                        }
16967                        if (revoke) {
16968                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16969                        }
16970                        serializer.endTag(null, TAG_PERMISSION);
16971                    }
16972                }
16973            }
16974
16975            if (pkgGrantsKnown) {
16976                serializer.endTag(null, TAG_GRANT);
16977            }
16978        }
16979
16980        serializer.endTag(null, TAG_ALL_GRANTS);
16981    }
16982
16983    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16984            throws XmlPullParserException, IOException {
16985        String pkgName = null;
16986        int outerDepth = parser.getDepth();
16987        int type;
16988        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16989                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16990            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16991                continue;
16992            }
16993
16994            final String tagName = parser.getName();
16995            if (tagName.equals(TAG_GRANT)) {
16996                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16997                if (DEBUG_BACKUP) {
16998                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16999                }
17000            } else if (tagName.equals(TAG_PERMISSION)) {
17001
17002                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17003                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17004
17005                int newFlagSet = 0;
17006                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17007                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17008                }
17009                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17010                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17011                }
17012                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17013                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17014                }
17015                if (DEBUG_BACKUP) {
17016                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17017                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17018                }
17019                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17020                if (ps != null) {
17021                    // Already installed so we apply the grant immediately
17022                    if (DEBUG_BACKUP) {
17023                        Slog.v(TAG, "        + already installed; applying");
17024                    }
17025                    PermissionsState perms = ps.getPermissionsState();
17026                    BasePermission bp = mSettings.mPermissions.get(permName);
17027                    if (bp != null) {
17028                        if (isGranted) {
17029                            perms.grantRuntimePermission(bp, userId);
17030                        }
17031                        if (newFlagSet != 0) {
17032                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17033                        }
17034                    }
17035                } else {
17036                    // Need to wait for post-restore install to apply the grant
17037                    if (DEBUG_BACKUP) {
17038                        Slog.v(TAG, "        - not yet installed; saving for later");
17039                    }
17040                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17041                            isGranted, newFlagSet, userId);
17042                }
17043            } else {
17044                PackageManagerService.reportSettingsProblem(Log.WARN,
17045                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17046                XmlUtils.skipCurrentTag(parser);
17047            }
17048        }
17049
17050        scheduleWriteSettingsLocked();
17051        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17052    }
17053
17054    @Override
17055    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17056            int sourceUserId, int targetUserId, int flags) {
17057        mContext.enforceCallingOrSelfPermission(
17058                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17059        int callingUid = Binder.getCallingUid();
17060        enforceOwnerRights(ownerPackage, callingUid);
17061        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17062        if (intentFilter.countActions() == 0) {
17063            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17064            return;
17065        }
17066        synchronized (mPackages) {
17067            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17068                    ownerPackage, targetUserId, flags);
17069            CrossProfileIntentResolver resolver =
17070                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17071            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17072            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17073            if (existing != null) {
17074                int size = existing.size();
17075                for (int i = 0; i < size; i++) {
17076                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17077                        return;
17078                    }
17079                }
17080            }
17081            resolver.addFilter(newFilter);
17082            scheduleWritePackageRestrictionsLocked(sourceUserId);
17083        }
17084    }
17085
17086    @Override
17087    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17088        mContext.enforceCallingOrSelfPermission(
17089                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17090        int callingUid = Binder.getCallingUid();
17091        enforceOwnerRights(ownerPackage, callingUid);
17092        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17093        synchronized (mPackages) {
17094            CrossProfileIntentResolver resolver =
17095                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17096            ArraySet<CrossProfileIntentFilter> set =
17097                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17098            for (CrossProfileIntentFilter filter : set) {
17099                if (filter.getOwnerPackage().equals(ownerPackage)) {
17100                    resolver.removeFilter(filter);
17101                }
17102            }
17103            scheduleWritePackageRestrictionsLocked(sourceUserId);
17104        }
17105    }
17106
17107    // Enforcing that callingUid is owning pkg on userId
17108    private void enforceOwnerRights(String pkg, int callingUid) {
17109        // The system owns everything.
17110        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17111            return;
17112        }
17113        int callingUserId = UserHandle.getUserId(callingUid);
17114        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17115        if (pi == null) {
17116            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17117                    + callingUserId);
17118        }
17119        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17120            throw new SecurityException("Calling uid " + callingUid
17121                    + " does not own package " + pkg);
17122        }
17123    }
17124
17125    @Override
17126    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17127        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17128    }
17129
17130    private Intent getHomeIntent() {
17131        Intent intent = new Intent(Intent.ACTION_MAIN);
17132        intent.addCategory(Intent.CATEGORY_HOME);
17133        return intent;
17134    }
17135
17136    private IntentFilter getHomeFilter() {
17137        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17138        filter.addCategory(Intent.CATEGORY_HOME);
17139        filter.addCategory(Intent.CATEGORY_DEFAULT);
17140        return filter;
17141    }
17142
17143    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17144            int userId) {
17145        Intent intent  = getHomeIntent();
17146        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17147                PackageManager.GET_META_DATA, userId);
17148        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17149                true, false, false, userId);
17150
17151        allHomeCandidates.clear();
17152        if (list != null) {
17153            for (ResolveInfo ri : list) {
17154                allHomeCandidates.add(ri);
17155            }
17156        }
17157        return (preferred == null || preferred.activityInfo == null)
17158                ? null
17159                : new ComponentName(preferred.activityInfo.packageName,
17160                        preferred.activityInfo.name);
17161    }
17162
17163    @Override
17164    public void setHomeActivity(ComponentName comp, int userId) {
17165        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17166        getHomeActivitiesAsUser(homeActivities, userId);
17167
17168        boolean found = false;
17169
17170        final int size = homeActivities.size();
17171        final ComponentName[] set = new ComponentName[size];
17172        for (int i = 0; i < size; i++) {
17173            final ResolveInfo candidate = homeActivities.get(i);
17174            final ActivityInfo info = candidate.activityInfo;
17175            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17176            set[i] = activityName;
17177            if (!found && activityName.equals(comp)) {
17178                found = true;
17179            }
17180        }
17181        if (!found) {
17182            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17183                    + userId);
17184        }
17185        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17186                set, comp, userId);
17187    }
17188
17189    private @Nullable String getSetupWizardPackageName() {
17190        final Intent intent = new Intent(Intent.ACTION_MAIN);
17191        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17192
17193        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17194                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17195                        | MATCH_DISABLED_COMPONENTS,
17196                UserHandle.myUserId());
17197        if (matches.size() == 1) {
17198            return matches.get(0).getComponentInfo().packageName;
17199        } else {
17200            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17201                    + ": matches=" + matches);
17202            return null;
17203        }
17204    }
17205
17206    @Override
17207    public void setApplicationEnabledSetting(String appPackageName,
17208            int newState, int flags, int userId, String callingPackage) {
17209        if (!sUserManager.exists(userId)) return;
17210        if (callingPackage == null) {
17211            callingPackage = Integer.toString(Binder.getCallingUid());
17212        }
17213        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17214    }
17215
17216    @Override
17217    public void setComponentEnabledSetting(ComponentName componentName,
17218            int newState, int flags, int userId) {
17219        if (!sUserManager.exists(userId)) return;
17220        setEnabledSetting(componentName.getPackageName(),
17221                componentName.getClassName(), newState, flags, userId, null);
17222    }
17223
17224    private void setEnabledSetting(final String packageName, String className, int newState,
17225            final int flags, int userId, String callingPackage) {
17226        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17227              || newState == COMPONENT_ENABLED_STATE_ENABLED
17228              || newState == COMPONENT_ENABLED_STATE_DISABLED
17229              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17230              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17231            throw new IllegalArgumentException("Invalid new component state: "
17232                    + newState);
17233        }
17234        PackageSetting pkgSetting;
17235        final int uid = Binder.getCallingUid();
17236        final int permission;
17237        if (uid == Process.SYSTEM_UID) {
17238            permission = PackageManager.PERMISSION_GRANTED;
17239        } else {
17240            permission = mContext.checkCallingOrSelfPermission(
17241                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17242        }
17243        enforceCrossUserPermission(uid, userId,
17244                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17245        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17246        boolean sendNow = false;
17247        boolean isApp = (className == null);
17248        String componentName = isApp ? packageName : className;
17249        int packageUid = -1;
17250        ArrayList<String> components;
17251
17252        // writer
17253        synchronized (mPackages) {
17254            pkgSetting = mSettings.mPackages.get(packageName);
17255            if (pkgSetting == null) {
17256                if (className == null) {
17257                    throw new IllegalArgumentException("Unknown package: " + packageName);
17258                }
17259                throw new IllegalArgumentException(
17260                        "Unknown component: " + packageName + "/" + className);
17261            }
17262            // Allow root and verify that userId is not being specified by a different user
17263            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17264                throw new SecurityException(
17265                        "Permission Denial: attempt to change component state from pid="
17266                        + Binder.getCallingPid()
17267                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17268            }
17269            if (className == null) {
17270                // We're dealing with an application/package level state change
17271                if (pkgSetting.getEnabled(userId) == newState) {
17272                    // Nothing to do
17273                    return;
17274                }
17275                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17276                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17277                    // Don't care about who enables an app.
17278                    callingPackage = null;
17279                }
17280                pkgSetting.setEnabled(newState, userId, callingPackage);
17281                // pkgSetting.pkg.mSetEnabled = newState;
17282            } else {
17283                // We're dealing with a component level state change
17284                // First, verify that this is a valid class name.
17285                PackageParser.Package pkg = pkgSetting.pkg;
17286                if (pkg == null || !pkg.hasComponentClassName(className)) {
17287                    if (pkg != null &&
17288                            pkg.applicationInfo.targetSdkVersion >=
17289                                    Build.VERSION_CODES.JELLY_BEAN) {
17290                        throw new IllegalArgumentException("Component class " + className
17291                                + " does not exist in " + packageName);
17292                    } else {
17293                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17294                                + className + " does not exist in " + packageName);
17295                    }
17296                }
17297                switch (newState) {
17298                case COMPONENT_ENABLED_STATE_ENABLED:
17299                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17300                        return;
17301                    }
17302                    break;
17303                case COMPONENT_ENABLED_STATE_DISABLED:
17304                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17305                        return;
17306                    }
17307                    break;
17308                case COMPONENT_ENABLED_STATE_DEFAULT:
17309                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17310                        return;
17311                    }
17312                    break;
17313                default:
17314                    Slog.e(TAG, "Invalid new component state: " + newState);
17315                    return;
17316                }
17317            }
17318            scheduleWritePackageRestrictionsLocked(userId);
17319            components = mPendingBroadcasts.get(userId, packageName);
17320            final boolean newPackage = components == null;
17321            if (newPackage) {
17322                components = new ArrayList<String>();
17323            }
17324            if (!components.contains(componentName)) {
17325                components.add(componentName);
17326            }
17327            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17328                sendNow = true;
17329                // Purge entry from pending broadcast list if another one exists already
17330                // since we are sending one right away.
17331                mPendingBroadcasts.remove(userId, packageName);
17332            } else {
17333                if (newPackage) {
17334                    mPendingBroadcasts.put(userId, packageName, components);
17335                }
17336                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17337                    // Schedule a message
17338                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17339                }
17340            }
17341        }
17342
17343        long callingId = Binder.clearCallingIdentity();
17344        try {
17345            if (sendNow) {
17346                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17347                sendPackageChangedBroadcast(packageName,
17348                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17349            }
17350        } finally {
17351            Binder.restoreCallingIdentity(callingId);
17352        }
17353    }
17354
17355    @Override
17356    public void flushPackageRestrictionsAsUser(int userId) {
17357        if (!sUserManager.exists(userId)) {
17358            return;
17359        }
17360        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17361                false /* checkShell */, "flushPackageRestrictions");
17362        synchronized (mPackages) {
17363            mSettings.writePackageRestrictionsLPr(userId);
17364            mDirtyUsers.remove(userId);
17365            if (mDirtyUsers.isEmpty()) {
17366                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17367            }
17368        }
17369    }
17370
17371    private void sendPackageChangedBroadcast(String packageName,
17372            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17373        if (DEBUG_INSTALL)
17374            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17375                    + componentNames);
17376        Bundle extras = new Bundle(4);
17377        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17378        String nameList[] = new String[componentNames.size()];
17379        componentNames.toArray(nameList);
17380        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17381        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17382        extras.putInt(Intent.EXTRA_UID, packageUid);
17383        // If this is not reporting a change of the overall package, then only send it
17384        // to registered receivers.  We don't want to launch a swath of apps for every
17385        // little component state change.
17386        final int flags = !componentNames.contains(packageName)
17387                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17388        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17389                new int[] {UserHandle.getUserId(packageUid)});
17390    }
17391
17392    @Override
17393    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17394        if (!sUserManager.exists(userId)) return;
17395        final int uid = Binder.getCallingUid();
17396        final int permission = mContext.checkCallingOrSelfPermission(
17397                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17398        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17399        enforceCrossUserPermission(uid, userId,
17400                true /* requireFullPermission */, true /* checkShell */, "stop package");
17401        // writer
17402        synchronized (mPackages) {
17403            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17404                    allowedByPermission, uid, userId)) {
17405                scheduleWritePackageRestrictionsLocked(userId);
17406            }
17407        }
17408    }
17409
17410    @Override
17411    public String getInstallerPackageName(String packageName) {
17412        // reader
17413        synchronized (mPackages) {
17414            return mSettings.getInstallerPackageNameLPr(packageName);
17415        }
17416    }
17417
17418    @Override
17419    public int getApplicationEnabledSetting(String packageName, int userId) {
17420        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17421        int uid = Binder.getCallingUid();
17422        enforceCrossUserPermission(uid, userId,
17423                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17424        // reader
17425        synchronized (mPackages) {
17426            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17427        }
17428    }
17429
17430    @Override
17431    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17432        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17433        int uid = Binder.getCallingUid();
17434        enforceCrossUserPermission(uid, userId,
17435                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17436        // reader
17437        synchronized (mPackages) {
17438            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17439        }
17440    }
17441
17442    @Override
17443    public void enterSafeMode() {
17444        enforceSystemOrRoot("Only the system can request entering safe mode");
17445
17446        if (!mSystemReady) {
17447            mSafeMode = true;
17448        }
17449    }
17450
17451    @Override
17452    public void systemReady() {
17453        mSystemReady = true;
17454
17455        // Read the compatibilty setting when the system is ready.
17456        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17457                mContext.getContentResolver(),
17458                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17459        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17460        if (DEBUG_SETTINGS) {
17461            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17462        }
17463
17464        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17465
17466        synchronized (mPackages) {
17467            // Verify that all of the preferred activity components actually
17468            // exist.  It is possible for applications to be updated and at
17469            // that point remove a previously declared activity component that
17470            // had been set as a preferred activity.  We try to clean this up
17471            // the next time we encounter that preferred activity, but it is
17472            // possible for the user flow to never be able to return to that
17473            // situation so here we do a sanity check to make sure we haven't
17474            // left any junk around.
17475            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17476            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17477                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17478                removed.clear();
17479                for (PreferredActivity pa : pir.filterSet()) {
17480                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17481                        removed.add(pa);
17482                    }
17483                }
17484                if (removed.size() > 0) {
17485                    for (int r=0; r<removed.size(); r++) {
17486                        PreferredActivity pa = removed.get(r);
17487                        Slog.w(TAG, "Removing dangling preferred activity: "
17488                                + pa.mPref.mComponent);
17489                        pir.removeFilter(pa);
17490                    }
17491                    mSettings.writePackageRestrictionsLPr(
17492                            mSettings.mPreferredActivities.keyAt(i));
17493                }
17494            }
17495
17496            for (int userId : UserManagerService.getInstance().getUserIds()) {
17497                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17498                    grantPermissionsUserIds = ArrayUtils.appendInt(
17499                            grantPermissionsUserIds, userId);
17500                }
17501            }
17502        }
17503        sUserManager.systemReady();
17504
17505        // If we upgraded grant all default permissions before kicking off.
17506        for (int userId : grantPermissionsUserIds) {
17507            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17508        }
17509
17510        // Kick off any messages waiting for system ready
17511        if (mPostSystemReadyMessages != null) {
17512            for (Message msg : mPostSystemReadyMessages) {
17513                msg.sendToTarget();
17514            }
17515            mPostSystemReadyMessages = null;
17516        }
17517
17518        // Watch for external volumes that come and go over time
17519        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17520        storage.registerListener(mStorageListener);
17521
17522        mInstallerService.systemReady();
17523        mPackageDexOptimizer.systemReady();
17524
17525        MountServiceInternal mountServiceInternal = LocalServices.getService(
17526                MountServiceInternal.class);
17527        mountServiceInternal.addExternalStoragePolicy(
17528                new MountServiceInternal.ExternalStorageMountPolicy() {
17529            @Override
17530            public int getMountMode(int uid, String packageName) {
17531                if (Process.isIsolated(uid)) {
17532                    return Zygote.MOUNT_EXTERNAL_NONE;
17533                }
17534                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17535                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17536                }
17537                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17538                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17539                }
17540                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17541                    return Zygote.MOUNT_EXTERNAL_READ;
17542                }
17543                return Zygote.MOUNT_EXTERNAL_WRITE;
17544            }
17545
17546            @Override
17547            public boolean hasExternalStorage(int uid, String packageName) {
17548                return true;
17549            }
17550        });
17551
17552        // Now that we're mostly running, clean up stale users and apps
17553        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17554        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17555    }
17556
17557    @Override
17558    public boolean isSafeMode() {
17559        return mSafeMode;
17560    }
17561
17562    @Override
17563    public boolean hasSystemUidErrors() {
17564        return mHasSystemUidErrors;
17565    }
17566
17567    static String arrayToString(int[] array) {
17568        StringBuffer buf = new StringBuffer(128);
17569        buf.append('[');
17570        if (array != null) {
17571            for (int i=0; i<array.length; i++) {
17572                if (i > 0) buf.append(", ");
17573                buf.append(array[i]);
17574            }
17575        }
17576        buf.append(']');
17577        return buf.toString();
17578    }
17579
17580    static class DumpState {
17581        public static final int DUMP_LIBS = 1 << 0;
17582        public static final int DUMP_FEATURES = 1 << 1;
17583        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17584        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17585        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17586        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17587        public static final int DUMP_PERMISSIONS = 1 << 6;
17588        public static final int DUMP_PACKAGES = 1 << 7;
17589        public static final int DUMP_SHARED_USERS = 1 << 8;
17590        public static final int DUMP_MESSAGES = 1 << 9;
17591        public static final int DUMP_PROVIDERS = 1 << 10;
17592        public static final int DUMP_VERIFIERS = 1 << 11;
17593        public static final int DUMP_PREFERRED = 1 << 12;
17594        public static final int DUMP_PREFERRED_XML = 1 << 13;
17595        public static final int DUMP_KEYSETS = 1 << 14;
17596        public static final int DUMP_VERSION = 1 << 15;
17597        public static final int DUMP_INSTALLS = 1 << 16;
17598        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17599        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17600        public static final int DUMP_FROZEN = 1 << 19;
17601
17602        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17603
17604        private int mTypes;
17605
17606        private int mOptions;
17607
17608        private boolean mTitlePrinted;
17609
17610        private SharedUserSetting mSharedUser;
17611
17612        public boolean isDumping(int type) {
17613            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17614                return true;
17615            }
17616
17617            return (mTypes & type) != 0;
17618        }
17619
17620        public void setDump(int type) {
17621            mTypes |= type;
17622        }
17623
17624        public boolean isOptionEnabled(int option) {
17625            return (mOptions & option) != 0;
17626        }
17627
17628        public void setOptionEnabled(int option) {
17629            mOptions |= option;
17630        }
17631
17632        public boolean onTitlePrinted() {
17633            final boolean printed = mTitlePrinted;
17634            mTitlePrinted = true;
17635            return printed;
17636        }
17637
17638        public boolean getTitlePrinted() {
17639            return mTitlePrinted;
17640        }
17641
17642        public void setTitlePrinted(boolean enabled) {
17643            mTitlePrinted = enabled;
17644        }
17645
17646        public SharedUserSetting getSharedUser() {
17647            return mSharedUser;
17648        }
17649
17650        public void setSharedUser(SharedUserSetting user) {
17651            mSharedUser = user;
17652        }
17653    }
17654
17655    @Override
17656    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17657            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17658        (new PackageManagerShellCommand(this)).exec(
17659                this, in, out, err, args, resultReceiver);
17660    }
17661
17662    @Override
17663    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17664        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17665                != PackageManager.PERMISSION_GRANTED) {
17666            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17667                    + Binder.getCallingPid()
17668                    + ", uid=" + Binder.getCallingUid()
17669                    + " without permission "
17670                    + android.Manifest.permission.DUMP);
17671            return;
17672        }
17673
17674        DumpState dumpState = new DumpState();
17675        boolean fullPreferred = false;
17676        boolean checkin = false;
17677
17678        String packageName = null;
17679        ArraySet<String> permissionNames = null;
17680
17681        int opti = 0;
17682        while (opti < args.length) {
17683            String opt = args[opti];
17684            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17685                break;
17686            }
17687            opti++;
17688
17689            if ("-a".equals(opt)) {
17690                // Right now we only know how to print all.
17691            } else if ("-h".equals(opt)) {
17692                pw.println("Package manager dump options:");
17693                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17694                pw.println("    --checkin: dump for a checkin");
17695                pw.println("    -f: print details of intent filters");
17696                pw.println("    -h: print this help");
17697                pw.println("  cmd may be one of:");
17698                pw.println("    l[ibraries]: list known shared libraries");
17699                pw.println("    f[eatures]: list device features");
17700                pw.println("    k[eysets]: print known keysets");
17701                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17702                pw.println("    perm[issions]: dump permissions");
17703                pw.println("    permission [name ...]: dump declaration and use of given permission");
17704                pw.println("    pref[erred]: print preferred package settings");
17705                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17706                pw.println("    prov[iders]: dump content providers");
17707                pw.println("    p[ackages]: dump installed packages");
17708                pw.println("    s[hared-users]: dump shared user IDs");
17709                pw.println("    m[essages]: print collected runtime messages");
17710                pw.println("    v[erifiers]: print package verifier info");
17711                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17712                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17713                pw.println("    version: print database version info");
17714                pw.println("    write: write current settings now");
17715                pw.println("    installs: details about install sessions");
17716                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17717                pw.println("    <package.name>: info about given package");
17718                return;
17719            } else if ("--checkin".equals(opt)) {
17720                checkin = true;
17721            } else if ("-f".equals(opt)) {
17722                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17723            } else {
17724                pw.println("Unknown argument: " + opt + "; use -h for help");
17725            }
17726        }
17727
17728        // Is the caller requesting to dump a particular piece of data?
17729        if (opti < args.length) {
17730            String cmd = args[opti];
17731            opti++;
17732            // Is this a package name?
17733            if ("android".equals(cmd) || cmd.contains(".")) {
17734                packageName = cmd;
17735                // When dumping a single package, we always dump all of its
17736                // filter information since the amount of data will be reasonable.
17737                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17738            } else if ("check-permission".equals(cmd)) {
17739                if (opti >= args.length) {
17740                    pw.println("Error: check-permission missing permission argument");
17741                    return;
17742                }
17743                String perm = args[opti];
17744                opti++;
17745                if (opti >= args.length) {
17746                    pw.println("Error: check-permission missing package argument");
17747                    return;
17748                }
17749                String pkg = args[opti];
17750                opti++;
17751                int user = UserHandle.getUserId(Binder.getCallingUid());
17752                if (opti < args.length) {
17753                    try {
17754                        user = Integer.parseInt(args[opti]);
17755                    } catch (NumberFormatException e) {
17756                        pw.println("Error: check-permission user argument is not a number: "
17757                                + args[opti]);
17758                        return;
17759                    }
17760                }
17761                pw.println(checkPermission(perm, pkg, user));
17762                return;
17763            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17764                dumpState.setDump(DumpState.DUMP_LIBS);
17765            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17766                dumpState.setDump(DumpState.DUMP_FEATURES);
17767            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17768                if (opti >= args.length) {
17769                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17770                            | DumpState.DUMP_SERVICE_RESOLVERS
17771                            | DumpState.DUMP_RECEIVER_RESOLVERS
17772                            | DumpState.DUMP_CONTENT_RESOLVERS);
17773                } else {
17774                    while (opti < args.length) {
17775                        String name = args[opti];
17776                        if ("a".equals(name) || "activity".equals(name)) {
17777                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17778                        } else if ("s".equals(name) || "service".equals(name)) {
17779                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17780                        } else if ("r".equals(name) || "receiver".equals(name)) {
17781                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17782                        } else if ("c".equals(name) || "content".equals(name)) {
17783                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17784                        } else {
17785                            pw.println("Error: unknown resolver table type: " + name);
17786                            return;
17787                        }
17788                        opti++;
17789                    }
17790                }
17791            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17792                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17793            } else if ("permission".equals(cmd)) {
17794                if (opti >= args.length) {
17795                    pw.println("Error: permission requires permission name");
17796                    return;
17797                }
17798                permissionNames = new ArraySet<>();
17799                while (opti < args.length) {
17800                    permissionNames.add(args[opti]);
17801                    opti++;
17802                }
17803                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17804                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17805            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17806                dumpState.setDump(DumpState.DUMP_PREFERRED);
17807            } else if ("preferred-xml".equals(cmd)) {
17808                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17809                if (opti < args.length && "--full".equals(args[opti])) {
17810                    fullPreferred = true;
17811                    opti++;
17812                }
17813            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17814                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17815            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17816                dumpState.setDump(DumpState.DUMP_PACKAGES);
17817            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17818                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17819            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17820                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17821            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17822                dumpState.setDump(DumpState.DUMP_MESSAGES);
17823            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17824                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17825            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17826                    || "intent-filter-verifiers".equals(cmd)) {
17827                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17828            } else if ("version".equals(cmd)) {
17829                dumpState.setDump(DumpState.DUMP_VERSION);
17830            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17831                dumpState.setDump(DumpState.DUMP_KEYSETS);
17832            } else if ("installs".equals(cmd)) {
17833                dumpState.setDump(DumpState.DUMP_INSTALLS);
17834            } else if ("frozen".equals(cmd)) {
17835                dumpState.setDump(DumpState.DUMP_FROZEN);
17836            } else if ("write".equals(cmd)) {
17837                synchronized (mPackages) {
17838                    mSettings.writeLPr();
17839                    pw.println("Settings written.");
17840                    return;
17841                }
17842            }
17843        }
17844
17845        if (checkin) {
17846            pw.println("vers,1");
17847        }
17848
17849        // reader
17850        synchronized (mPackages) {
17851            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17852                if (!checkin) {
17853                    if (dumpState.onTitlePrinted())
17854                        pw.println();
17855                    pw.println("Database versions:");
17856                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17857                }
17858            }
17859
17860            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17861                if (!checkin) {
17862                    if (dumpState.onTitlePrinted())
17863                        pw.println();
17864                    pw.println("Verifiers:");
17865                    pw.print("  Required: ");
17866                    pw.print(mRequiredVerifierPackage);
17867                    pw.print(" (uid=");
17868                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17869                            UserHandle.USER_SYSTEM));
17870                    pw.println(")");
17871                } else if (mRequiredVerifierPackage != null) {
17872                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17873                    pw.print(",");
17874                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17875                            UserHandle.USER_SYSTEM));
17876                }
17877            }
17878
17879            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17880                    packageName == null) {
17881                if (mIntentFilterVerifierComponent != null) {
17882                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17883                    if (!checkin) {
17884                        if (dumpState.onTitlePrinted())
17885                            pw.println();
17886                        pw.println("Intent Filter Verifier:");
17887                        pw.print("  Using: ");
17888                        pw.print(verifierPackageName);
17889                        pw.print(" (uid=");
17890                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17891                                UserHandle.USER_SYSTEM));
17892                        pw.println(")");
17893                    } else if (verifierPackageName != null) {
17894                        pw.print("ifv,"); pw.print(verifierPackageName);
17895                        pw.print(",");
17896                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17897                                UserHandle.USER_SYSTEM));
17898                    }
17899                } else {
17900                    pw.println();
17901                    pw.println("No Intent Filter Verifier available!");
17902                }
17903            }
17904
17905            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17906                boolean printedHeader = false;
17907                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17908                while (it.hasNext()) {
17909                    String name = it.next();
17910                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17911                    if (!checkin) {
17912                        if (!printedHeader) {
17913                            if (dumpState.onTitlePrinted())
17914                                pw.println();
17915                            pw.println("Libraries:");
17916                            printedHeader = true;
17917                        }
17918                        pw.print("  ");
17919                    } else {
17920                        pw.print("lib,");
17921                    }
17922                    pw.print(name);
17923                    if (!checkin) {
17924                        pw.print(" -> ");
17925                    }
17926                    if (ent.path != null) {
17927                        if (!checkin) {
17928                            pw.print("(jar) ");
17929                            pw.print(ent.path);
17930                        } else {
17931                            pw.print(",jar,");
17932                            pw.print(ent.path);
17933                        }
17934                    } else {
17935                        if (!checkin) {
17936                            pw.print("(apk) ");
17937                            pw.print(ent.apk);
17938                        } else {
17939                            pw.print(",apk,");
17940                            pw.print(ent.apk);
17941                        }
17942                    }
17943                    pw.println();
17944                }
17945            }
17946
17947            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17948                if (dumpState.onTitlePrinted())
17949                    pw.println();
17950                if (!checkin) {
17951                    pw.println("Features:");
17952                }
17953
17954                for (FeatureInfo feat : mAvailableFeatures.values()) {
17955                    if (checkin) {
17956                        pw.print("feat,");
17957                        pw.print(feat.name);
17958                        pw.print(",");
17959                        pw.println(feat.version);
17960                    } else {
17961                        pw.print("  ");
17962                        pw.print(feat.name);
17963                        if (feat.version > 0) {
17964                            pw.print(" version=");
17965                            pw.print(feat.version);
17966                        }
17967                        pw.println();
17968                    }
17969                }
17970            }
17971
17972            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17973                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17974                        : "Activity Resolver Table:", "  ", packageName,
17975                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17976                    dumpState.setTitlePrinted(true);
17977                }
17978            }
17979            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17980                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17981                        : "Receiver Resolver Table:", "  ", packageName,
17982                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17983                    dumpState.setTitlePrinted(true);
17984                }
17985            }
17986            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17987                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17988                        : "Service Resolver Table:", "  ", packageName,
17989                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17990                    dumpState.setTitlePrinted(true);
17991                }
17992            }
17993            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17994                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17995                        : "Provider Resolver Table:", "  ", packageName,
17996                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17997                    dumpState.setTitlePrinted(true);
17998                }
17999            }
18000
18001            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18002                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18003                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18004                    int user = mSettings.mPreferredActivities.keyAt(i);
18005                    if (pir.dump(pw,
18006                            dumpState.getTitlePrinted()
18007                                ? "\nPreferred Activities User " + user + ":"
18008                                : "Preferred Activities User " + user + ":", "  ",
18009                            packageName, true, false)) {
18010                        dumpState.setTitlePrinted(true);
18011                    }
18012                }
18013            }
18014
18015            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18016                pw.flush();
18017                FileOutputStream fout = new FileOutputStream(fd);
18018                BufferedOutputStream str = new BufferedOutputStream(fout);
18019                XmlSerializer serializer = new FastXmlSerializer();
18020                try {
18021                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18022                    serializer.startDocument(null, true);
18023                    serializer.setFeature(
18024                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18025                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18026                    serializer.endDocument();
18027                    serializer.flush();
18028                } catch (IllegalArgumentException e) {
18029                    pw.println("Failed writing: " + e);
18030                } catch (IllegalStateException e) {
18031                    pw.println("Failed writing: " + e);
18032                } catch (IOException e) {
18033                    pw.println("Failed writing: " + e);
18034                }
18035            }
18036
18037            if (!checkin
18038                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18039                    && packageName == null) {
18040                pw.println();
18041                int count = mSettings.mPackages.size();
18042                if (count == 0) {
18043                    pw.println("No applications!");
18044                    pw.println();
18045                } else {
18046                    final String prefix = "  ";
18047                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18048                    if (allPackageSettings.size() == 0) {
18049                        pw.println("No domain preferred apps!");
18050                        pw.println();
18051                    } else {
18052                        pw.println("App verification status:");
18053                        pw.println();
18054                        count = 0;
18055                        for (PackageSetting ps : allPackageSettings) {
18056                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18057                            if (ivi == null || ivi.getPackageName() == null) continue;
18058                            pw.println(prefix + "Package: " + ivi.getPackageName());
18059                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18060                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18061                            pw.println();
18062                            count++;
18063                        }
18064                        if (count == 0) {
18065                            pw.println(prefix + "No app verification established.");
18066                            pw.println();
18067                        }
18068                        for (int userId : sUserManager.getUserIds()) {
18069                            pw.println("App linkages for user " + userId + ":");
18070                            pw.println();
18071                            count = 0;
18072                            for (PackageSetting ps : allPackageSettings) {
18073                                final long status = ps.getDomainVerificationStatusForUser(userId);
18074                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18075                                    continue;
18076                                }
18077                                pw.println(prefix + "Package: " + ps.name);
18078                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18079                                String statusStr = IntentFilterVerificationInfo.
18080                                        getStatusStringFromValue(status);
18081                                pw.println(prefix + "Status:  " + statusStr);
18082                                pw.println();
18083                                count++;
18084                            }
18085                            if (count == 0) {
18086                                pw.println(prefix + "No configured app linkages.");
18087                                pw.println();
18088                            }
18089                        }
18090                    }
18091                }
18092            }
18093
18094            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18095                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18096                if (packageName == null && permissionNames == null) {
18097                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18098                        if (iperm == 0) {
18099                            if (dumpState.onTitlePrinted())
18100                                pw.println();
18101                            pw.println("AppOp Permissions:");
18102                        }
18103                        pw.print("  AppOp Permission ");
18104                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18105                        pw.println(":");
18106                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18107                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18108                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18109                        }
18110                    }
18111                }
18112            }
18113
18114            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18115                boolean printedSomething = false;
18116                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18117                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18118                        continue;
18119                    }
18120                    if (!printedSomething) {
18121                        if (dumpState.onTitlePrinted())
18122                            pw.println();
18123                        pw.println("Registered ContentProviders:");
18124                        printedSomething = true;
18125                    }
18126                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18127                    pw.print("    "); pw.println(p.toString());
18128                }
18129                printedSomething = false;
18130                for (Map.Entry<String, PackageParser.Provider> entry :
18131                        mProvidersByAuthority.entrySet()) {
18132                    PackageParser.Provider p = entry.getValue();
18133                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18134                        continue;
18135                    }
18136                    if (!printedSomething) {
18137                        if (dumpState.onTitlePrinted())
18138                            pw.println();
18139                        pw.println("ContentProvider Authorities:");
18140                        printedSomething = true;
18141                    }
18142                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18143                    pw.print("    "); pw.println(p.toString());
18144                    if (p.info != null && p.info.applicationInfo != null) {
18145                        final String appInfo = p.info.applicationInfo.toString();
18146                        pw.print("      applicationInfo="); pw.println(appInfo);
18147                    }
18148                }
18149            }
18150
18151            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18152                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18153            }
18154
18155            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18156                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18157            }
18158
18159            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18160                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18161            }
18162
18163            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18164                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18165            }
18166
18167            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18168                // XXX should handle packageName != null by dumping only install data that
18169                // the given package is involved with.
18170                if (dumpState.onTitlePrinted()) pw.println();
18171                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18172            }
18173
18174            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18175                // XXX should handle packageName != null by dumping only install data that
18176                // the given package is involved with.
18177                if (dumpState.onTitlePrinted()) pw.println();
18178
18179                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18180                ipw.println();
18181                ipw.println("Frozen packages:");
18182                ipw.increaseIndent();
18183                if (mFrozenPackages.size() == 0) {
18184                    ipw.println("(none)");
18185                } else {
18186                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18187                        ipw.println(mFrozenPackages.valueAt(i));
18188                    }
18189                }
18190                ipw.decreaseIndent();
18191            }
18192
18193            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18194                if (dumpState.onTitlePrinted()) pw.println();
18195                mSettings.dumpReadMessagesLPr(pw, dumpState);
18196
18197                pw.println();
18198                pw.println("Package warning messages:");
18199                BufferedReader in = null;
18200                String line = null;
18201                try {
18202                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18203                    while ((line = in.readLine()) != null) {
18204                        if (line.contains("ignored: updated version")) continue;
18205                        pw.println(line);
18206                    }
18207                } catch (IOException ignored) {
18208                } finally {
18209                    IoUtils.closeQuietly(in);
18210                }
18211            }
18212
18213            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18214                BufferedReader in = null;
18215                String line = null;
18216                try {
18217                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18218                    while ((line = in.readLine()) != null) {
18219                        if (line.contains("ignored: updated version")) continue;
18220                        pw.print("msg,");
18221                        pw.println(line);
18222                    }
18223                } catch (IOException ignored) {
18224                } finally {
18225                    IoUtils.closeQuietly(in);
18226                }
18227            }
18228        }
18229    }
18230
18231    private String dumpDomainString(String packageName) {
18232        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18233                .getList();
18234        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18235
18236        ArraySet<String> result = new ArraySet<>();
18237        if (iviList.size() > 0) {
18238            for (IntentFilterVerificationInfo ivi : iviList) {
18239                for (String host : ivi.getDomains()) {
18240                    result.add(host);
18241                }
18242            }
18243        }
18244        if (filters != null && filters.size() > 0) {
18245            for (IntentFilter filter : filters) {
18246                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18247                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18248                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18249                    result.addAll(filter.getHostsList());
18250                }
18251            }
18252        }
18253
18254        StringBuilder sb = new StringBuilder(result.size() * 16);
18255        for (String domain : result) {
18256            if (sb.length() > 0) sb.append(" ");
18257            sb.append(domain);
18258        }
18259        return sb.toString();
18260    }
18261
18262    // ------- apps on sdcard specific code -------
18263    static final boolean DEBUG_SD_INSTALL = false;
18264
18265    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18266
18267    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18268
18269    private boolean mMediaMounted = false;
18270
18271    static String getEncryptKey() {
18272        try {
18273            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18274                    SD_ENCRYPTION_KEYSTORE_NAME);
18275            if (sdEncKey == null) {
18276                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18277                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18278                if (sdEncKey == null) {
18279                    Slog.e(TAG, "Failed to create encryption keys");
18280                    return null;
18281                }
18282            }
18283            return sdEncKey;
18284        } catch (NoSuchAlgorithmException nsae) {
18285            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18286            return null;
18287        } catch (IOException ioe) {
18288            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18289            return null;
18290        }
18291    }
18292
18293    /*
18294     * Update media status on PackageManager.
18295     */
18296    @Override
18297    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18298        int callingUid = Binder.getCallingUid();
18299        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18300            throw new SecurityException("Media status can only be updated by the system");
18301        }
18302        // reader; this apparently protects mMediaMounted, but should probably
18303        // be a different lock in that case.
18304        synchronized (mPackages) {
18305            Log.i(TAG, "Updating external media status from "
18306                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18307                    + (mediaStatus ? "mounted" : "unmounted"));
18308            if (DEBUG_SD_INSTALL)
18309                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18310                        + ", mMediaMounted=" + mMediaMounted);
18311            if (mediaStatus == mMediaMounted) {
18312                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18313                        : 0, -1);
18314                mHandler.sendMessage(msg);
18315                return;
18316            }
18317            mMediaMounted = mediaStatus;
18318        }
18319        // Queue up an async operation since the package installation may take a
18320        // little while.
18321        mHandler.post(new Runnable() {
18322            public void run() {
18323                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18324            }
18325        });
18326    }
18327
18328    /**
18329     * Called by MountService when the initial ASECs to scan are available.
18330     * Should block until all the ASEC containers are finished being scanned.
18331     */
18332    public void scanAvailableAsecs() {
18333        updateExternalMediaStatusInner(true, false, false);
18334    }
18335
18336    /*
18337     * Collect information of applications on external media, map them against
18338     * existing containers and update information based on current mount status.
18339     * Please note that we always have to report status if reportStatus has been
18340     * set to true especially when unloading packages.
18341     */
18342    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18343            boolean externalStorage) {
18344        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18345        int[] uidArr = EmptyArray.INT;
18346
18347        final String[] list = PackageHelper.getSecureContainerList();
18348        if (ArrayUtils.isEmpty(list)) {
18349            Log.i(TAG, "No secure containers found");
18350        } else {
18351            // Process list of secure containers and categorize them
18352            // as active or stale based on their package internal state.
18353
18354            // reader
18355            synchronized (mPackages) {
18356                for (String cid : list) {
18357                    // Leave stages untouched for now; installer service owns them
18358                    if (PackageInstallerService.isStageName(cid)) continue;
18359
18360                    if (DEBUG_SD_INSTALL)
18361                        Log.i(TAG, "Processing container " + cid);
18362                    String pkgName = getAsecPackageName(cid);
18363                    if (pkgName == null) {
18364                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18365                        continue;
18366                    }
18367                    if (DEBUG_SD_INSTALL)
18368                        Log.i(TAG, "Looking for pkg : " + pkgName);
18369
18370                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18371                    if (ps == null) {
18372                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18373                        continue;
18374                    }
18375
18376                    /*
18377                     * Skip packages that are not external if we're unmounting
18378                     * external storage.
18379                     */
18380                    if (externalStorage && !isMounted && !isExternal(ps)) {
18381                        continue;
18382                    }
18383
18384                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18385                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18386                    // The package status is changed only if the code path
18387                    // matches between settings and the container id.
18388                    if (ps.codePathString != null
18389                            && ps.codePathString.startsWith(args.getCodePath())) {
18390                        if (DEBUG_SD_INSTALL) {
18391                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18392                                    + " at code path: " + ps.codePathString);
18393                        }
18394
18395                        // We do have a valid package installed on sdcard
18396                        processCids.put(args, ps.codePathString);
18397                        final int uid = ps.appId;
18398                        if (uid != -1) {
18399                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18400                        }
18401                    } else {
18402                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18403                                + ps.codePathString);
18404                    }
18405                }
18406            }
18407
18408            Arrays.sort(uidArr);
18409        }
18410
18411        // Process packages with valid entries.
18412        if (isMounted) {
18413            if (DEBUG_SD_INSTALL)
18414                Log.i(TAG, "Loading packages");
18415            loadMediaPackages(processCids, uidArr, externalStorage);
18416            startCleaningPackages();
18417            mInstallerService.onSecureContainersAvailable();
18418        } else {
18419            if (DEBUG_SD_INSTALL)
18420                Log.i(TAG, "Unloading packages");
18421            unloadMediaPackages(processCids, uidArr, reportStatus);
18422        }
18423    }
18424
18425    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18426            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18427        final int size = infos.size();
18428        final String[] packageNames = new String[size];
18429        final int[] packageUids = new int[size];
18430        for (int i = 0; i < size; i++) {
18431            final ApplicationInfo info = infos.get(i);
18432            packageNames[i] = info.packageName;
18433            packageUids[i] = info.uid;
18434        }
18435        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18436                finishedReceiver);
18437    }
18438
18439    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18440            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18441        sendResourcesChangedBroadcast(mediaStatus, replacing,
18442                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18443    }
18444
18445    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18446            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18447        int size = pkgList.length;
18448        if (size > 0) {
18449            // Send broadcasts here
18450            Bundle extras = new Bundle();
18451            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18452            if (uidArr != null) {
18453                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18454            }
18455            if (replacing) {
18456                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18457            }
18458            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18459                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18460            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18461        }
18462    }
18463
18464   /*
18465     * Look at potentially valid container ids from processCids If package
18466     * information doesn't match the one on record or package scanning fails,
18467     * the cid is added to list of removeCids. We currently don't delete stale
18468     * containers.
18469     */
18470    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18471            boolean externalStorage) {
18472        ArrayList<String> pkgList = new ArrayList<String>();
18473        Set<AsecInstallArgs> keys = processCids.keySet();
18474
18475        for (AsecInstallArgs args : keys) {
18476            String codePath = processCids.get(args);
18477            if (DEBUG_SD_INSTALL)
18478                Log.i(TAG, "Loading container : " + args.cid);
18479            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18480            try {
18481                // Make sure there are no container errors first.
18482                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18483                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18484                            + " when installing from sdcard");
18485                    continue;
18486                }
18487                // Check code path here.
18488                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18489                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18490                            + " does not match one in settings " + codePath);
18491                    continue;
18492                }
18493                // Parse package
18494                int parseFlags = mDefParseFlags;
18495                if (args.isExternalAsec()) {
18496                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18497                }
18498                if (args.isFwdLocked()) {
18499                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18500                }
18501
18502                synchronized (mInstallLock) {
18503                    PackageParser.Package pkg = null;
18504                    try {
18505                        // Sadly we don't know the package name yet to freeze it
18506                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18507                                SCAN_IGNORE_FROZEN, 0, null);
18508                    } catch (PackageManagerException e) {
18509                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18510                    }
18511                    // Scan the package
18512                    if (pkg != null) {
18513                        /*
18514                         * TODO why is the lock being held? doPostInstall is
18515                         * called in other places without the lock. This needs
18516                         * to be straightened out.
18517                         */
18518                        // writer
18519                        synchronized (mPackages) {
18520                            retCode = PackageManager.INSTALL_SUCCEEDED;
18521                            pkgList.add(pkg.packageName);
18522                            // Post process args
18523                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18524                                    pkg.applicationInfo.uid);
18525                        }
18526                    } else {
18527                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18528                    }
18529                }
18530
18531            } finally {
18532                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18533                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18534                }
18535            }
18536        }
18537        // writer
18538        synchronized (mPackages) {
18539            // If the platform SDK has changed since the last time we booted,
18540            // we need to re-grant app permission to catch any new ones that
18541            // appear. This is really a hack, and means that apps can in some
18542            // cases get permissions that the user didn't initially explicitly
18543            // allow... it would be nice to have some better way to handle
18544            // this situation.
18545            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18546                    : mSettings.getInternalVersion();
18547            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18548                    : StorageManager.UUID_PRIVATE_INTERNAL;
18549
18550            int updateFlags = UPDATE_PERMISSIONS_ALL;
18551            if (ver.sdkVersion != mSdkVersion) {
18552                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18553                        + mSdkVersion + "; regranting permissions for external");
18554                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18555            }
18556            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18557
18558            // Yay, everything is now upgraded
18559            ver.forceCurrent();
18560
18561            // can downgrade to reader
18562            // Persist settings
18563            mSettings.writeLPr();
18564        }
18565        // Send a broadcast to let everyone know we are done processing
18566        if (pkgList.size() > 0) {
18567            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18568        }
18569    }
18570
18571   /*
18572     * Utility method to unload a list of specified containers
18573     */
18574    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18575        // Just unmount all valid containers.
18576        for (AsecInstallArgs arg : cidArgs) {
18577            synchronized (mInstallLock) {
18578                arg.doPostDeleteLI(false);
18579           }
18580       }
18581   }
18582
18583    /*
18584     * Unload packages mounted on external media. This involves deleting package
18585     * data from internal structures, sending broadcasts about disabled packages,
18586     * gc'ing to free up references, unmounting all secure containers
18587     * corresponding to packages on external media, and posting a
18588     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18589     * that we always have to post this message if status has been requested no
18590     * matter what.
18591     */
18592    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18593            final boolean reportStatus) {
18594        if (DEBUG_SD_INSTALL)
18595            Log.i(TAG, "unloading media packages");
18596        ArrayList<String> pkgList = new ArrayList<String>();
18597        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18598        final Set<AsecInstallArgs> keys = processCids.keySet();
18599        for (AsecInstallArgs args : keys) {
18600            String pkgName = args.getPackageName();
18601            if (DEBUG_SD_INSTALL)
18602                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18603            // Delete package internally
18604            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18605            synchronized (mInstallLock) {
18606                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18607                final boolean res;
18608                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18609                        "unloadMediaPackages")) {
18610                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18611                            null);
18612                }
18613                if (res) {
18614                    pkgList.add(pkgName);
18615                } else {
18616                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18617                    failedList.add(args);
18618                }
18619            }
18620        }
18621
18622        // reader
18623        synchronized (mPackages) {
18624            // We didn't update the settings after removing each package;
18625            // write them now for all packages.
18626            mSettings.writeLPr();
18627        }
18628
18629        // We have to absolutely send UPDATED_MEDIA_STATUS only
18630        // after confirming that all the receivers processed the ordered
18631        // broadcast when packages get disabled, force a gc to clean things up.
18632        // and unload all the containers.
18633        if (pkgList.size() > 0) {
18634            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18635                    new IIntentReceiver.Stub() {
18636                public void performReceive(Intent intent, int resultCode, String data,
18637                        Bundle extras, boolean ordered, boolean sticky,
18638                        int sendingUser) throws RemoteException {
18639                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18640                            reportStatus ? 1 : 0, 1, keys);
18641                    mHandler.sendMessage(msg);
18642                }
18643            });
18644        } else {
18645            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18646                    keys);
18647            mHandler.sendMessage(msg);
18648        }
18649    }
18650
18651    private void loadPrivatePackages(final VolumeInfo vol) {
18652        mHandler.post(new Runnable() {
18653            @Override
18654            public void run() {
18655                loadPrivatePackagesInner(vol);
18656            }
18657        });
18658    }
18659
18660    private void loadPrivatePackagesInner(VolumeInfo vol) {
18661        final String volumeUuid = vol.fsUuid;
18662        if (TextUtils.isEmpty(volumeUuid)) {
18663            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18664            return;
18665        }
18666
18667        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18668        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18669        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18670
18671        final VersionInfo ver;
18672        final List<PackageSetting> packages;
18673        synchronized (mPackages) {
18674            ver = mSettings.findOrCreateVersion(volumeUuid);
18675            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18676        }
18677
18678        for (PackageSetting ps : packages) {
18679            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18680            synchronized (mInstallLock) {
18681                final PackageParser.Package pkg;
18682                try {
18683                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18684                    loaded.add(pkg.applicationInfo);
18685
18686                } catch (PackageManagerException e) {
18687                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18688                }
18689
18690                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18691                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18692                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18693                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18694                }
18695            }
18696        }
18697
18698        // Reconcile app data for all started/unlocked users
18699        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18700        final UserManager um = mContext.getSystemService(UserManager.class);
18701        for (UserInfo user : um.getUsers()) {
18702            final int flags;
18703            if (um.isUserUnlockingOrUnlocked(user.id)) {
18704                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18705            } else if (um.isUserRunning(user.id)) {
18706                flags = StorageManager.FLAG_STORAGE_DE;
18707            } else {
18708                continue;
18709            }
18710
18711            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18712            synchronized (mInstallLock) {
18713                reconcileAppsDataLI(volumeUuid, user.id, flags);
18714            }
18715        }
18716
18717        synchronized (mPackages) {
18718            int updateFlags = UPDATE_PERMISSIONS_ALL;
18719            if (ver.sdkVersion != mSdkVersion) {
18720                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18721                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18722                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18723            }
18724            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18725
18726            // Yay, everything is now upgraded
18727            ver.forceCurrent();
18728
18729            mSettings.writeLPr();
18730        }
18731
18732        for (PackageFreezer freezer : freezers) {
18733            freezer.close();
18734        }
18735
18736        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18737        sendResourcesChangedBroadcast(true, false, loaded, null);
18738    }
18739
18740    private void unloadPrivatePackages(final VolumeInfo vol) {
18741        mHandler.post(new Runnable() {
18742            @Override
18743            public void run() {
18744                unloadPrivatePackagesInner(vol);
18745            }
18746        });
18747    }
18748
18749    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18750        final String volumeUuid = vol.fsUuid;
18751        if (TextUtils.isEmpty(volumeUuid)) {
18752            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18753            return;
18754        }
18755
18756        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18757        synchronized (mInstallLock) {
18758        synchronized (mPackages) {
18759            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18760            for (PackageSetting ps : packages) {
18761                if (ps.pkg == null) continue;
18762
18763                final ApplicationInfo info = ps.pkg.applicationInfo;
18764                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18765                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18766
18767                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18768                        "unloadPrivatePackagesInner")) {
18769                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18770                            false, null)) {
18771                        unloaded.add(info);
18772                    } else {
18773                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18774                    }
18775                }
18776            }
18777
18778            mSettings.writeLPr();
18779        }
18780        }
18781
18782        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18783        sendResourcesChangedBroadcast(false, false, unloaded, null);
18784    }
18785
18786    /**
18787     * Prepare storage areas for given user on all mounted devices.
18788     */
18789    void prepareUserData(int userId, int userSerial, int flags) {
18790        synchronized (mInstallLock) {
18791            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18792            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18793                final String volumeUuid = vol.getFsUuid();
18794                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18795            }
18796        }
18797    }
18798
18799    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18800            boolean allowRecover) {
18801        // Prepare storage and verify that serial numbers are consistent; if
18802        // there's a mismatch we need to destroy to avoid leaking data
18803        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18804        try {
18805            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18806
18807            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18808                UserManagerService.enforceSerialNumber(
18809                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18810            }
18811            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18812                UserManagerService.enforceSerialNumber(
18813                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18814            }
18815
18816            synchronized (mInstallLock) {
18817                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18818            }
18819        } catch (Exception e) {
18820            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18821                    + " because we failed to prepare: " + e);
18822            destroyUserDataLI(volumeUuid, userId,
18823                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18824
18825            if (allowRecover) {
18826                // Try one last time; if we fail again we're really in trouble
18827                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18828            }
18829        }
18830    }
18831
18832    /**
18833     * Destroy storage areas for given user on all mounted devices.
18834     */
18835    void destroyUserData(int userId, int flags) {
18836        synchronized (mInstallLock) {
18837            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18838            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18839                final String volumeUuid = vol.getFsUuid();
18840                destroyUserDataLI(volumeUuid, userId, flags);
18841            }
18842        }
18843    }
18844
18845    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18846        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18847        try {
18848            // Clean up app data, profile data, and media data
18849            mInstaller.destroyUserData(volumeUuid, userId, flags);
18850
18851            // Clean up system data
18852            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18853                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18854                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18855                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18856                }
18857                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18858                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18859                }
18860            }
18861
18862            // Data with special labels is now gone, so finish the job
18863            storage.destroyUserStorage(volumeUuid, userId, flags);
18864
18865        } catch (Exception e) {
18866            logCriticalInfo(Log.WARN,
18867                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
18868        }
18869    }
18870
18871    /**
18872     * Examine all users present on given mounted volume, and destroy data
18873     * belonging to users that are no longer valid, or whose user ID has been
18874     * recycled.
18875     */
18876    private void reconcileUsers(String volumeUuid) {
18877        final List<File> files = new ArrayList<>();
18878        Collections.addAll(files, FileUtils
18879                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
18880        Collections.addAll(files, FileUtils
18881                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
18882        for (File file : files) {
18883            if (!file.isDirectory()) continue;
18884
18885            final int userId;
18886            final UserInfo info;
18887            try {
18888                userId = Integer.parseInt(file.getName());
18889                info = sUserManager.getUserInfo(userId);
18890            } catch (NumberFormatException e) {
18891                Slog.w(TAG, "Invalid user directory " + file);
18892                continue;
18893            }
18894
18895            boolean destroyUser = false;
18896            if (info == null) {
18897                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18898                        + " because no matching user was found");
18899                destroyUser = true;
18900            } else if (!mOnlyCore) {
18901                try {
18902                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18903                } catch (IOException e) {
18904                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18905                            + " because we failed to enforce serial number: " + e);
18906                    destroyUser = true;
18907                }
18908            }
18909
18910            if (destroyUser) {
18911                synchronized (mInstallLock) {
18912                    destroyUserDataLI(volumeUuid, userId,
18913                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18914                }
18915            }
18916        }
18917    }
18918
18919    private void assertPackageKnown(String volumeUuid, String packageName)
18920            throws PackageManagerException {
18921        synchronized (mPackages) {
18922            final PackageSetting ps = mSettings.mPackages.get(packageName);
18923            if (ps == null) {
18924                throw new PackageManagerException("Package " + packageName + " is unknown");
18925            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18926                throw new PackageManagerException(
18927                        "Package " + packageName + " found on unknown volume " + volumeUuid
18928                                + "; expected volume " + ps.volumeUuid);
18929            }
18930        }
18931    }
18932
18933    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18934            throws PackageManagerException {
18935        synchronized (mPackages) {
18936            final PackageSetting ps = mSettings.mPackages.get(packageName);
18937            if (ps == null) {
18938                throw new PackageManagerException("Package " + packageName + " is unknown");
18939            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18940                throw new PackageManagerException(
18941                        "Package " + packageName + " found on unknown volume " + volumeUuid
18942                                + "; expected volume " + ps.volumeUuid);
18943            } else if (!ps.getInstalled(userId)) {
18944                throw new PackageManagerException(
18945                        "Package " + packageName + " not installed for user " + userId);
18946            }
18947        }
18948    }
18949
18950    /**
18951     * Examine all apps present on given mounted volume, and destroy apps that
18952     * aren't expected, either due to uninstallation or reinstallation on
18953     * another volume.
18954     */
18955    private void reconcileApps(String volumeUuid) {
18956        final File[] files = FileUtils
18957                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18958        for (File file : files) {
18959            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18960                    && !PackageInstallerService.isStageName(file.getName());
18961            if (!isPackage) {
18962                // Ignore entries which are not packages
18963                continue;
18964            }
18965
18966            try {
18967                final PackageLite pkg = PackageParser.parsePackageLite(file,
18968                        PackageParser.PARSE_MUST_BE_APK);
18969                assertPackageKnown(volumeUuid, pkg.packageName);
18970
18971            } catch (PackageParserException | PackageManagerException e) {
18972                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18973                synchronized (mInstallLock) {
18974                    removeCodePathLI(file);
18975                }
18976            }
18977        }
18978    }
18979
18980    /**
18981     * Reconcile all app data for the given user.
18982     * <p>
18983     * Verifies that directories exist and that ownership and labeling is
18984     * correct for all installed apps on all mounted volumes.
18985     */
18986    void reconcileAppsData(int userId, int flags) {
18987        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18988        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18989            final String volumeUuid = vol.getFsUuid();
18990            synchronized (mInstallLock) {
18991                reconcileAppsDataLI(volumeUuid, userId, flags);
18992            }
18993        }
18994    }
18995
18996    /**
18997     * Reconcile all app data on given mounted volume.
18998     * <p>
18999     * Destroys app data that isn't expected, either due to uninstallation or
19000     * reinstallation on another volume.
19001     * <p>
19002     * Verifies that directories exist and that ownership and labeling is
19003     * correct for all installed apps.
19004     */
19005    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19006        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19007                + Integer.toHexString(flags));
19008
19009        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19010        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19011
19012        boolean restoreconNeeded = false;
19013
19014        // First look for stale data that doesn't belong, and check if things
19015        // have changed since we did our last restorecon
19016        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19017            if (!StorageManager.isUserKeyUnlocked(userId)) {
19018                throw new RuntimeException(
19019                        "Yikes, someone asked us to reconcile CE storage while " + userId
19020                                + " was still locked; this would have caused massive data loss!");
19021            }
19022
19023            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19024
19025            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19026            for (File file : files) {
19027                final String packageName = file.getName();
19028                try {
19029                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19030                } catch (PackageManagerException e) {
19031                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19032                    try {
19033                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19034                                StorageManager.FLAG_STORAGE_CE, 0);
19035                    } catch (InstallerException e2) {
19036                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19037                    }
19038                }
19039            }
19040        }
19041        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19042            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19043
19044            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19045            for (File file : files) {
19046                final String packageName = file.getName();
19047                try {
19048                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19049                } catch (PackageManagerException e) {
19050                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19051                    try {
19052                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19053                                StorageManager.FLAG_STORAGE_DE, 0);
19054                    } catch (InstallerException e2) {
19055                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19056                    }
19057                }
19058            }
19059        }
19060
19061        // Ensure that data directories are ready to roll for all packages
19062        // installed for this volume and user
19063        final List<PackageSetting> packages;
19064        synchronized (mPackages) {
19065            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19066        }
19067        int preparedCount = 0;
19068        for (PackageSetting ps : packages) {
19069            final String packageName = ps.name;
19070            if (ps.pkg == null) {
19071                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19072                // TODO: might be due to legacy ASEC apps; we should circle back
19073                // and reconcile again once they're scanned
19074                continue;
19075            }
19076
19077            if (ps.getInstalled(userId)) {
19078                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19079
19080                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19081                    // We may have just shuffled around app data directories, so
19082                    // prepare them one more time
19083                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19084                }
19085
19086                preparedCount++;
19087            }
19088        }
19089
19090        if (restoreconNeeded) {
19091            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19092                SELinuxMMAC.setRestoreconDone(ceDir);
19093            }
19094            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19095                SELinuxMMAC.setRestoreconDone(deDir);
19096            }
19097        }
19098
19099        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19100                + " packages; restoreconNeeded was " + restoreconNeeded);
19101    }
19102
19103    /**
19104     * Prepare app data for the given app just after it was installed or
19105     * upgraded. This method carefully only touches users that it's installed
19106     * for, and it forces a restorecon to handle any seinfo changes.
19107     * <p>
19108     * Verifies that directories exist and that ownership and labeling is
19109     * correct for all installed apps. If there is an ownership mismatch, it
19110     * will try recovering system apps by wiping data; third-party app data is
19111     * left intact.
19112     * <p>
19113     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19114     */
19115    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19116        final PackageSetting ps;
19117        synchronized (mPackages) {
19118            ps = mSettings.mPackages.get(pkg.packageName);
19119            mSettings.writeKernelMappingLPr(ps);
19120        }
19121
19122        final UserManager um = mContext.getSystemService(UserManager.class);
19123        for (UserInfo user : um.getUsers()) {
19124            final int flags;
19125            if (um.isUserUnlockingOrUnlocked(user.id)) {
19126                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19127            } else if (um.isUserRunning(user.id)) {
19128                flags = StorageManager.FLAG_STORAGE_DE;
19129            } else {
19130                continue;
19131            }
19132
19133            if (ps.getInstalled(user.id)) {
19134                // Whenever an app changes, force a restorecon of its data
19135                // TODO: when user data is locked, mark that we're still dirty
19136                prepareAppDataLIF(pkg, user.id, flags, true);
19137            }
19138        }
19139    }
19140
19141    /**
19142     * Prepare app data for the given app.
19143     * <p>
19144     * Verifies that directories exist and that ownership and labeling is
19145     * correct for all installed apps. If there is an ownership mismatch, this
19146     * will try recovering system apps by wiping data; third-party app data is
19147     * left intact.
19148     */
19149    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19150            boolean restoreconNeeded) {
19151        if (pkg == null) {
19152            Slog.wtf(TAG, "Package was null!", new Throwable());
19153            return;
19154        }
19155        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19156        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19157        for (int i = 0; i < childCount; i++) {
19158            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19159        }
19160    }
19161
19162    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19163            boolean restoreconNeeded) {
19164        if (DEBUG_APP_DATA) {
19165            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19166                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19167        }
19168
19169        final String volumeUuid = pkg.volumeUuid;
19170        final String packageName = pkg.packageName;
19171        final ApplicationInfo app = pkg.applicationInfo;
19172        final int appId = UserHandle.getAppId(app.uid);
19173
19174        Preconditions.checkNotNull(app.seinfo);
19175
19176        try {
19177            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19178                    appId, app.seinfo, app.targetSdkVersion);
19179        } catch (InstallerException e) {
19180            if (app.isSystemApp()) {
19181                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19182                        + ", but trying to recover: " + e);
19183                destroyAppDataLeafLIF(pkg, userId, flags);
19184                try {
19185                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19186                            appId, app.seinfo, app.targetSdkVersion);
19187                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19188                } catch (InstallerException e2) {
19189                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19190                }
19191            } else {
19192                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19193            }
19194        }
19195
19196        if (restoreconNeeded) {
19197            try {
19198                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19199                        app.seinfo);
19200            } catch (InstallerException e) {
19201                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19202            }
19203        }
19204
19205        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19206            try {
19207                // CE storage is unlocked right now, so read out the inode and
19208                // remember for use later when it's locked
19209                // TODO: mark this structure as dirty so we persist it!
19210                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19211                        StorageManager.FLAG_STORAGE_CE);
19212                synchronized (mPackages) {
19213                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19214                    if (ps != null) {
19215                        ps.setCeDataInode(ceDataInode, userId);
19216                    }
19217                }
19218            } catch (InstallerException e) {
19219                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19220            }
19221        }
19222
19223        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19224    }
19225
19226    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19227        if (pkg == null) {
19228            Slog.wtf(TAG, "Package was null!", new Throwable());
19229            return;
19230        }
19231        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19232        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19233        for (int i = 0; i < childCount; i++) {
19234            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19235        }
19236    }
19237
19238    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19239        final String volumeUuid = pkg.volumeUuid;
19240        final String packageName = pkg.packageName;
19241        final ApplicationInfo app = pkg.applicationInfo;
19242
19243        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19244            // Create a native library symlink only if we have native libraries
19245            // and if the native libraries are 32 bit libraries. We do not provide
19246            // this symlink for 64 bit libraries.
19247            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19248                final String nativeLibPath = app.nativeLibraryDir;
19249                try {
19250                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19251                            nativeLibPath, userId);
19252                } catch (InstallerException e) {
19253                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19254                }
19255            }
19256        }
19257    }
19258
19259    /**
19260     * For system apps on non-FBE devices, this method migrates any existing
19261     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19262     * requested by the app.
19263     */
19264    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19265        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19266                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19267            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19268                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19269            try {
19270                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19271                        storageTarget);
19272            } catch (InstallerException e) {
19273                logCriticalInfo(Log.WARN,
19274                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19275            }
19276            return true;
19277        } else {
19278            return false;
19279        }
19280    }
19281
19282    public PackageFreezer freezePackage(String packageName, String killReason) {
19283        return new PackageFreezer(packageName, killReason);
19284    }
19285
19286    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19287            String killReason) {
19288        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19289            return new PackageFreezer();
19290        } else {
19291            return freezePackage(packageName, killReason);
19292        }
19293    }
19294
19295    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19296            String killReason) {
19297        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19298            return new PackageFreezer();
19299        } else {
19300            return freezePackage(packageName, killReason);
19301        }
19302    }
19303
19304    /**
19305     * Class that freezes and kills the given package upon creation, and
19306     * unfreezes it upon closing. This is typically used when doing surgery on
19307     * app code/data to prevent the app from running while you're working.
19308     */
19309    private class PackageFreezer implements AutoCloseable {
19310        private final String mPackageName;
19311        private final PackageFreezer[] mChildren;
19312
19313        private final boolean mWeFroze;
19314
19315        private final AtomicBoolean mClosed = new AtomicBoolean();
19316        private final CloseGuard mCloseGuard = CloseGuard.get();
19317
19318        /**
19319         * Create and return a stub freezer that doesn't actually do anything,
19320         * typically used when someone requested
19321         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19322         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19323         */
19324        public PackageFreezer() {
19325            mPackageName = null;
19326            mChildren = null;
19327            mWeFroze = false;
19328            mCloseGuard.open("close");
19329        }
19330
19331        public PackageFreezer(String packageName, String killReason) {
19332            synchronized (mPackages) {
19333                mPackageName = packageName;
19334                mWeFroze = mFrozenPackages.add(mPackageName);
19335
19336                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19337                if (ps != null) {
19338                    killApplication(ps.name, ps.appId, killReason);
19339                }
19340
19341                final PackageParser.Package p = mPackages.get(packageName);
19342                if (p != null && p.childPackages != null) {
19343                    final int N = p.childPackages.size();
19344                    mChildren = new PackageFreezer[N];
19345                    for (int i = 0; i < N; i++) {
19346                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19347                                killReason);
19348                    }
19349                } else {
19350                    mChildren = null;
19351                }
19352            }
19353            mCloseGuard.open("close");
19354        }
19355
19356        @Override
19357        protected void finalize() throws Throwable {
19358            try {
19359                mCloseGuard.warnIfOpen();
19360                close();
19361            } finally {
19362                super.finalize();
19363            }
19364        }
19365
19366        @Override
19367        public void close() {
19368            mCloseGuard.close();
19369            if (mClosed.compareAndSet(false, true)) {
19370                synchronized (mPackages) {
19371                    if (mWeFroze) {
19372                        mFrozenPackages.remove(mPackageName);
19373                    }
19374
19375                    if (mChildren != null) {
19376                        for (PackageFreezer freezer : mChildren) {
19377                            freezer.close();
19378                        }
19379                    }
19380                }
19381            }
19382        }
19383    }
19384
19385    /**
19386     * Verify that given package is currently frozen.
19387     */
19388    private void checkPackageFrozen(String packageName) {
19389        synchronized (mPackages) {
19390            if (!mFrozenPackages.contains(packageName)) {
19391                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19392            }
19393        }
19394    }
19395
19396    @Override
19397    public int movePackage(final String packageName, final String volumeUuid) {
19398        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19399
19400        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19401        final int moveId = mNextMoveId.getAndIncrement();
19402        mHandler.post(new Runnable() {
19403            @Override
19404            public void run() {
19405                try {
19406                    movePackageInternal(packageName, volumeUuid, moveId, user);
19407                } catch (PackageManagerException e) {
19408                    Slog.w(TAG, "Failed to move " + packageName, e);
19409                    mMoveCallbacks.notifyStatusChanged(moveId,
19410                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19411                }
19412            }
19413        });
19414        return moveId;
19415    }
19416
19417    private void movePackageInternal(final String packageName, final String volumeUuid,
19418            final int moveId, UserHandle user) throws PackageManagerException {
19419        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19420        final PackageManager pm = mContext.getPackageManager();
19421
19422        final boolean currentAsec;
19423        final String currentVolumeUuid;
19424        final File codeFile;
19425        final String installerPackageName;
19426        final String packageAbiOverride;
19427        final int appId;
19428        final String seinfo;
19429        final String label;
19430        final int targetSdkVersion;
19431        final PackageFreezer freezer;
19432
19433        // reader
19434        synchronized (mPackages) {
19435            final PackageParser.Package pkg = mPackages.get(packageName);
19436            final PackageSetting ps = mSettings.mPackages.get(packageName);
19437            if (pkg == null || ps == null) {
19438                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19439            }
19440
19441            if (pkg.applicationInfo.isSystemApp()) {
19442                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19443                        "Cannot move system application");
19444            }
19445
19446            if (pkg.applicationInfo.isExternalAsec()) {
19447                currentAsec = true;
19448                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19449            } else if (pkg.applicationInfo.isForwardLocked()) {
19450                currentAsec = true;
19451                currentVolumeUuid = "forward_locked";
19452            } else {
19453                currentAsec = false;
19454                currentVolumeUuid = ps.volumeUuid;
19455
19456                final File probe = new File(pkg.codePath);
19457                final File probeOat = new File(probe, "oat");
19458                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19459                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19460                            "Move only supported for modern cluster style installs");
19461                }
19462            }
19463
19464            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19465                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19466                        "Package already moved to " + volumeUuid);
19467            }
19468            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19469                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19470                        "Device admin cannot be moved");
19471            }
19472
19473            if (mFrozenPackages.contains(packageName)) {
19474                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19475                        "Failed to move already frozen package");
19476            }
19477
19478            codeFile = new File(pkg.codePath);
19479            installerPackageName = ps.installerPackageName;
19480            packageAbiOverride = ps.cpuAbiOverrideString;
19481            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19482            seinfo = pkg.applicationInfo.seinfo;
19483            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19484            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19485            freezer = new PackageFreezer(packageName, "movePackageInternal");
19486        }
19487
19488        final Bundle extras = new Bundle();
19489        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19490        extras.putString(Intent.EXTRA_TITLE, label);
19491        mMoveCallbacks.notifyCreated(moveId, extras);
19492
19493        int installFlags;
19494        final boolean moveCompleteApp;
19495        final File measurePath;
19496
19497        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19498            installFlags = INSTALL_INTERNAL;
19499            moveCompleteApp = !currentAsec;
19500            measurePath = Environment.getDataAppDirectory(volumeUuid);
19501        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19502            installFlags = INSTALL_EXTERNAL;
19503            moveCompleteApp = false;
19504            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19505        } else {
19506            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19507            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19508                    || !volume.isMountedWritable()) {
19509                freezer.close();
19510                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19511                        "Move location not mounted private volume");
19512            }
19513
19514            Preconditions.checkState(!currentAsec);
19515
19516            installFlags = INSTALL_INTERNAL;
19517            moveCompleteApp = true;
19518            measurePath = Environment.getDataAppDirectory(volumeUuid);
19519        }
19520
19521        final PackageStats stats = new PackageStats(null, -1);
19522        synchronized (mInstaller) {
19523            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19524                freezer.close();
19525                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19526                        "Failed to measure package size");
19527            }
19528        }
19529
19530        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19531                + stats.dataSize);
19532
19533        final long startFreeBytes = measurePath.getFreeSpace();
19534        final long sizeBytes;
19535        if (moveCompleteApp) {
19536            sizeBytes = stats.codeSize + stats.dataSize;
19537        } else {
19538            sizeBytes = stats.codeSize;
19539        }
19540
19541        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19542            freezer.close();
19543            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19544                    "Not enough free space to move");
19545        }
19546
19547        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19548
19549        final CountDownLatch installedLatch = new CountDownLatch(1);
19550        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19551            @Override
19552            public void onUserActionRequired(Intent intent) throws RemoteException {
19553                throw new IllegalStateException();
19554            }
19555
19556            @Override
19557            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19558                    Bundle extras) throws RemoteException {
19559                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19560                        + PackageManager.installStatusToString(returnCode, msg));
19561
19562                installedLatch.countDown();
19563                freezer.close();
19564
19565                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19566                switch (status) {
19567                    case PackageInstaller.STATUS_SUCCESS:
19568                        mMoveCallbacks.notifyStatusChanged(moveId,
19569                                PackageManager.MOVE_SUCCEEDED);
19570                        break;
19571                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19572                        mMoveCallbacks.notifyStatusChanged(moveId,
19573                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19574                        break;
19575                    default:
19576                        mMoveCallbacks.notifyStatusChanged(moveId,
19577                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19578                        break;
19579                }
19580            }
19581        };
19582
19583        final MoveInfo move;
19584        if (moveCompleteApp) {
19585            // Kick off a thread to report progress estimates
19586            new Thread() {
19587                @Override
19588                public void run() {
19589                    while (true) {
19590                        try {
19591                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19592                                break;
19593                            }
19594                        } catch (InterruptedException ignored) {
19595                        }
19596
19597                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19598                        final int progress = 10 + (int) MathUtils.constrain(
19599                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19600                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19601                    }
19602                }
19603            }.start();
19604
19605            final String dataAppName = codeFile.getName();
19606            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19607                    dataAppName, appId, seinfo, targetSdkVersion);
19608        } else {
19609            move = null;
19610        }
19611
19612        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19613
19614        final Message msg = mHandler.obtainMessage(INIT_COPY);
19615        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19616        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19617                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19618                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19619        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19620        msg.obj = params;
19621
19622        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19623                System.identityHashCode(msg.obj));
19624        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19625                System.identityHashCode(msg.obj));
19626
19627        mHandler.sendMessage(msg);
19628    }
19629
19630    @Override
19631    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19632        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19633
19634        final int realMoveId = mNextMoveId.getAndIncrement();
19635        final Bundle extras = new Bundle();
19636        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19637        mMoveCallbacks.notifyCreated(realMoveId, extras);
19638
19639        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19640            @Override
19641            public void onCreated(int moveId, Bundle extras) {
19642                // Ignored
19643            }
19644
19645            @Override
19646            public void onStatusChanged(int moveId, int status, long estMillis) {
19647                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19648            }
19649        };
19650
19651        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19652        storage.setPrimaryStorageUuid(volumeUuid, callback);
19653        return realMoveId;
19654    }
19655
19656    @Override
19657    public int getMoveStatus(int moveId) {
19658        mContext.enforceCallingOrSelfPermission(
19659                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19660        return mMoveCallbacks.mLastStatus.get(moveId);
19661    }
19662
19663    @Override
19664    public void registerMoveCallback(IPackageMoveObserver callback) {
19665        mContext.enforceCallingOrSelfPermission(
19666                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19667        mMoveCallbacks.register(callback);
19668    }
19669
19670    @Override
19671    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19672        mContext.enforceCallingOrSelfPermission(
19673                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19674        mMoveCallbacks.unregister(callback);
19675    }
19676
19677    @Override
19678    public boolean setInstallLocation(int loc) {
19679        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19680                null);
19681        if (getInstallLocation() == loc) {
19682            return true;
19683        }
19684        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19685                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19686            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19687                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19688            return true;
19689        }
19690        return false;
19691   }
19692
19693    @Override
19694    public int getInstallLocation() {
19695        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19696                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19697                PackageHelper.APP_INSTALL_AUTO);
19698    }
19699
19700    /** Called by UserManagerService */
19701    void cleanUpUser(UserManagerService userManager, int userHandle) {
19702        synchronized (mPackages) {
19703            mDirtyUsers.remove(userHandle);
19704            mUserNeedsBadging.delete(userHandle);
19705            mSettings.removeUserLPw(userHandle);
19706            mPendingBroadcasts.remove(userHandle);
19707            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19708            removeUnusedPackagesLPw(userManager, userHandle);
19709        }
19710    }
19711
19712    /**
19713     * We're removing userHandle and would like to remove any downloaded packages
19714     * that are no longer in use by any other user.
19715     * @param userHandle the user being removed
19716     */
19717    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19718        final boolean DEBUG_CLEAN_APKS = false;
19719        int [] users = userManager.getUserIds();
19720        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19721        while (psit.hasNext()) {
19722            PackageSetting ps = psit.next();
19723            if (ps.pkg == null) {
19724                continue;
19725            }
19726            final String packageName = ps.pkg.packageName;
19727            // Skip over if system app
19728            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19729                continue;
19730            }
19731            if (DEBUG_CLEAN_APKS) {
19732                Slog.i(TAG, "Checking package " + packageName);
19733            }
19734            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19735            if (keep) {
19736                if (DEBUG_CLEAN_APKS) {
19737                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19738                }
19739            } else {
19740                for (int i = 0; i < users.length; i++) {
19741                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19742                        keep = true;
19743                        if (DEBUG_CLEAN_APKS) {
19744                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19745                                    + users[i]);
19746                        }
19747                        break;
19748                    }
19749                }
19750            }
19751            if (!keep) {
19752                if (DEBUG_CLEAN_APKS) {
19753                    Slog.i(TAG, "  Removing package " + packageName);
19754                }
19755                mHandler.post(new Runnable() {
19756                    public void run() {
19757                        deletePackageX(packageName, userHandle, 0);
19758                    } //end run
19759                });
19760            }
19761        }
19762    }
19763
19764    /** Called by UserManagerService */
19765    void createNewUser(int userHandle) {
19766        synchronized (mInstallLock) {
19767            mSettings.createNewUserLI(this, mInstaller, userHandle);
19768        }
19769        synchronized (mPackages) {
19770            applyFactoryDefaultBrowserLPw(userHandle);
19771            primeDomainVerificationsLPw(userHandle);
19772        }
19773    }
19774
19775    void newUserCreated(final int userHandle) {
19776        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19777        // If permission review for legacy apps is required, we represent
19778        // dagerous permissions for such apps as always granted runtime
19779        // permissions to keep per user flag state whether review is needed.
19780        // Hence, if a new user is added we have to propagate dangerous
19781        // permission grants for these legacy apps.
19782        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19783            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19784                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19785        }
19786    }
19787
19788    @Override
19789    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19790        mContext.enforceCallingOrSelfPermission(
19791                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19792                "Only package verification agents can read the verifier device identity");
19793
19794        synchronized (mPackages) {
19795            return mSettings.getVerifierDeviceIdentityLPw();
19796        }
19797    }
19798
19799    @Override
19800    public void setPermissionEnforced(String permission, boolean enforced) {
19801        // TODO: Now that we no longer change GID for storage, this should to away.
19802        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19803                "setPermissionEnforced");
19804        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19805            synchronized (mPackages) {
19806                if (mSettings.mReadExternalStorageEnforced == null
19807                        || mSettings.mReadExternalStorageEnforced != enforced) {
19808                    mSettings.mReadExternalStorageEnforced = enforced;
19809                    mSettings.writeLPr();
19810                }
19811            }
19812            // kill any non-foreground processes so we restart them and
19813            // grant/revoke the GID.
19814            final IActivityManager am = ActivityManagerNative.getDefault();
19815            if (am != null) {
19816                final long token = Binder.clearCallingIdentity();
19817                try {
19818                    am.killProcessesBelowForeground("setPermissionEnforcement");
19819                } catch (RemoteException e) {
19820                } finally {
19821                    Binder.restoreCallingIdentity(token);
19822                }
19823            }
19824        } else {
19825            throw new IllegalArgumentException("No selective enforcement for " + permission);
19826        }
19827    }
19828
19829    @Override
19830    @Deprecated
19831    public boolean isPermissionEnforced(String permission) {
19832        return true;
19833    }
19834
19835    @Override
19836    public boolean isStorageLow() {
19837        final long token = Binder.clearCallingIdentity();
19838        try {
19839            final DeviceStorageMonitorInternal
19840                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19841            if (dsm != null) {
19842                return dsm.isMemoryLow();
19843            } else {
19844                return false;
19845            }
19846        } finally {
19847            Binder.restoreCallingIdentity(token);
19848        }
19849    }
19850
19851    @Override
19852    public IPackageInstaller getPackageInstaller() {
19853        return mInstallerService;
19854    }
19855
19856    private boolean userNeedsBadging(int userId) {
19857        int index = mUserNeedsBadging.indexOfKey(userId);
19858        if (index < 0) {
19859            final UserInfo userInfo;
19860            final long token = Binder.clearCallingIdentity();
19861            try {
19862                userInfo = sUserManager.getUserInfo(userId);
19863            } finally {
19864                Binder.restoreCallingIdentity(token);
19865            }
19866            final boolean b;
19867            if (userInfo != null && userInfo.isManagedProfile()) {
19868                b = true;
19869            } else {
19870                b = false;
19871            }
19872            mUserNeedsBadging.put(userId, b);
19873            return b;
19874        }
19875        return mUserNeedsBadging.valueAt(index);
19876    }
19877
19878    @Override
19879    public KeySet getKeySetByAlias(String packageName, String alias) {
19880        if (packageName == null || alias == null) {
19881            return null;
19882        }
19883        synchronized(mPackages) {
19884            final PackageParser.Package pkg = mPackages.get(packageName);
19885            if (pkg == null) {
19886                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19887                throw new IllegalArgumentException("Unknown package: " + packageName);
19888            }
19889            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19890            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19891        }
19892    }
19893
19894    @Override
19895    public KeySet getSigningKeySet(String packageName) {
19896        if (packageName == null) {
19897            return null;
19898        }
19899        synchronized(mPackages) {
19900            final PackageParser.Package pkg = mPackages.get(packageName);
19901            if (pkg == null) {
19902                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19903                throw new IllegalArgumentException("Unknown package: " + packageName);
19904            }
19905            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19906                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19907                throw new SecurityException("May not access signing KeySet of other apps.");
19908            }
19909            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19910            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19911        }
19912    }
19913
19914    @Override
19915    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19916        if (packageName == null || ks == null) {
19917            return false;
19918        }
19919        synchronized(mPackages) {
19920            final PackageParser.Package pkg = mPackages.get(packageName);
19921            if (pkg == null) {
19922                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19923                throw new IllegalArgumentException("Unknown package: " + packageName);
19924            }
19925            IBinder ksh = ks.getToken();
19926            if (ksh instanceof KeySetHandle) {
19927                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19928                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19929            }
19930            return false;
19931        }
19932    }
19933
19934    @Override
19935    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19936        if (packageName == null || ks == null) {
19937            return false;
19938        }
19939        synchronized(mPackages) {
19940            final PackageParser.Package pkg = mPackages.get(packageName);
19941            if (pkg == null) {
19942                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19943                throw new IllegalArgumentException("Unknown package: " + packageName);
19944            }
19945            IBinder ksh = ks.getToken();
19946            if (ksh instanceof KeySetHandle) {
19947                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19948                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19949            }
19950            return false;
19951        }
19952    }
19953
19954    private void deletePackageIfUnusedLPr(final String packageName) {
19955        PackageSetting ps = mSettings.mPackages.get(packageName);
19956        if (ps == null) {
19957            return;
19958        }
19959        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19960            // TODO Implement atomic delete if package is unused
19961            // It is currently possible that the package will be deleted even if it is installed
19962            // after this method returns.
19963            mHandler.post(new Runnable() {
19964                public void run() {
19965                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19966                }
19967            });
19968        }
19969    }
19970
19971    /**
19972     * Check and throw if the given before/after packages would be considered a
19973     * downgrade.
19974     */
19975    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19976            throws PackageManagerException {
19977        if (after.versionCode < before.mVersionCode) {
19978            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19979                    "Update version code " + after.versionCode + " is older than current "
19980                    + before.mVersionCode);
19981        } else if (after.versionCode == before.mVersionCode) {
19982            if (after.baseRevisionCode < before.baseRevisionCode) {
19983                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19984                        "Update base revision code " + after.baseRevisionCode
19985                        + " is older than current " + before.baseRevisionCode);
19986            }
19987
19988            if (!ArrayUtils.isEmpty(after.splitNames)) {
19989                for (int i = 0; i < after.splitNames.length; i++) {
19990                    final String splitName = after.splitNames[i];
19991                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19992                    if (j != -1) {
19993                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19994                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19995                                    "Update split " + splitName + " revision code "
19996                                    + after.splitRevisionCodes[i] + " is older than current "
19997                                    + before.splitRevisionCodes[j]);
19998                        }
19999                    }
20000                }
20001            }
20002        }
20003    }
20004
20005    private static class MoveCallbacks extends Handler {
20006        private static final int MSG_CREATED = 1;
20007        private static final int MSG_STATUS_CHANGED = 2;
20008
20009        private final RemoteCallbackList<IPackageMoveObserver>
20010                mCallbacks = new RemoteCallbackList<>();
20011
20012        private final SparseIntArray mLastStatus = new SparseIntArray();
20013
20014        public MoveCallbacks(Looper looper) {
20015            super(looper);
20016        }
20017
20018        public void register(IPackageMoveObserver callback) {
20019            mCallbacks.register(callback);
20020        }
20021
20022        public void unregister(IPackageMoveObserver callback) {
20023            mCallbacks.unregister(callback);
20024        }
20025
20026        @Override
20027        public void handleMessage(Message msg) {
20028            final SomeArgs args = (SomeArgs) msg.obj;
20029            final int n = mCallbacks.beginBroadcast();
20030            for (int i = 0; i < n; i++) {
20031                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20032                try {
20033                    invokeCallback(callback, msg.what, args);
20034                } catch (RemoteException ignored) {
20035                }
20036            }
20037            mCallbacks.finishBroadcast();
20038            args.recycle();
20039        }
20040
20041        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20042                throws RemoteException {
20043            switch (what) {
20044                case MSG_CREATED: {
20045                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20046                    break;
20047                }
20048                case MSG_STATUS_CHANGED: {
20049                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20050                    break;
20051                }
20052            }
20053        }
20054
20055        private void notifyCreated(int moveId, Bundle extras) {
20056            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20057
20058            final SomeArgs args = SomeArgs.obtain();
20059            args.argi1 = moveId;
20060            args.arg2 = extras;
20061            obtainMessage(MSG_CREATED, args).sendToTarget();
20062        }
20063
20064        private void notifyStatusChanged(int moveId, int status) {
20065            notifyStatusChanged(moveId, status, -1);
20066        }
20067
20068        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20069            Slog.v(TAG, "Move " + moveId + " status " + status);
20070
20071            final SomeArgs args = SomeArgs.obtain();
20072            args.argi1 = moveId;
20073            args.argi2 = status;
20074            args.arg3 = estMillis;
20075            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20076
20077            synchronized (mLastStatus) {
20078                mLastStatus.put(moveId, status);
20079            }
20080        }
20081    }
20082
20083    private final static class OnPermissionChangeListeners extends Handler {
20084        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20085
20086        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20087                new RemoteCallbackList<>();
20088
20089        public OnPermissionChangeListeners(Looper looper) {
20090            super(looper);
20091        }
20092
20093        @Override
20094        public void handleMessage(Message msg) {
20095            switch (msg.what) {
20096                case MSG_ON_PERMISSIONS_CHANGED: {
20097                    final int uid = msg.arg1;
20098                    handleOnPermissionsChanged(uid);
20099                } break;
20100            }
20101        }
20102
20103        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20104            mPermissionListeners.register(listener);
20105
20106        }
20107
20108        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20109            mPermissionListeners.unregister(listener);
20110        }
20111
20112        public void onPermissionsChanged(int uid) {
20113            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20114                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20115            }
20116        }
20117
20118        private void handleOnPermissionsChanged(int uid) {
20119            final int count = mPermissionListeners.beginBroadcast();
20120            try {
20121                for (int i = 0; i < count; i++) {
20122                    IOnPermissionsChangeListener callback = mPermissionListeners
20123                            .getBroadcastItem(i);
20124                    try {
20125                        callback.onPermissionsChanged(uid);
20126                    } catch (RemoteException e) {
20127                        Log.e(TAG, "Permission listener is dead", e);
20128                    }
20129                }
20130            } finally {
20131                mPermissionListeners.finishBroadcast();
20132            }
20133        }
20134    }
20135
20136    private class PackageManagerInternalImpl extends PackageManagerInternal {
20137        @Override
20138        public void setLocationPackagesProvider(PackagesProvider provider) {
20139            synchronized (mPackages) {
20140                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20141            }
20142        }
20143
20144        @Override
20145        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20146            synchronized (mPackages) {
20147                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20148            }
20149        }
20150
20151        @Override
20152        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20153            synchronized (mPackages) {
20154                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20155            }
20156        }
20157
20158        @Override
20159        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20160            synchronized (mPackages) {
20161                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20162            }
20163        }
20164
20165        @Override
20166        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20167            synchronized (mPackages) {
20168                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20169            }
20170        }
20171
20172        @Override
20173        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20174            synchronized (mPackages) {
20175                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20176            }
20177        }
20178
20179        @Override
20180        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20181            synchronized (mPackages) {
20182                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20183                        packageName, userId);
20184            }
20185        }
20186
20187        @Override
20188        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20189            synchronized (mPackages) {
20190                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20191                        packageName, userId);
20192            }
20193        }
20194
20195        @Override
20196        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20197            synchronized (mPackages) {
20198                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20199                        packageName, userId);
20200            }
20201        }
20202
20203        @Override
20204        public void setKeepUninstalledPackages(final List<String> packageList) {
20205            Preconditions.checkNotNull(packageList);
20206            List<String> removedFromList = null;
20207            synchronized (mPackages) {
20208                if (mKeepUninstalledPackages != null) {
20209                    final int packagesCount = mKeepUninstalledPackages.size();
20210                    for (int i = 0; i < packagesCount; i++) {
20211                        String oldPackage = mKeepUninstalledPackages.get(i);
20212                        if (packageList != null && packageList.contains(oldPackage)) {
20213                            continue;
20214                        }
20215                        if (removedFromList == null) {
20216                            removedFromList = new ArrayList<>();
20217                        }
20218                        removedFromList.add(oldPackage);
20219                    }
20220                }
20221                mKeepUninstalledPackages = new ArrayList<>(packageList);
20222                if (removedFromList != null) {
20223                    final int removedCount = removedFromList.size();
20224                    for (int i = 0; i < removedCount; i++) {
20225                        deletePackageIfUnusedLPr(removedFromList.get(i));
20226                    }
20227                }
20228            }
20229        }
20230
20231        @Override
20232        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20233            synchronized (mPackages) {
20234                // If we do not support permission review, done.
20235                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20236                    return false;
20237                }
20238
20239                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20240                if (packageSetting == null) {
20241                    return false;
20242                }
20243
20244                // Permission review applies only to apps not supporting the new permission model.
20245                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20246                    return false;
20247                }
20248
20249                // Legacy apps have the permission and get user consent on launch.
20250                PermissionsState permissionsState = packageSetting.getPermissionsState();
20251                return permissionsState.isPermissionReviewRequired(userId);
20252            }
20253        }
20254
20255        @Override
20256        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20257            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20258        }
20259
20260        @Override
20261        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20262                int userId) {
20263            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20264        }
20265    }
20266
20267    @Override
20268    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20269        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20270        synchronized (mPackages) {
20271            final long identity = Binder.clearCallingIdentity();
20272            try {
20273                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20274                        packageNames, userId);
20275            } finally {
20276                Binder.restoreCallingIdentity(identity);
20277            }
20278        }
20279    }
20280
20281    private static void enforceSystemOrPhoneCaller(String tag) {
20282        int callingUid = Binder.getCallingUid();
20283        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20284            throw new SecurityException(
20285                    "Cannot call " + tag + " from UID " + callingUid);
20286        }
20287    }
20288
20289    boolean isHistoricalPackageUsageAvailable() {
20290        return mPackageUsage.isHistoricalPackageUsageAvailable();
20291    }
20292
20293    /**
20294     * Return a <b>copy</b> of the collection of packages known to the package manager.
20295     * @return A copy of the values of mPackages.
20296     */
20297    Collection<PackageParser.Package> getPackages() {
20298        synchronized (mPackages) {
20299            return new ArrayList<>(mPackages.values());
20300        }
20301    }
20302
20303    /**
20304     * Logs process start information (including base APK hash) to the security log.
20305     * @hide
20306     */
20307    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20308            String apkFile, int pid) {
20309        if (!SecurityLog.isLoggingEnabled()) {
20310            return;
20311        }
20312        Bundle data = new Bundle();
20313        data.putLong("startTimestamp", System.currentTimeMillis());
20314        data.putString("processName", processName);
20315        data.putInt("uid", uid);
20316        data.putString("seinfo", seinfo);
20317        data.putString("apkFile", apkFile);
20318        data.putInt("pid", pid);
20319        Message msg = mProcessLoggingHandler.obtainMessage(
20320                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20321        msg.setData(data);
20322        mProcessLoggingHandler.sendMessage(msg);
20323    }
20324}
20325