PackageManagerService.java revision ccdad8f85b3dbdfb29f795d82fdd60d58cbd61df
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.annotation.UserIdInt;
106import android.app.ActivityManager;
107import android.app.ActivityManagerNative;
108import android.app.IActivityManager;
109import android.app.ResourcesManager;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentSender;
120import android.content.IntentSender.SendIntentException;
121import android.content.ServiceConnection;
122import android.content.pm.ActivityInfo;
123import android.content.pm.ApplicationInfo;
124import android.content.pm.AppsQueryHelper;
125import android.content.pm.ComponentInfo;
126import android.content.pm.EphemeralApplicationInfo;
127import android.content.pm.EphemeralResolveInfo;
128import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
130import android.content.pm.FeatureInfo;
131import android.content.pm.IOnPermissionsChangeListener;
132import android.content.pm.IPackageDataObserver;
133import android.content.pm.IPackageDeleteObserver;
134import android.content.pm.IPackageDeleteObserver2;
135import android.content.pm.IPackageInstallObserver2;
136import android.content.pm.IPackageInstaller;
137import android.content.pm.IPackageManager;
138import android.content.pm.IPackageMoveObserver;
139import android.content.pm.IPackageStatsObserver;
140import android.content.pm.InstrumentationInfo;
141import android.content.pm.IntentFilterVerificationInfo;
142import android.content.pm.KeySet;
143import android.content.pm.PackageCleanItem;
144import android.content.pm.PackageInfo;
145import android.content.pm.PackageInfoLite;
146import android.content.pm.PackageInstaller;
147import android.content.pm.PackageManager;
148import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
149import android.content.pm.PackageManagerInternal;
150import android.content.pm.PackageParser;
151import android.content.pm.PackageParser.ActivityIntentInfo;
152import android.content.pm.PackageParser.PackageLite;
153import android.content.pm.PackageParser.PackageParserException;
154import android.content.pm.PackageStats;
155import android.content.pm.PackageUserState;
156import android.content.pm.ParceledListSlice;
157import android.content.pm.PermissionGroupInfo;
158import android.content.pm.PermissionInfo;
159import android.content.pm.ProviderInfo;
160import android.content.pm.ResolveInfo;
161import android.content.pm.ServiceInfo;
162import android.content.pm.Signature;
163import android.content.pm.UserInfo;
164import android.content.pm.VerifierDeviceIdentity;
165import android.content.pm.VerifierInfo;
166import android.content.res.Resources;
167import android.graphics.Bitmap;
168import android.hardware.display.DisplayManager;
169import android.net.Uri;
170import android.os.Binder;
171import android.os.Build;
172import android.os.Bundle;
173import android.os.Debug;
174import android.os.Environment;
175import android.os.Environment.UserEnvironment;
176import android.os.FileUtils;
177import android.os.Handler;
178import android.os.IBinder;
179import android.os.Looper;
180import android.os.Message;
181import android.os.Parcel;
182import android.os.ParcelFileDescriptor;
183import android.os.Process;
184import android.os.RemoteCallbackList;
185import android.os.RemoteException;
186import android.os.ResultReceiver;
187import android.os.SELinux;
188import android.os.ServiceManager;
189import android.os.SystemClock;
190import android.os.SystemProperties;
191import android.os.Trace;
192import android.os.UserHandle;
193import android.os.UserManager;
194import android.os.UserManagerInternal;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.provider.Settings.Global;
202import android.security.KeyStore;
203import android.security.SystemKeyStore;
204import android.system.ErrnoException;
205import android.system.Os;
206import android.text.TextUtils;
207import android.text.format.DateUtils;
208import android.util.ArrayMap;
209import android.util.ArraySet;
210import android.util.AtomicFile;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.PrintStreamPrinter;
218import android.util.Slog;
219import android.util.SparseArray;
220import android.util.SparseBooleanArray;
221import android.util.SparseIntArray;
222import android.util.Xml;
223import android.util.jar.StrictJarFile;
224import android.view.Display;
225
226import com.android.internal.R;
227import com.android.internal.annotations.GuardedBy;
228import com.android.internal.app.IMediaContainerService;
229import com.android.internal.app.ResolverActivity;
230import com.android.internal.content.NativeLibraryHelper;
231import com.android.internal.content.PackageHelper;
232import com.android.internal.logging.MetricsLogger;
233import com.android.internal.os.IParcelFileDescriptorFactory;
234import com.android.internal.os.InstallerConnection.InstallerException;
235import com.android.internal.os.SomeArgs;
236import com.android.internal.os.Zygote;
237import com.android.internal.telephony.CarrierAppUtils;
238import com.android.internal.util.ArrayUtils;
239import com.android.internal.util.FastPrintWriter;
240import com.android.internal.util.FastXmlSerializer;
241import com.android.internal.util.IndentingPrintWriter;
242import com.android.internal.util.Preconditions;
243import com.android.internal.util.XmlUtils;
244import com.android.server.AttributeCache;
245import com.android.server.EventLogTags;
246import com.android.server.FgThread;
247import com.android.server.IntentResolver;
248import com.android.server.LocalServices;
249import com.android.server.ServiceThread;
250import com.android.server.SystemConfig;
251import com.android.server.Watchdog;
252import com.android.server.net.NetworkPolicyManagerInternal;
253import com.android.server.pm.PermissionsState.PermissionState;
254import com.android.server.pm.Settings.DatabaseVersion;
255import com.android.server.pm.Settings.VersionInfo;
256import com.android.server.storage.DeviceStorageMonitorInternal;
257
258import dalvik.system.CloseGuard;
259import dalvik.system.DexFile;
260import dalvik.system.VMRuntime;
261
262import libcore.io.IoUtils;
263import libcore.util.EmptyArray;
264
265import org.xmlpull.v1.XmlPullParser;
266import org.xmlpull.v1.XmlPullParserException;
267import org.xmlpull.v1.XmlSerializer;
268
269import java.io.BufferedInputStream;
270import java.io.BufferedOutputStream;
271import java.io.BufferedReader;
272import java.io.ByteArrayInputStream;
273import java.io.ByteArrayOutputStream;
274import java.io.File;
275import java.io.FileDescriptor;
276import java.io.FileInputStream;
277import java.io.FileNotFoundException;
278import java.io.FileOutputStream;
279import java.io.FileReader;
280import java.io.FilenameFilter;
281import java.io.IOException;
282import java.io.InputStream;
283import java.io.PrintWriter;
284import java.nio.charset.StandardCharsets;
285import java.security.DigestInputStream;
286import java.security.MessageDigest;
287import java.security.NoSuchAlgorithmException;
288import java.security.PublicKey;
289import java.security.cert.Certificate;
290import java.security.cert.CertificateEncodingException;
291import java.security.cert.CertificateException;
292import java.text.SimpleDateFormat;
293import java.util.ArrayList;
294import java.util.Arrays;
295import java.util.Collection;
296import java.util.Collections;
297import java.util.Comparator;
298import java.util.Date;
299import java.util.HashSet;
300import java.util.Iterator;
301import java.util.List;
302import java.util.Map;
303import java.util.Objects;
304import java.util.Set;
305import java.util.concurrent.CountDownLatch;
306import java.util.concurrent.TimeUnit;
307import java.util.concurrent.atomic.AtomicBoolean;
308import java.util.concurrent.atomic.AtomicInteger;
309import java.util.concurrent.atomic.AtomicLong;
310
311/**
312 * Keep track of all those APKs everywhere.
313 * <p>
314 * Internally there are two important locks:
315 * <ul>
316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
317 * and other related state. It is a fine-grained lock that should only be held
318 * momentarily, as it's one of the most contended locks in the system.
319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
320 * operations typically involve heavy lifting of application data on disk. Since
321 * {@code installd} is single-threaded, and it's operations can often be slow,
322 * this lock should never be acquired while already holding {@link #mPackages}.
323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
324 * holding {@link #mInstallLock}.
325 * </ul>
326 * Many internal methods rely on the caller to hold the appropriate locks, and
327 * this contract is expressed through method name suffixes:
328 * <ul>
329 * <li>fooLI(): the caller must hold {@link #mInstallLock}
330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
331 * being modified must be frozen
332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
334 * </ul>
335 * <p>
336 * Because this class is very central to the platform's security; please run all
337 * CTS and unit tests whenever making modifications:
338 *
339 * <pre>
340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
341 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
342 * </pre>
343 */
344public class PackageManagerService extends IPackageManager.Stub {
345    static final String TAG = "PackageManager";
346    static final boolean DEBUG_SETTINGS = false;
347    static final boolean DEBUG_PREFERRED = false;
348    static final boolean DEBUG_UPGRADE = false;
349    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
350    private static final boolean DEBUG_BACKUP = false;
351    private static final boolean DEBUG_INSTALL = false;
352    private static final boolean DEBUG_REMOVE = false;
353    private static final boolean DEBUG_BROADCASTS = false;
354    private static final boolean DEBUG_SHOW_INFO = false;
355    private static final boolean DEBUG_PACKAGE_INFO = false;
356    private static final boolean DEBUG_INTENT_MATCHING = false;
357    private static final boolean DEBUG_PACKAGE_SCANNING = false;
358    private static final boolean DEBUG_VERIFY = false;
359    private static final boolean DEBUG_FILTERS = false;
360
361    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
362    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
363    // user, but by default initialize to this.
364    static final boolean DEBUG_DEXOPT = false;
365
366    private static final boolean DEBUG_ABI_SELECTION = false;
367    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
368    private static final boolean DEBUG_TRIAGED_MISSING = false;
369    private static final boolean DEBUG_APP_DATA = false;
370
371    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
372
373    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
374
375    private static final int RADIO_UID = Process.PHONE_UID;
376    private static final int LOG_UID = Process.LOG_UID;
377    private static final int NFC_UID = Process.NFC_UID;
378    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
379    private static final int SHELL_UID = Process.SHELL_UID;
380
381    // Cap the size of permission trees that 3rd party apps can define
382    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
383
384    // Suffix used during package installation when copying/moving
385    // package apks to install directory.
386    private static final String INSTALL_PACKAGE_SUFFIX = "-";
387
388    static final int SCAN_NO_DEX = 1<<1;
389    static final int SCAN_FORCE_DEX = 1<<2;
390    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
391    static final int SCAN_NEW_INSTALL = 1<<4;
392    static final int SCAN_NO_PATHS = 1<<5;
393    static final int SCAN_UPDATE_TIME = 1<<6;
394    static final int SCAN_DEFER_DEX = 1<<7;
395    static final int SCAN_BOOTING = 1<<8;
396    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
397    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
398    static final int SCAN_REPLACING = 1<<11;
399    static final int SCAN_REQUIRE_KNOWN = 1<<12;
400    static final int SCAN_MOVE = 1<<13;
401    static final int SCAN_INITIAL = 1<<14;
402    static final int SCAN_CHECK_ONLY = 1<<15;
403    static final int SCAN_DONT_KILL_APP = 1<<17;
404    static final int SCAN_IGNORE_FROZEN = 1<<18;
405
406    static final int REMOVE_CHATTY = 1<<16;
407
408    private static final int[] EMPTY_INT_ARRAY = new int[0];
409
410    /**
411     * Timeout (in milliseconds) after which the watchdog should declare that
412     * our handler thread is wedged.  The usual default for such things is one
413     * minute but we sometimes do very lengthy I/O operations on this thread,
414     * such as installing multi-gigabyte applications, so ours needs to be longer.
415     */
416    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
417
418    /**
419     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
420     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
421     * settings entry if available, otherwise we use the hardcoded default.  If it's been
422     * more than this long since the last fstrim, we force one during the boot sequence.
423     *
424     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
425     * one gets run at the next available charging+idle time.  This final mandatory
426     * no-fstrim check kicks in only of the other scheduling criteria is never met.
427     */
428    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
429
430    /**
431     * Whether verification is enabled by default.
432     */
433    private static final boolean DEFAULT_VERIFY_ENABLE = true;
434
435    /**
436     * The default maximum time to wait for the verification agent to return in
437     * milliseconds.
438     */
439    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
440
441    /**
442     * The default response for package verification timeout.
443     *
444     * This can be either PackageManager.VERIFICATION_ALLOW or
445     * PackageManager.VERIFICATION_REJECT.
446     */
447    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
448
449    static final String PLATFORM_PACKAGE_NAME = "android";
450
451    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
452
453    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
454            DEFAULT_CONTAINER_PACKAGE,
455            "com.android.defcontainer.DefaultContainerService");
456
457    private static final String KILL_APP_REASON_GIDS_CHANGED =
458            "permission grant or revoke changed gids";
459
460    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
461            "permissions revoked";
462
463    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
464
465    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
466
467    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
468    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
469
470    /** Permission grant: not grant the permission. */
471    private static final int GRANT_DENIED = 1;
472
473    /** Permission grant: grant the permission as an install permission. */
474    private static final int GRANT_INSTALL = 2;
475
476    /** Permission grant: grant the permission as a runtime one. */
477    private static final int GRANT_RUNTIME = 3;
478
479    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
480    private static final int GRANT_UPGRADE = 4;
481
482    /** Canonical intent used to identify what counts as a "web browser" app */
483    private static final Intent sBrowserIntent;
484    static {
485        sBrowserIntent = new Intent();
486        sBrowserIntent.setAction(Intent.ACTION_VIEW);
487        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
488        sBrowserIntent.setData(Uri.parse("http:"));
489    }
490
491    /**
492     * The set of all protected actions [i.e. those actions for which a high priority
493     * intent filter is disallowed].
494     */
495    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
496    static {
497        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
498        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
499        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
500        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
501    }
502
503    // Compilation reasons.
504    public static final int REASON_FIRST_BOOT = 0;
505    public static final int REASON_BOOT = 1;
506    public static final int REASON_INSTALL = 2;
507    public static final int REASON_BACKGROUND_DEXOPT = 3;
508    public static final int REASON_AB_OTA = 4;
509    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
510    public static final int REASON_SHARED_APK = 6;
511    public static final int REASON_FORCED_DEXOPT = 7;
512    public static final int REASON_CORE_APP = 8;
513
514    public static final int REASON_LAST = REASON_CORE_APP;
515
516    /** Special library name that skips shared libraries check during compilation. */
517    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
518
519    final ServiceThread mHandlerThread;
520
521    final PackageHandler mHandler;
522
523    private final ProcessLoggingHandler mProcessLoggingHandler;
524
525    /**
526     * Messages for {@link #mHandler} that need to wait for system ready before
527     * being dispatched.
528     */
529    private ArrayList<Message> mPostSystemReadyMessages;
530
531    final int mSdkVersion = Build.VERSION.SDK_INT;
532
533    final Context mContext;
534    final boolean mFactoryTest;
535    final boolean mOnlyCore;
536    final DisplayMetrics mMetrics;
537    final int mDefParseFlags;
538    final String[] mSeparateProcesses;
539    final boolean mIsUpgrade;
540    final boolean mIsPreNUpgrade;
541
542    /** The location for ASEC container files on internal storage. */
543    final String mAsecInternalPath;
544
545    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
546    // LOCK HELD.  Can be called with mInstallLock held.
547    @GuardedBy("mInstallLock")
548    final Installer mInstaller;
549
550    /** Directory where installed third-party apps stored */
551    final File mAppInstallDir;
552    final File mEphemeralInstallDir;
553
554    /**
555     * Directory to which applications installed internally have their
556     * 32 bit native libraries copied.
557     */
558    private File mAppLib32InstallDir;
559
560    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
561    // apps.
562    final File mDrmAppPrivateInstallDir;
563
564    // ----------------------------------------------------------------
565
566    // Lock for state used when installing and doing other long running
567    // operations.  Methods that must be called with this lock held have
568    // the suffix "LI".
569    final Object mInstallLock = new Object();
570
571    // ----------------------------------------------------------------
572
573    // Keys are String (package name), values are Package.  This also serves
574    // as the lock for the global state.  Methods that must be called with
575    // this lock held have the prefix "LP".
576    @GuardedBy("mPackages")
577    final ArrayMap<String, PackageParser.Package> mPackages =
578            new ArrayMap<String, PackageParser.Package>();
579
580    final ArrayMap<String, Set<String>> mKnownCodebase =
581            new ArrayMap<String, Set<String>>();
582
583    // Tracks available target package names -> overlay package paths.
584    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
585        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
586
587    /**
588     * Tracks new system packages [received in an OTA] that we expect to
589     * find updated user-installed versions. Keys are package name, values
590     * are package location.
591     */
592    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
593    /**
594     * Tracks high priority intent filters for protected actions. During boot, certain
595     * filter actions are protected and should never be allowed to have a high priority
596     * intent filter for them. However, there is one, and only one exception -- the
597     * setup wizard. It must be able to define a high priority intent filter for these
598     * actions to ensure there are no escapes from the wizard. We need to delay processing
599     * of these during boot as we need to look at all of the system packages in order
600     * to know which component is the setup wizard.
601     */
602    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
603    /**
604     * Whether or not processing protected filters should be deferred.
605     */
606    private boolean mDeferProtectedFilters = true;
607
608    /**
609     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
610     */
611    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
612    /**
613     * Whether or not system app permissions should be promoted from install to runtime.
614     */
615    boolean mPromoteSystemApps;
616
617    @GuardedBy("mPackages")
618    final Settings mSettings;
619
620    /**
621     * Set of package names that are currently "frozen", which means active
622     * surgery is being done on the code/data for that package. The platform
623     * will refuse to launch frozen packages to avoid race conditions.
624     *
625     * @see PackageFreezer
626     */
627    @GuardedBy("mPackages")
628    final ArraySet<String> mFrozenPackages = new ArraySet<>();
629
630    final ProtectedPackages mProtectedPackages;
631
632    boolean mFirstBoot;
633
634    // System configuration read by SystemConfig.
635    final int[] mGlobalGids;
636    final SparseArray<ArraySet<String>> mSystemPermissions;
637    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
638
639    // If mac_permissions.xml was found for seinfo labeling.
640    boolean mFoundPolicyFile;
641
642    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
643
644    public static final class SharedLibraryEntry {
645        public final String path;
646        public final String apk;
647
648        SharedLibraryEntry(String _path, String _apk) {
649            path = _path;
650            apk = _apk;
651        }
652    }
653
654    // Currently known shared libraries.
655    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
656            new ArrayMap<String, SharedLibraryEntry>();
657
658    // All available activities, for your resolving pleasure.
659    final ActivityIntentResolver mActivities =
660            new ActivityIntentResolver();
661
662    // All available receivers, for your resolving pleasure.
663    final ActivityIntentResolver mReceivers =
664            new ActivityIntentResolver();
665
666    // All available services, for your resolving pleasure.
667    final ServiceIntentResolver mServices = new ServiceIntentResolver();
668
669    // All available providers, for your resolving pleasure.
670    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
671
672    // Mapping from provider base names (first directory in content URI codePath)
673    // to the provider information.
674    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
675            new ArrayMap<String, PackageParser.Provider>();
676
677    // Mapping from instrumentation class names to info about them.
678    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
679            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
680
681    // Mapping from permission names to info about them.
682    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
683            new ArrayMap<String, PackageParser.PermissionGroup>();
684
685    // Packages whose data we have transfered into another package, thus
686    // should no longer exist.
687    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
688
689    // Broadcast actions that are only available to the system.
690    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
691
692    /** List of packages waiting for verification. */
693    final SparseArray<PackageVerificationState> mPendingVerification
694            = new SparseArray<PackageVerificationState>();
695
696    /** Set of packages associated with each app op permission. */
697    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
698
699    final PackageInstallerService mInstallerService;
700
701    private final PackageDexOptimizer mPackageDexOptimizer;
702
703    private AtomicInteger mNextMoveId = new AtomicInteger();
704    private final MoveCallbacks mMoveCallbacks;
705
706    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
707
708    // Cache of users who need badging.
709    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
710
711    /** Token for keys in mPendingVerification. */
712    private int mPendingVerificationToken = 0;
713
714    volatile boolean mSystemReady;
715    volatile boolean mSafeMode;
716    volatile boolean mHasSystemUidErrors;
717
718    ApplicationInfo mAndroidApplication;
719    final ActivityInfo mResolveActivity = new ActivityInfo();
720    final ResolveInfo mResolveInfo = new ResolveInfo();
721    ComponentName mResolveComponentName;
722    PackageParser.Package mPlatformPackage;
723    ComponentName mCustomResolverComponentName;
724
725    boolean mResolverReplaced = false;
726
727    private final @Nullable ComponentName mIntentFilterVerifierComponent;
728    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
729
730    private int mIntentFilterVerificationToken = 0;
731
732    /** Component that knows whether or not an ephemeral application exists */
733    final ComponentName mEphemeralResolverComponent;
734    /** The service connection to the ephemeral resolver */
735    final EphemeralResolverConnection mEphemeralResolverConnection;
736
737    /** Component used to install ephemeral applications */
738    final ComponentName mEphemeralInstallerComponent;
739    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
740    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
741
742    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
743            = new SparseArray<IntentFilterVerificationState>();
744
745    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
746            new DefaultPermissionGrantPolicy(this);
747
748    // List of packages names to keep cached, even if they are uninstalled for all users
749    private List<String> mKeepUninstalledPackages;
750
751    private UserManagerInternal mUserManagerInternal;
752
753    private static class IFVerificationParams {
754        PackageParser.Package pkg;
755        boolean replacing;
756        int userId;
757        int verifierUid;
758
759        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
760                int _userId, int _verifierUid) {
761            pkg = _pkg;
762            replacing = _replacing;
763            userId = _userId;
764            replacing = _replacing;
765            verifierUid = _verifierUid;
766        }
767    }
768
769    private interface IntentFilterVerifier<T extends IntentFilter> {
770        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
771                                               T filter, String packageName);
772        void startVerifications(int userId);
773        void receiveVerificationResponse(int verificationId);
774    }
775
776    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
777        private Context mContext;
778        private ComponentName mIntentFilterVerifierComponent;
779        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
780
781        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
782            mContext = context;
783            mIntentFilterVerifierComponent = verifierComponent;
784        }
785
786        private String getDefaultScheme() {
787            return IntentFilter.SCHEME_HTTPS;
788        }
789
790        @Override
791        public void startVerifications(int userId) {
792            // Launch verifications requests
793            int count = mCurrentIntentFilterVerifications.size();
794            for (int n=0; n<count; n++) {
795                int verificationId = mCurrentIntentFilterVerifications.get(n);
796                final IntentFilterVerificationState ivs =
797                        mIntentFilterVerificationStates.get(verificationId);
798
799                String packageName = ivs.getPackageName();
800
801                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
802                final int filterCount = filters.size();
803                ArraySet<String> domainsSet = new ArraySet<>();
804                for (int m=0; m<filterCount; m++) {
805                    PackageParser.ActivityIntentInfo filter = filters.get(m);
806                    domainsSet.addAll(filter.getHostsList());
807                }
808                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
809                synchronized (mPackages) {
810                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
811                            packageName, domainsList) != null) {
812                        scheduleWriteSettingsLocked();
813                    }
814                }
815                sendVerificationRequest(userId, verificationId, ivs);
816            }
817            mCurrentIntentFilterVerifications.clear();
818        }
819
820        private void sendVerificationRequest(int userId, int verificationId,
821                IntentFilterVerificationState ivs) {
822
823            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
824            verificationIntent.putExtra(
825                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
826                    verificationId);
827            verificationIntent.putExtra(
828                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
829                    getDefaultScheme());
830            verificationIntent.putExtra(
831                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
832                    ivs.getHostsString());
833            verificationIntent.putExtra(
834                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
835                    ivs.getPackageName());
836            verificationIntent.setComponent(mIntentFilterVerifierComponent);
837            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
838
839            UserHandle user = new UserHandle(userId);
840            mContext.sendBroadcastAsUser(verificationIntent, user);
841            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
842                    "Sending IntentFilter verification broadcast");
843        }
844
845        public void receiveVerificationResponse(int verificationId) {
846            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
847
848            final boolean verified = ivs.isVerified();
849
850            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
851            final int count = filters.size();
852            if (DEBUG_DOMAIN_VERIFICATION) {
853                Slog.i(TAG, "Received verification response " + verificationId
854                        + " for " + count + " filters, verified=" + verified);
855            }
856            for (int n=0; n<count; n++) {
857                PackageParser.ActivityIntentInfo filter = filters.get(n);
858                filter.setVerified(verified);
859
860                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
861                        + " verified with result:" + verified + " and hosts:"
862                        + ivs.getHostsString());
863            }
864
865            mIntentFilterVerificationStates.remove(verificationId);
866
867            final String packageName = ivs.getPackageName();
868            IntentFilterVerificationInfo ivi = null;
869
870            synchronized (mPackages) {
871                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
872            }
873            if (ivi == null) {
874                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
875                        + verificationId + " packageName:" + packageName);
876                return;
877            }
878            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
879                    "Updating IntentFilterVerificationInfo for package " + packageName
880                            +" verificationId:" + verificationId);
881
882            synchronized (mPackages) {
883                if (verified) {
884                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
885                } else {
886                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
887                }
888                scheduleWriteSettingsLocked();
889
890                final int userId = ivs.getUserId();
891                if (userId != UserHandle.USER_ALL) {
892                    final int userStatus =
893                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
894
895                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
896                    boolean needUpdate = false;
897
898                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
899                    // already been set by the User thru the Disambiguation dialog
900                    switch (userStatus) {
901                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
902                            if (verified) {
903                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
904                            } else {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
906                            }
907                            needUpdate = true;
908                            break;
909
910                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
911                            if (verified) {
912                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
913                                needUpdate = true;
914                            }
915                            break;
916
917                        default:
918                            // Nothing to do
919                    }
920
921                    if (needUpdate) {
922                        mSettings.updateIntentFilterVerificationStatusLPw(
923                                packageName, updatedStatus, userId);
924                        scheduleWritePackageRestrictionsLocked(userId);
925                    }
926                }
927            }
928        }
929
930        @Override
931        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
932                    ActivityIntentInfo filter, String packageName) {
933            if (!hasValidDomains(filter)) {
934                return false;
935            }
936            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
937            if (ivs == null) {
938                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
939                        packageName);
940            }
941            if (DEBUG_DOMAIN_VERIFICATION) {
942                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
943            }
944            ivs.addFilter(filter);
945            return true;
946        }
947
948        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
949                int userId, int verificationId, String packageName) {
950            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
951                    verifierUid, userId, packageName);
952            ivs.setPendingState();
953            synchronized (mPackages) {
954                mIntentFilterVerificationStates.append(verificationId, ivs);
955                mCurrentIntentFilterVerifications.add(verificationId);
956            }
957            return ivs;
958        }
959    }
960
961    private static boolean hasValidDomains(ActivityIntentInfo filter) {
962        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
963                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
964                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
965    }
966
967    // Set of pending broadcasts for aggregating enable/disable of components.
968    static class PendingPackageBroadcasts {
969        // for each user id, a map of <package name -> components within that package>
970        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
971
972        public PendingPackageBroadcasts() {
973            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
974        }
975
976        public ArrayList<String> get(int userId, String packageName) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            return packages.get(packageName);
979        }
980
981        public void put(int userId, String packageName, ArrayList<String> components) {
982            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
983            packages.put(packageName, components);
984        }
985
986        public void remove(int userId, String packageName) {
987            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
988            if (packages != null) {
989                packages.remove(packageName);
990            }
991        }
992
993        public void remove(int userId) {
994            mUidMap.remove(userId);
995        }
996
997        public int userIdCount() {
998            return mUidMap.size();
999        }
1000
1001        public int userIdAt(int n) {
1002            return mUidMap.keyAt(n);
1003        }
1004
1005        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1006            return mUidMap.get(userId);
1007        }
1008
1009        public int size() {
1010            // total number of pending broadcast entries across all userIds
1011            int num = 0;
1012            for (int i = 0; i< mUidMap.size(); i++) {
1013                num += mUidMap.valueAt(i).size();
1014            }
1015            return num;
1016        }
1017
1018        public void clear() {
1019            mUidMap.clear();
1020        }
1021
1022        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1023            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1024            if (map == null) {
1025                map = new ArrayMap<String, ArrayList<String>>();
1026                mUidMap.put(userId, map);
1027            }
1028            return map;
1029        }
1030    }
1031    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1032
1033    // Service Connection to remote media container service to copy
1034    // package uri's from external media onto secure containers
1035    // or internal storage.
1036    private IMediaContainerService mContainerService = null;
1037
1038    static final int SEND_PENDING_BROADCAST = 1;
1039    static final int MCS_BOUND = 3;
1040    static final int END_COPY = 4;
1041    static final int INIT_COPY = 5;
1042    static final int MCS_UNBIND = 6;
1043    static final int START_CLEANING_PACKAGE = 7;
1044    static final int FIND_INSTALL_LOC = 8;
1045    static final int POST_INSTALL = 9;
1046    static final int MCS_RECONNECT = 10;
1047    static final int MCS_GIVE_UP = 11;
1048    static final int UPDATED_MEDIA_STATUS = 12;
1049    static final int WRITE_SETTINGS = 13;
1050    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1051    static final int PACKAGE_VERIFIED = 15;
1052    static final int CHECK_PENDING_VERIFICATION = 16;
1053    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1054    static final int INTENT_FILTER_VERIFIED = 18;
1055    static final int WRITE_PACKAGE_LIST = 19;
1056
1057    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1058
1059    // Delay time in millisecs
1060    static final int BROADCAST_DELAY = 10 * 1000;
1061
1062    static UserManagerService sUserManager;
1063
1064    // Stores a list of users whose package restrictions file needs to be updated
1065    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1066
1067    final private DefaultContainerConnection mDefContainerConn =
1068            new DefaultContainerConnection();
1069    class DefaultContainerConnection implements ServiceConnection {
1070        public void onServiceConnected(ComponentName name, IBinder service) {
1071            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1072            IMediaContainerService imcs =
1073                IMediaContainerService.Stub.asInterface(service);
1074            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1075        }
1076
1077        public void onServiceDisconnected(ComponentName name) {
1078            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1079        }
1080    }
1081
1082    // Recordkeeping of restore-after-install operations that are currently in flight
1083    // between the Package Manager and the Backup Manager
1084    static class PostInstallData {
1085        public InstallArgs args;
1086        public PackageInstalledInfo res;
1087
1088        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1089            args = _a;
1090            res = _r;
1091        }
1092    }
1093
1094    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1095    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1096
1097    // XML tags for backup/restore of various bits of state
1098    private static final String TAG_PREFERRED_BACKUP = "pa";
1099    private static final String TAG_DEFAULT_APPS = "da";
1100    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1101
1102    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1103    private static final String TAG_ALL_GRANTS = "rt-grants";
1104    private static final String TAG_GRANT = "grant";
1105    private static final String ATTR_PACKAGE_NAME = "pkg";
1106
1107    private static final String TAG_PERMISSION = "perm";
1108    private static final String ATTR_PERMISSION_NAME = "name";
1109    private static final String ATTR_IS_GRANTED = "g";
1110    private static final String ATTR_USER_SET = "set";
1111    private static final String ATTR_USER_FIXED = "fixed";
1112    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1113
1114    // System/policy permission grants are not backed up
1115    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1116            FLAG_PERMISSION_POLICY_FIXED
1117            | FLAG_PERMISSION_SYSTEM_FIXED
1118            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1119
1120    // And we back up these user-adjusted states
1121    private static final int USER_RUNTIME_GRANT_MASK =
1122            FLAG_PERMISSION_USER_SET
1123            | FLAG_PERMISSION_USER_FIXED
1124            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1125
1126    final @Nullable String mRequiredVerifierPackage;
1127    final @NonNull String mRequiredInstallerPackage;
1128    final @Nullable String mSetupWizardPackage;
1129    final @NonNull String mServicesSystemSharedLibraryPackageName;
1130    final @NonNull String mSharedSystemSharedLibraryPackageName;
1131
1132    private final PackageUsage mPackageUsage = new PackageUsage();
1133
1134    private class PackageUsage {
1135        private static final int WRITE_INTERVAL
1136            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1137
1138        private final Object mFileLock = new Object();
1139        private final AtomicLong mLastWritten = new AtomicLong(0);
1140        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1141
1142        private boolean mIsHistoricalPackageUsageAvailable = true;
1143
1144        boolean isHistoricalPackageUsageAvailable() {
1145            return mIsHistoricalPackageUsageAvailable;
1146        }
1147
1148        void write(boolean force) {
1149            if (force) {
1150                writeInternal();
1151                return;
1152            }
1153            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1154                && !DEBUG_DEXOPT) {
1155                return;
1156            }
1157            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1158                new Thread("PackageUsage_DiskWriter") {
1159                    @Override
1160                    public void run() {
1161                        try {
1162                            writeInternal();
1163                        } finally {
1164                            mBackgroundWriteRunning.set(false);
1165                        }
1166                    }
1167                }.start();
1168            }
1169        }
1170
1171        private void writeInternal() {
1172            synchronized (mPackages) {
1173                synchronized (mFileLock) {
1174                    AtomicFile file = getFile();
1175                    FileOutputStream f = null;
1176                    try {
1177                        f = file.startWrite();
1178                        BufferedOutputStream out = new BufferedOutputStream(f);
1179                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1180                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1181                        StringBuilder sb = new StringBuilder();
1182
1183                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1184                        sb.append('\n');
1185                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1186
1187                        for (PackageParser.Package pkg : mPackages.values()) {
1188                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1189                                continue;
1190                            }
1191                            sb.setLength(0);
1192                            sb.append(pkg.packageName);
1193                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1194                                sb.append(' ');
1195                                sb.append(usageTimeInMillis);
1196                            }
1197                            sb.append('\n');
1198                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1199                        }
1200                        out.flush();
1201                        file.finishWrite(f);
1202                    } catch (IOException e) {
1203                        if (f != null) {
1204                            file.failWrite(f);
1205                        }
1206                        Log.e(TAG, "Failed to write package usage times", e);
1207                    }
1208                }
1209            }
1210            mLastWritten.set(SystemClock.elapsedRealtime());
1211        }
1212
1213        void readLP() {
1214            synchronized (mFileLock) {
1215                AtomicFile file = getFile();
1216                BufferedInputStream in = null;
1217                try {
1218                    in = new BufferedInputStream(file.openRead());
1219                    StringBuffer sb = new StringBuffer();
1220
1221                    String firstLine = readLine(in, sb);
1222                    if (firstLine == null) {
1223                        // Empty file. Do nothing.
1224                    } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) {
1225                        readVersion1LP(in, sb);
1226                    } else {
1227                        readVersion0LP(in, sb, firstLine);
1228                    }
1229                } catch (FileNotFoundException expected) {
1230                    mIsHistoricalPackageUsageAvailable = false;
1231                } catch (IOException e) {
1232                    Log.w(TAG, "Failed to read package usage times", e);
1233                } finally {
1234                    IoUtils.closeQuietly(in);
1235                }
1236            }
1237            mLastWritten.set(SystemClock.elapsedRealtime());
1238        }
1239
1240        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1241                throws IOException {
1242            // Initial version of the file had no version number and stored one
1243            // package-timestamp pair per line.
1244            // Note that the first line has already been read from the InputStream.
1245            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1246                String[] tokens = line.split(" ");
1247                if (tokens.length != 2) {
1248                    throw new IOException("Failed to parse " + line +
1249                            " as package-timestamp pair.");
1250                }
1251
1252                String packageName = tokens[0];
1253                PackageParser.Package pkg = mPackages.get(packageName);
1254                if (pkg == null) {
1255                    continue;
1256                }
1257
1258                long timestamp = parseAsLong(tokens[1]);
1259                for (int reason = 0;
1260                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1261                        reason++) {
1262                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1263                }
1264            }
1265        }
1266
1267        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1268            // Version 1 of the file started with the corresponding version
1269            // number and then stored a package name and eight timestamps per line.
1270            String line;
1271            while ((line = readLine(in, sb)) != null) {
1272                String[] tokens = line.split(" ");
1273                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1274                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1275                }
1276
1277                String packageName = tokens[0];
1278                PackageParser.Package pkg = mPackages.get(packageName);
1279                if (pkg == null) {
1280                    continue;
1281                }
1282
1283                for (int reason = 0;
1284                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1285                        reason++) {
1286                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1287                }
1288            }
1289        }
1290
1291        private long parseAsLong(String token) throws IOException {
1292            try {
1293                return Long.parseLong(token);
1294            } catch (NumberFormatException e) {
1295                throw new IOException("Failed to parse " + token + " as a long.", e);
1296            }
1297        }
1298
1299        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1300            return readToken(in, sb, '\n');
1301        }
1302
1303        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1304                throws IOException {
1305            sb.setLength(0);
1306            while (true) {
1307                int ch = in.read();
1308                if (ch == -1) {
1309                    if (sb.length() == 0) {
1310                        return null;
1311                    }
1312                    throw new IOException("Unexpected EOF");
1313                }
1314                if (ch == endOfToken) {
1315                    return sb.toString();
1316                }
1317                sb.append((char)ch);
1318            }
1319        }
1320
1321        private AtomicFile getFile() {
1322            File dataDir = Environment.getDataDirectory();
1323            File systemDir = new File(dataDir, "system");
1324            File fname = new File(systemDir, "package-usage.list");
1325            return new AtomicFile(fname);
1326        }
1327
1328        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1329        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1330    }
1331
1332    class PackageHandler extends Handler {
1333        private boolean mBound = false;
1334        final ArrayList<HandlerParams> mPendingInstalls =
1335            new ArrayList<HandlerParams>();
1336
1337        private boolean connectToService() {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1339                    " DefaultContainerService");
1340            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1341            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1342            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1343                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1344                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1345                mBound = true;
1346                return true;
1347            }
1348            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1349            return false;
1350        }
1351
1352        private void disconnectService() {
1353            mContainerService = null;
1354            mBound = false;
1355            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1356            mContext.unbindService(mDefContainerConn);
1357            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1358        }
1359
1360        PackageHandler(Looper looper) {
1361            super(looper);
1362        }
1363
1364        public void handleMessage(Message msg) {
1365            try {
1366                doHandleMessage(msg);
1367            } finally {
1368                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1369            }
1370        }
1371
1372        void doHandleMessage(Message msg) {
1373            switch (msg.what) {
1374                case INIT_COPY: {
1375                    HandlerParams params = (HandlerParams) msg.obj;
1376                    int idx = mPendingInstalls.size();
1377                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1378                    // If a bind was already initiated we dont really
1379                    // need to do anything. The pending install
1380                    // will be processed later on.
1381                    if (!mBound) {
1382                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1383                                System.identityHashCode(mHandler));
1384                        // If this is the only one pending we might
1385                        // have to bind to the service again.
1386                        if (!connectToService()) {
1387                            Slog.e(TAG, "Failed to bind to media container service");
1388                            params.serviceError();
1389                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1390                                    System.identityHashCode(mHandler));
1391                            if (params.traceMethod != null) {
1392                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1393                                        params.traceCookie);
1394                            }
1395                            return;
1396                        } else {
1397                            // Once we bind to the service, the first
1398                            // pending request will be processed.
1399                            mPendingInstalls.add(idx, params);
1400                        }
1401                    } else {
1402                        mPendingInstalls.add(idx, params);
1403                        // Already bound to the service. Just make
1404                        // sure we trigger off processing the first request.
1405                        if (idx == 0) {
1406                            mHandler.sendEmptyMessage(MCS_BOUND);
1407                        }
1408                    }
1409                    break;
1410                }
1411                case MCS_BOUND: {
1412                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1413                    if (msg.obj != null) {
1414                        mContainerService = (IMediaContainerService) msg.obj;
1415                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1416                                System.identityHashCode(mHandler));
1417                    }
1418                    if (mContainerService == null) {
1419                        if (!mBound) {
1420                            // Something seriously wrong since we are not bound and we are not
1421                            // waiting for connection. Bail out.
1422                            Slog.e(TAG, "Cannot bind to media container service");
1423                            for (HandlerParams params : mPendingInstalls) {
1424                                // Indicate service bind error
1425                                params.serviceError();
1426                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1427                                        System.identityHashCode(params));
1428                                if (params.traceMethod != null) {
1429                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1430                                            params.traceMethod, params.traceCookie);
1431                                }
1432                                return;
1433                            }
1434                            mPendingInstalls.clear();
1435                        } else {
1436                            Slog.w(TAG, "Waiting to connect to media container service");
1437                        }
1438                    } else if (mPendingInstalls.size() > 0) {
1439                        HandlerParams params = mPendingInstalls.get(0);
1440                        if (params != null) {
1441                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1442                                    System.identityHashCode(params));
1443                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1444                            if (params.startCopy()) {
1445                                // We are done...  look for more work or to
1446                                // go idle.
1447                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1448                                        "Checking for more work or unbind...");
1449                                // Delete pending install
1450                                if (mPendingInstalls.size() > 0) {
1451                                    mPendingInstalls.remove(0);
1452                                }
1453                                if (mPendingInstalls.size() == 0) {
1454                                    if (mBound) {
1455                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1456                                                "Posting delayed MCS_UNBIND");
1457                                        removeMessages(MCS_UNBIND);
1458                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1459                                        // Unbind after a little delay, to avoid
1460                                        // continual thrashing.
1461                                        sendMessageDelayed(ubmsg, 10000);
1462                                    }
1463                                } else {
1464                                    // There are more pending requests in queue.
1465                                    // Just post MCS_BOUND message to trigger processing
1466                                    // of next pending install.
1467                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1468                                            "Posting MCS_BOUND for next work");
1469                                    mHandler.sendEmptyMessage(MCS_BOUND);
1470                                }
1471                            }
1472                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1473                        }
1474                    } else {
1475                        // Should never happen ideally.
1476                        Slog.w(TAG, "Empty queue");
1477                    }
1478                    break;
1479                }
1480                case MCS_RECONNECT: {
1481                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1482                    if (mPendingInstalls.size() > 0) {
1483                        if (mBound) {
1484                            disconnectService();
1485                        }
1486                        if (!connectToService()) {
1487                            Slog.e(TAG, "Failed to bind to media container service");
1488                            for (HandlerParams params : mPendingInstalls) {
1489                                // Indicate service bind error
1490                                params.serviceError();
1491                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1492                                        System.identityHashCode(params));
1493                            }
1494                            mPendingInstalls.clear();
1495                        }
1496                    }
1497                    break;
1498                }
1499                case MCS_UNBIND: {
1500                    // If there is no actual work left, then time to unbind.
1501                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1502
1503                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1504                        if (mBound) {
1505                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1506
1507                            disconnectService();
1508                        }
1509                    } else if (mPendingInstalls.size() > 0) {
1510                        // There are more pending requests in queue.
1511                        // Just post MCS_BOUND message to trigger processing
1512                        // of next pending install.
1513                        mHandler.sendEmptyMessage(MCS_BOUND);
1514                    }
1515
1516                    break;
1517                }
1518                case MCS_GIVE_UP: {
1519                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1520                    HandlerParams params = mPendingInstalls.remove(0);
1521                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                            System.identityHashCode(params));
1523                    break;
1524                }
1525                case SEND_PENDING_BROADCAST: {
1526                    String packages[];
1527                    ArrayList<String> components[];
1528                    int size = 0;
1529                    int uids[];
1530                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1531                    synchronized (mPackages) {
1532                        if (mPendingBroadcasts == null) {
1533                            return;
1534                        }
1535                        size = mPendingBroadcasts.size();
1536                        if (size <= 0) {
1537                            // Nothing to be done. Just return
1538                            return;
1539                        }
1540                        packages = new String[size];
1541                        components = new ArrayList[size];
1542                        uids = new int[size];
1543                        int i = 0;  // filling out the above arrays
1544
1545                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1546                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1547                            Iterator<Map.Entry<String, ArrayList<String>>> it
1548                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1549                                            .entrySet().iterator();
1550                            while (it.hasNext() && i < size) {
1551                                Map.Entry<String, ArrayList<String>> ent = it.next();
1552                                packages[i] = ent.getKey();
1553                                components[i] = ent.getValue();
1554                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1555                                uids[i] = (ps != null)
1556                                        ? UserHandle.getUid(packageUserId, ps.appId)
1557                                        : -1;
1558                                i++;
1559                            }
1560                        }
1561                        size = i;
1562                        mPendingBroadcasts.clear();
1563                    }
1564                    // Send broadcasts
1565                    for (int i = 0; i < size; i++) {
1566                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1567                    }
1568                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1569                    break;
1570                }
1571                case START_CLEANING_PACKAGE: {
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1573                    final String packageName = (String)msg.obj;
1574                    final int userId = msg.arg1;
1575                    final boolean andCode = msg.arg2 != 0;
1576                    synchronized (mPackages) {
1577                        if (userId == UserHandle.USER_ALL) {
1578                            int[] users = sUserManager.getUserIds();
1579                            for (int user : users) {
1580                                mSettings.addPackageToCleanLPw(
1581                                        new PackageCleanItem(user, packageName, andCode));
1582                            }
1583                        } else {
1584                            mSettings.addPackageToCleanLPw(
1585                                    new PackageCleanItem(userId, packageName, andCode));
1586                        }
1587                    }
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589                    startCleaningPackages();
1590                } break;
1591                case POST_INSTALL: {
1592                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1593
1594                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1595                    final boolean didRestore = (msg.arg2 != 0);
1596                    mRunningInstalls.delete(msg.arg1);
1597
1598                    if (data != null) {
1599                        InstallArgs args = data.args;
1600                        PackageInstalledInfo parentRes = data.res;
1601
1602                        final boolean grantPermissions = (args.installFlags
1603                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1604                        final boolean killApp = (args.installFlags
1605                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1606                        final String[] grantedPermissions = args.installGrantPermissions;
1607
1608                        // Handle the parent package
1609                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1610                                grantedPermissions, didRestore, args.installerPackageName,
1611                                args.observer);
1612
1613                        // Handle the child packages
1614                        final int childCount = (parentRes.addedChildPackages != null)
1615                                ? parentRes.addedChildPackages.size() : 0;
1616                        for (int i = 0; i < childCount; i++) {
1617                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1618                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1619                                    grantedPermissions, false, args.installerPackageName,
1620                                    args.observer);
1621                        }
1622
1623                        // Log tracing if needed
1624                        if (args.traceMethod != null) {
1625                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1626                                    args.traceCookie);
1627                        }
1628                    } else {
1629                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1630                    }
1631
1632                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1633                } break;
1634                case UPDATED_MEDIA_STATUS: {
1635                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1636                    boolean reportStatus = msg.arg1 == 1;
1637                    boolean doGc = msg.arg2 == 1;
1638                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1639                    if (doGc) {
1640                        // Force a gc to clear up stale containers.
1641                        Runtime.getRuntime().gc();
1642                    }
1643                    if (msg.obj != null) {
1644                        @SuppressWarnings("unchecked")
1645                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1646                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1647                        // Unload containers
1648                        unloadAllContainers(args);
1649                    }
1650                    if (reportStatus) {
1651                        try {
1652                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1653                            PackageHelper.getMountService().finishMediaUpdate();
1654                        } catch (RemoteException e) {
1655                            Log.e(TAG, "MountService not running?");
1656                        }
1657                    }
1658                } break;
1659                case WRITE_SETTINGS: {
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1661                    synchronized (mPackages) {
1662                        removeMessages(WRITE_SETTINGS);
1663                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1664                        mSettings.writeLPr();
1665                        mDirtyUsers.clear();
1666                    }
1667                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1668                } break;
1669                case WRITE_PACKAGE_RESTRICTIONS: {
1670                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1671                    synchronized (mPackages) {
1672                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1673                        for (int userId : mDirtyUsers) {
1674                            mSettings.writePackageRestrictionsLPr(userId);
1675                        }
1676                        mDirtyUsers.clear();
1677                    }
1678                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1679                } break;
1680                case WRITE_PACKAGE_LIST: {
1681                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1682                    synchronized (mPackages) {
1683                        removeMessages(WRITE_PACKAGE_LIST);
1684                        mSettings.writePackageListLPr(msg.arg1);
1685                    }
1686                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1687                } break;
1688                case CHECK_PENDING_VERIFICATION: {
1689                    final int verificationId = msg.arg1;
1690                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1691
1692                    if ((state != null) && !state.timeoutExtended()) {
1693                        final InstallArgs args = state.getInstallArgs();
1694                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1695
1696                        Slog.i(TAG, "Verification timed out for " + originUri);
1697                        mPendingVerification.remove(verificationId);
1698
1699                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1700
1701                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1702                            Slog.i(TAG, "Continuing with installation of " + originUri);
1703                            state.setVerifierResponse(Binder.getCallingUid(),
1704                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1705                            broadcastPackageVerified(verificationId, originUri,
1706                                    PackageManager.VERIFICATION_ALLOW,
1707                                    state.getInstallArgs().getUser());
1708                            try {
1709                                ret = args.copyApk(mContainerService, true);
1710                            } catch (RemoteException e) {
1711                                Slog.e(TAG, "Could not contact the ContainerService");
1712                            }
1713                        } else {
1714                            broadcastPackageVerified(verificationId, originUri,
1715                                    PackageManager.VERIFICATION_REJECT,
1716                                    state.getInstallArgs().getUser());
1717                        }
1718
1719                        Trace.asyncTraceEnd(
1720                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1721
1722                        processPendingInstall(args, ret);
1723                        mHandler.sendEmptyMessage(MCS_UNBIND);
1724                    }
1725                    break;
1726                }
1727                case PACKAGE_VERIFIED: {
1728                    final int verificationId = msg.arg1;
1729
1730                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1731                    if (state == null) {
1732                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1733                        break;
1734                    }
1735
1736                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1737
1738                    state.setVerifierResponse(response.callerUid, response.code);
1739
1740                    if (state.isVerificationComplete()) {
1741                        mPendingVerification.remove(verificationId);
1742
1743                        final InstallArgs args = state.getInstallArgs();
1744                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1745
1746                        int ret;
1747                        if (state.isInstallAllowed()) {
1748                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1749                            broadcastPackageVerified(verificationId, originUri,
1750                                    response.code, state.getInstallArgs().getUser());
1751                            try {
1752                                ret = args.copyApk(mContainerService, true);
1753                            } catch (RemoteException e) {
1754                                Slog.e(TAG, "Could not contact the ContainerService");
1755                            }
1756                        } else {
1757                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1758                        }
1759
1760                        Trace.asyncTraceEnd(
1761                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1762
1763                        processPendingInstall(args, ret);
1764                        mHandler.sendEmptyMessage(MCS_UNBIND);
1765                    }
1766
1767                    break;
1768                }
1769                case START_INTENT_FILTER_VERIFICATIONS: {
1770                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1771                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1772                            params.replacing, params.pkg);
1773                    break;
1774                }
1775                case INTENT_FILTER_VERIFIED: {
1776                    final int verificationId = msg.arg1;
1777
1778                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1779                            verificationId);
1780                    if (state == null) {
1781                        Slog.w(TAG, "Invalid IntentFilter verification token "
1782                                + verificationId + " received");
1783                        break;
1784                    }
1785
1786                    final int userId = state.getUserId();
1787
1788                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1789                            "Processing IntentFilter verification with token:"
1790                            + verificationId + " and userId:" + userId);
1791
1792                    final IntentFilterVerificationResponse response =
1793                            (IntentFilterVerificationResponse) msg.obj;
1794
1795                    state.setVerifierResponse(response.callerUid, response.code);
1796
1797                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1798                            "IntentFilter verification with token:" + verificationId
1799                            + " and userId:" + userId
1800                            + " is settings verifier response with response code:"
1801                            + response.code);
1802
1803                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1804                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1805                                + response.getFailedDomainsString());
1806                    }
1807
1808                    if (state.isVerificationComplete()) {
1809                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1810                    } else {
1811                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1812                                "IntentFilter verification with token:" + verificationId
1813                                + " was not said to be complete");
1814                    }
1815
1816                    break;
1817                }
1818            }
1819        }
1820    }
1821
1822    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1823            boolean killApp, String[] grantedPermissions,
1824            boolean launchedForRestore, String installerPackage,
1825            IPackageInstallObserver2 installObserver) {
1826        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1827            // Send the removed broadcasts
1828            if (res.removedInfo != null) {
1829                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1830            }
1831
1832            // Now that we successfully installed the package, grant runtime
1833            // permissions if requested before broadcasting the install.
1834            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1835                    >= Build.VERSION_CODES.M) {
1836                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1837            }
1838
1839            final boolean update = res.removedInfo != null
1840                    && res.removedInfo.removedPackage != null;
1841
1842            // If this is the first time we have child packages for a disabled privileged
1843            // app that had no children, we grant requested runtime permissions to the new
1844            // children if the parent on the system image had them already granted.
1845            if (res.pkg.parentPackage != null) {
1846                synchronized (mPackages) {
1847                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1848                }
1849            }
1850
1851            synchronized (mPackages) {
1852                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1853            }
1854
1855            final String packageName = res.pkg.applicationInfo.packageName;
1856            Bundle extras = new Bundle(1);
1857            extras.putInt(Intent.EXTRA_UID, res.uid);
1858
1859            // Determine the set of users who are adding this package for
1860            // the first time vs. those who are seeing an update.
1861            int[] firstUsers = EMPTY_INT_ARRAY;
1862            int[] updateUsers = EMPTY_INT_ARRAY;
1863            if (res.origUsers == null || res.origUsers.length == 0) {
1864                firstUsers = res.newUsers;
1865            } else {
1866                for (int newUser : res.newUsers) {
1867                    boolean isNew = true;
1868                    for (int origUser : res.origUsers) {
1869                        if (origUser == newUser) {
1870                            isNew = false;
1871                            break;
1872                        }
1873                    }
1874                    if (isNew) {
1875                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1876                    } else {
1877                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1878                    }
1879                }
1880            }
1881
1882            // Send installed broadcasts if the install/update is not ephemeral
1883            if (!isEphemeral(res.pkg)) {
1884                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1885
1886                // Send added for users that see the package for the first time
1887                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1888                        extras, 0 /*flags*/, null /*targetPackage*/,
1889                        null /*finishedReceiver*/, firstUsers);
1890
1891                // Send added for users that don't see the package for the first time
1892                if (update) {
1893                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1894                }
1895                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1896                        extras, 0 /*flags*/, null /*targetPackage*/,
1897                        null /*finishedReceiver*/, updateUsers);
1898
1899                // Send replaced for users that don't see the package for the first time
1900                if (update) {
1901                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1902                            packageName, extras, 0 /*flags*/,
1903                            null /*targetPackage*/, null /*finishedReceiver*/,
1904                            updateUsers);
1905                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1906                            null /*package*/, null /*extras*/, 0 /*flags*/,
1907                            packageName /*targetPackage*/,
1908                            null /*finishedReceiver*/, updateUsers);
1909                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1910                    // First-install and we did a restore, so we're responsible for the
1911                    // first-launch broadcast.
1912                    if (DEBUG_BACKUP) {
1913                        Slog.i(TAG, "Post-restore of " + packageName
1914                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1915                    }
1916                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1917                }
1918
1919                // Send broadcast package appeared if forward locked/external for all users
1920                // treat asec-hosted packages like removable media on upgrade
1921                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1922                    if (DEBUG_INSTALL) {
1923                        Slog.i(TAG, "upgrading pkg " + res.pkg
1924                                + " is ASEC-hosted -> AVAILABLE");
1925                    }
1926                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1927                    ArrayList<String> pkgList = new ArrayList<>(1);
1928                    pkgList.add(packageName);
1929                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1930                }
1931            }
1932
1933            // Work that needs to happen on first install within each user
1934            if (firstUsers != null && firstUsers.length > 0) {
1935                synchronized (mPackages) {
1936                    for (int userId : firstUsers) {
1937                        // If this app is a browser and it's newly-installed for some
1938                        // users, clear any default-browser state in those users. The
1939                        // app's nature doesn't depend on the user, so we can just check
1940                        // its browser nature in any user and generalize.
1941                        if (packageIsBrowser(packageName, userId)) {
1942                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1943                        }
1944
1945                        // We may also need to apply pending (restored) runtime
1946                        // permission grants within these users.
1947                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1948                    }
1949                }
1950            }
1951
1952            // Log current value of "unknown sources" setting
1953            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1954                    getUnknownSourcesSettings());
1955
1956            // Force a gc to clear up things
1957            Runtime.getRuntime().gc();
1958
1959            // Remove the replaced package's older resources safely now
1960            // We delete after a gc for applications  on sdcard.
1961            if (res.removedInfo != null && res.removedInfo.args != null) {
1962                synchronized (mInstallLock) {
1963                    res.removedInfo.args.doPostDeleteLI(true);
1964                }
1965            }
1966        }
1967
1968        // If someone is watching installs - notify them
1969        if (installObserver != null) {
1970            try {
1971                Bundle extras = extrasForInstallResult(res);
1972                installObserver.onPackageInstalled(res.name, res.returnCode,
1973                        res.returnMsg, extras);
1974            } catch (RemoteException e) {
1975                Slog.i(TAG, "Observer no longer exists.");
1976            }
1977        }
1978    }
1979
1980    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1981            PackageParser.Package pkg) {
1982        if (pkg.parentPackage == null) {
1983            return;
1984        }
1985        if (pkg.requestedPermissions == null) {
1986            return;
1987        }
1988        final PackageSetting disabledSysParentPs = mSettings
1989                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1990        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1991                || !disabledSysParentPs.isPrivileged()
1992                || (disabledSysParentPs.childPackageNames != null
1993                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1994            return;
1995        }
1996        final int[] allUserIds = sUserManager.getUserIds();
1997        final int permCount = pkg.requestedPermissions.size();
1998        for (int i = 0; i < permCount; i++) {
1999            String permission = pkg.requestedPermissions.get(i);
2000            BasePermission bp = mSettings.mPermissions.get(permission);
2001            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2002                continue;
2003            }
2004            for (int userId : allUserIds) {
2005                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2006                        permission, userId)) {
2007                    grantRuntimePermission(pkg.packageName, permission, userId);
2008                }
2009            }
2010        }
2011    }
2012
2013    private StorageEventListener mStorageListener = new StorageEventListener() {
2014        @Override
2015        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2016            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2017                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2018                    final String volumeUuid = vol.getFsUuid();
2019
2020                    // Clean up any users or apps that were removed or recreated
2021                    // while this volume was missing
2022                    reconcileUsers(volumeUuid);
2023                    reconcileApps(volumeUuid);
2024
2025                    // Clean up any install sessions that expired or were
2026                    // cancelled while this volume was missing
2027                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2028
2029                    loadPrivatePackages(vol);
2030
2031                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2032                    unloadPrivatePackages(vol);
2033                }
2034            }
2035
2036            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2037                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2038                    updateExternalMediaStatus(true, false);
2039                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2040                    updateExternalMediaStatus(false, false);
2041                }
2042            }
2043        }
2044
2045        @Override
2046        public void onVolumeForgotten(String fsUuid) {
2047            if (TextUtils.isEmpty(fsUuid)) {
2048                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2049                return;
2050            }
2051
2052            // Remove any apps installed on the forgotten volume
2053            synchronized (mPackages) {
2054                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2055                for (PackageSetting ps : packages) {
2056                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2057                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2058                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2059                }
2060
2061                mSettings.onVolumeForgotten(fsUuid);
2062                mSettings.writeLPr();
2063            }
2064        }
2065    };
2066
2067    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2068            String[] grantedPermissions) {
2069        for (int userId : userIds) {
2070            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2071        }
2072
2073        // We could have touched GID membership, so flush out packages.list
2074        synchronized (mPackages) {
2075            mSettings.writePackageListLPr();
2076        }
2077    }
2078
2079    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2080            String[] grantedPermissions) {
2081        SettingBase sb = (SettingBase) pkg.mExtras;
2082        if (sb == null) {
2083            return;
2084        }
2085
2086        PermissionsState permissionsState = sb.getPermissionsState();
2087
2088        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2089                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2090
2091        for (String permission : pkg.requestedPermissions) {
2092            final BasePermission bp;
2093            synchronized (mPackages) {
2094                bp = mSettings.mPermissions.get(permission);
2095            }
2096            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2097                    && (grantedPermissions == null
2098                           || ArrayUtils.contains(grantedPermissions, permission))) {
2099                final int flags = permissionsState.getPermissionFlags(permission, userId);
2100                // Installer cannot change immutable permissions.
2101                if ((flags & immutableFlags) == 0) {
2102                    grantRuntimePermission(pkg.packageName, permission, userId);
2103                }
2104            }
2105        }
2106    }
2107
2108    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2109        Bundle extras = null;
2110        switch (res.returnCode) {
2111            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2112                extras = new Bundle();
2113                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2114                        res.origPermission);
2115                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2116                        res.origPackage);
2117                break;
2118            }
2119            case PackageManager.INSTALL_SUCCEEDED: {
2120                extras = new Bundle();
2121                extras.putBoolean(Intent.EXTRA_REPLACING,
2122                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2123                break;
2124            }
2125        }
2126        return extras;
2127    }
2128
2129    void scheduleWriteSettingsLocked() {
2130        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2131            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2132        }
2133    }
2134
2135    void scheduleWritePackageListLocked(int userId) {
2136        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2137            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2138            msg.arg1 = userId;
2139            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2140        }
2141    }
2142
2143    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2144        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2145        scheduleWritePackageRestrictionsLocked(userId);
2146    }
2147
2148    void scheduleWritePackageRestrictionsLocked(int userId) {
2149        final int[] userIds = (userId == UserHandle.USER_ALL)
2150                ? sUserManager.getUserIds() : new int[]{userId};
2151        for (int nextUserId : userIds) {
2152            if (!sUserManager.exists(nextUserId)) return;
2153            mDirtyUsers.add(nextUserId);
2154            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2155                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2156            }
2157        }
2158    }
2159
2160    public static PackageManagerService main(Context context, Installer installer,
2161            boolean factoryTest, boolean onlyCore) {
2162        // Self-check for initial settings.
2163        PackageManagerServiceCompilerMapping.checkProperties();
2164
2165        PackageManagerService m = new PackageManagerService(context, installer,
2166                factoryTest, onlyCore);
2167        m.enableSystemUserPackages();
2168        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2169        // disabled after already being started.
2170        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2171                UserHandle.USER_SYSTEM);
2172        ServiceManager.addService("package", m);
2173        return m;
2174    }
2175
2176    private void enableSystemUserPackages() {
2177        if (!UserManager.isSplitSystemUser()) {
2178            return;
2179        }
2180        // For system user, enable apps based on the following conditions:
2181        // - app is whitelisted or belong to one of these groups:
2182        //   -- system app which has no launcher icons
2183        //   -- system app which has INTERACT_ACROSS_USERS permission
2184        //   -- system IME app
2185        // - app is not in the blacklist
2186        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2187        Set<String> enableApps = new ArraySet<>();
2188        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2189                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2190                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2191        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2192        enableApps.addAll(wlApps);
2193        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2194                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2195        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2196        enableApps.removeAll(blApps);
2197        Log.i(TAG, "Applications installed for system user: " + enableApps);
2198        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2199                UserHandle.SYSTEM);
2200        final int allAppsSize = allAps.size();
2201        synchronized (mPackages) {
2202            for (int i = 0; i < allAppsSize; i++) {
2203                String pName = allAps.get(i);
2204                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2205                // Should not happen, but we shouldn't be failing if it does
2206                if (pkgSetting == null) {
2207                    continue;
2208                }
2209                boolean install = enableApps.contains(pName);
2210                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2211                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2212                            + " for system user");
2213                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2214                }
2215            }
2216        }
2217    }
2218
2219    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2220        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2221                Context.DISPLAY_SERVICE);
2222        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2223    }
2224
2225    /**
2226     * Requests that files preopted on a secondary system partition be copied to the data partition
2227     * if possible.  Note that the actual copying of the files is accomplished by init for security
2228     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2229     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2230     */
2231    private static void requestCopyPreoptedFiles() {
2232        final int WAIT_TIME_MS = 100;
2233        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2234        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2235            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2236            // We will wait for up to 100 seconds.
2237            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2238            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2239                try {
2240                    Thread.sleep(WAIT_TIME_MS);
2241                } catch (InterruptedException e) {
2242                    // Do nothing
2243                }
2244                if (SystemClock.uptimeMillis() > timeEnd) {
2245                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2246                    Slog.wtf(TAG, "cppreopt did not finish!");
2247                    break;
2248                }
2249            }
2250        }
2251    }
2252
2253    public PackageManagerService(Context context, Installer installer,
2254            boolean factoryTest, boolean onlyCore) {
2255        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2256                SystemClock.uptimeMillis());
2257
2258        if (mSdkVersion <= 0) {
2259            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2260        }
2261
2262        mContext = context;
2263        mFactoryTest = factoryTest;
2264        mOnlyCore = onlyCore;
2265        mMetrics = new DisplayMetrics();
2266        mSettings = new Settings(mPackages);
2267        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2268                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2269        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2270                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2271        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2272                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2273        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2274                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2275        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2276                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2277        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2278                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2279
2280        String separateProcesses = SystemProperties.get("debug.separate_processes");
2281        if (separateProcesses != null && separateProcesses.length() > 0) {
2282            if ("*".equals(separateProcesses)) {
2283                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2284                mSeparateProcesses = null;
2285                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2286            } else {
2287                mDefParseFlags = 0;
2288                mSeparateProcesses = separateProcesses.split(",");
2289                Slog.w(TAG, "Running with debug.separate_processes: "
2290                        + separateProcesses);
2291            }
2292        } else {
2293            mDefParseFlags = 0;
2294            mSeparateProcesses = null;
2295        }
2296
2297        mInstaller = installer;
2298        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2299                "*dexopt*");
2300        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2301
2302        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2303                FgThread.get().getLooper());
2304
2305        getDefaultDisplayMetrics(context, mMetrics);
2306
2307        SystemConfig systemConfig = SystemConfig.getInstance();
2308        mGlobalGids = systemConfig.getGlobalGids();
2309        mSystemPermissions = systemConfig.getSystemPermissions();
2310        mAvailableFeatures = systemConfig.getAvailableFeatures();
2311
2312        mProtectedPackages = new ProtectedPackages(mContext);
2313
2314        synchronized (mInstallLock) {
2315        // writer
2316        synchronized (mPackages) {
2317            mHandlerThread = new ServiceThread(TAG,
2318                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2319            mHandlerThread.start();
2320            mHandler = new PackageHandler(mHandlerThread.getLooper());
2321            mProcessLoggingHandler = new ProcessLoggingHandler();
2322            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2323
2324            File dataDir = Environment.getDataDirectory();
2325            mAppInstallDir = new File(dataDir, "app");
2326            mAppLib32InstallDir = new File(dataDir, "app-lib");
2327            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2328            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2329            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2330
2331            sUserManager = new UserManagerService(context, this, mPackages);
2332
2333            // Propagate permission configuration in to package manager.
2334            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2335                    = systemConfig.getPermissions();
2336            for (int i=0; i<permConfig.size(); i++) {
2337                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2338                BasePermission bp = mSettings.mPermissions.get(perm.name);
2339                if (bp == null) {
2340                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2341                    mSettings.mPermissions.put(perm.name, bp);
2342                }
2343                if (perm.gids != null) {
2344                    bp.setGids(perm.gids, perm.perUser);
2345                }
2346            }
2347
2348            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2349            for (int i=0; i<libConfig.size(); i++) {
2350                mSharedLibraries.put(libConfig.keyAt(i),
2351                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2352            }
2353
2354            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2355
2356            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2357
2358            if (mFirstBoot) {
2359                requestCopyPreoptedFiles();
2360            }
2361
2362            String customResolverActivity = Resources.getSystem().getString(
2363                    R.string.config_customResolverActivity);
2364            if (TextUtils.isEmpty(customResolverActivity)) {
2365                customResolverActivity = null;
2366            } else {
2367                mCustomResolverComponentName = ComponentName.unflattenFromString(
2368                        customResolverActivity);
2369            }
2370
2371            long startTime = SystemClock.uptimeMillis();
2372
2373            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2374                    startTime);
2375
2376            // Set flag to monitor and not change apk file paths when
2377            // scanning install directories.
2378            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2379
2380            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2381            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2382
2383            if (bootClassPath == null) {
2384                Slog.w(TAG, "No BOOTCLASSPATH found!");
2385            }
2386
2387            if (systemServerClassPath == null) {
2388                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2389            }
2390
2391            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2392            final String[] dexCodeInstructionSets =
2393                    getDexCodeInstructionSets(
2394                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2395
2396            /**
2397             * Ensure all external libraries have had dexopt run on them.
2398             */
2399            if (mSharedLibraries.size() > 0) {
2400                // NOTE: For now, we're compiling these system "shared libraries"
2401                // (and framework jars) into all available architectures. It's possible
2402                // to compile them only when we come across an app that uses them (there's
2403                // already logic for that in scanPackageLI) but that adds some complexity.
2404                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2405                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2406                        final String lib = libEntry.path;
2407                        if (lib == null) {
2408                            continue;
2409                        }
2410
2411                        try {
2412                            // Shared libraries do not have profiles so we perform a full
2413                            // AOT compilation (if needed).
2414                            int dexoptNeeded = DexFile.getDexOptNeeded(
2415                                    lib, dexCodeInstructionSet,
2416                                    getCompilerFilterForReason(REASON_SHARED_APK),
2417                                    false /* newProfile */);
2418                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2419                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2420                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2421                                        getCompilerFilterForReason(REASON_SHARED_APK),
2422                                        StorageManager.UUID_PRIVATE_INTERNAL,
2423                                        SKIP_SHARED_LIBRARY_CHECK);
2424                            }
2425                        } catch (FileNotFoundException e) {
2426                            Slog.w(TAG, "Library not found: " + lib);
2427                        } catch (IOException | InstallerException e) {
2428                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2429                                    + e.getMessage());
2430                        }
2431                    }
2432                }
2433            }
2434
2435            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2436
2437            final VersionInfo ver = mSettings.getInternalVersion();
2438            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2439
2440            // when upgrading from pre-M, promote system app permissions from install to runtime
2441            mPromoteSystemApps =
2442                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2443
2444            // When upgrading from pre-N, we need to handle package extraction like first boot,
2445            // as there is no profiling data available.
2446            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2447
2448            // save off the names of pre-existing system packages prior to scanning; we don't
2449            // want to automatically grant runtime permissions for new system apps
2450            if (mPromoteSystemApps) {
2451                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2452                while (pkgSettingIter.hasNext()) {
2453                    PackageSetting ps = pkgSettingIter.next();
2454                    if (isSystemApp(ps)) {
2455                        mExistingSystemPackages.add(ps.name);
2456                    }
2457                }
2458            }
2459
2460            // Collect vendor overlay packages.
2461            // (Do this before scanning any apps.)
2462            // For security and version matching reason, only consider
2463            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2464            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2465            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2466                    | PackageParser.PARSE_IS_SYSTEM
2467                    | PackageParser.PARSE_IS_SYSTEM_DIR
2468                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2469
2470            // Find base frameworks (resource packages without code).
2471            scanDirTracedLI(frameworkDir, mDefParseFlags
2472                    | PackageParser.PARSE_IS_SYSTEM
2473                    | PackageParser.PARSE_IS_SYSTEM_DIR
2474                    | PackageParser.PARSE_IS_PRIVILEGED,
2475                    scanFlags | SCAN_NO_DEX, 0);
2476
2477            // Collected privileged system packages.
2478            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2479            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2480                    | PackageParser.PARSE_IS_SYSTEM
2481                    | PackageParser.PARSE_IS_SYSTEM_DIR
2482                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2483
2484            // Collect ordinary system packages.
2485            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2486            scanDirTracedLI(systemAppDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2489
2490            // Collect all vendor packages.
2491            File vendorAppDir = new File("/vendor/app");
2492            try {
2493                vendorAppDir = vendorAppDir.getCanonicalFile();
2494            } catch (IOException e) {
2495                // failed to look up canonical path, continue with original one
2496            }
2497            scanDirTracedLI(vendorAppDir, mDefParseFlags
2498                    | PackageParser.PARSE_IS_SYSTEM
2499                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2500
2501            // Collect all OEM packages.
2502            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2503            scanDirTracedLI(oemAppDir, mDefParseFlags
2504                    | PackageParser.PARSE_IS_SYSTEM
2505                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2506
2507            // Prune any system packages that no longer exist.
2508            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2509            if (!mOnlyCore) {
2510                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2511                while (psit.hasNext()) {
2512                    PackageSetting ps = psit.next();
2513
2514                    /*
2515                     * If this is not a system app, it can't be a
2516                     * disable system app.
2517                     */
2518                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2519                        continue;
2520                    }
2521
2522                    /*
2523                     * If the package is scanned, it's not erased.
2524                     */
2525                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2526                    if (scannedPkg != null) {
2527                        /*
2528                         * If the system app is both scanned and in the
2529                         * disabled packages list, then it must have been
2530                         * added via OTA. Remove it from the currently
2531                         * scanned package so the previously user-installed
2532                         * application can be scanned.
2533                         */
2534                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2535                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2536                                    + ps.name + "; removing system app.  Last known codePath="
2537                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2538                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2539                                    + scannedPkg.mVersionCode);
2540                            removePackageLI(scannedPkg, true);
2541                            mExpectingBetter.put(ps.name, ps.codePath);
2542                        }
2543
2544                        continue;
2545                    }
2546
2547                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2548                        psit.remove();
2549                        logCriticalInfo(Log.WARN, "System package " + ps.name
2550                                + " no longer exists; it's data will be wiped");
2551                        // Actual deletion of code and data will be handled by later
2552                        // reconciliation step
2553                    } else {
2554                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2555                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2556                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2557                        }
2558                    }
2559                }
2560            }
2561
2562            //look for any incomplete package installations
2563            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2564            for (int i = 0; i < deletePkgsList.size(); i++) {
2565                // Actual deletion of code and data will be handled by later
2566                // reconciliation step
2567                final String packageName = deletePkgsList.get(i).name;
2568                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2569                synchronized (mPackages) {
2570                    mSettings.removePackageLPw(packageName);
2571                }
2572            }
2573
2574            //delete tmp files
2575            deleteTempPackageFiles();
2576
2577            // Remove any shared userIDs that have no associated packages
2578            mSettings.pruneSharedUsersLPw();
2579
2580            if (!mOnlyCore) {
2581                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2582                        SystemClock.uptimeMillis());
2583                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2584
2585                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2586                        | PackageParser.PARSE_FORWARD_LOCK,
2587                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2588
2589                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2590                        | PackageParser.PARSE_IS_EPHEMERAL,
2591                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2592
2593                /**
2594                 * Remove disable package settings for any updated system
2595                 * apps that were removed via an OTA. If they're not a
2596                 * previously-updated app, remove them completely.
2597                 * Otherwise, just revoke their system-level permissions.
2598                 */
2599                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2600                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2601                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2602
2603                    String msg;
2604                    if (deletedPkg == null) {
2605                        msg = "Updated system package " + deletedAppName
2606                                + " no longer exists; it's data will be wiped";
2607                        // Actual deletion of code and data will be handled by later
2608                        // reconciliation step
2609                    } else {
2610                        msg = "Updated system app + " + deletedAppName
2611                                + " no longer present; removing system privileges for "
2612                                + deletedAppName;
2613
2614                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2615
2616                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2617                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2618                    }
2619                    logCriticalInfo(Log.WARN, msg);
2620                }
2621
2622                /**
2623                 * Make sure all system apps that we expected to appear on
2624                 * the userdata partition actually showed up. If they never
2625                 * appeared, crawl back and revive the system version.
2626                 */
2627                for (int i = 0; i < mExpectingBetter.size(); i++) {
2628                    final String packageName = mExpectingBetter.keyAt(i);
2629                    if (!mPackages.containsKey(packageName)) {
2630                        final File scanFile = mExpectingBetter.valueAt(i);
2631
2632                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2633                                + " but never showed up; reverting to system");
2634
2635                        int reparseFlags = mDefParseFlags;
2636                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2637                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2638                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2639                                    | PackageParser.PARSE_IS_PRIVILEGED;
2640                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2641                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2642                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2643                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else {
2650                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2651                            continue;
2652                        }
2653
2654                        mSettings.enableSystemPackageLPw(packageName);
2655
2656                        try {
2657                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2658                        } catch (PackageManagerException e) {
2659                            Slog.e(TAG, "Failed to parse original system package: "
2660                                    + e.getMessage());
2661                        }
2662                    }
2663                }
2664            }
2665            mExpectingBetter.clear();
2666
2667            // Resolve protected action filters. Only the setup wizard is allowed to
2668            // have a high priority filter for these actions.
2669            mSetupWizardPackage = getSetupWizardPackageName();
2670            if (mProtectedFilters.size() > 0) {
2671                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2672                    Slog.i(TAG, "No setup wizard;"
2673                        + " All protected intents capped to priority 0");
2674                }
2675                for (ActivityIntentInfo filter : mProtectedFilters) {
2676                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2677                        if (DEBUG_FILTERS) {
2678                            Slog.i(TAG, "Found setup wizard;"
2679                                + " allow priority " + filter.getPriority() + ";"
2680                                + " package: " + filter.activity.info.packageName
2681                                + " activity: " + filter.activity.className
2682                                + " priority: " + filter.getPriority());
2683                        }
2684                        // skip setup wizard; allow it to keep the high priority filter
2685                        continue;
2686                    }
2687                    Slog.w(TAG, "Protected action; cap priority to 0;"
2688                            + " package: " + filter.activity.info.packageName
2689                            + " activity: " + filter.activity.className
2690                            + " origPrio: " + filter.getPriority());
2691                    filter.setPriority(0);
2692                }
2693            }
2694            mDeferProtectedFilters = false;
2695            mProtectedFilters.clear();
2696
2697            // Now that we know all of the shared libraries, update all clients to have
2698            // the correct library paths.
2699            updateAllSharedLibrariesLPw();
2700
2701            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2702                // NOTE: We ignore potential failures here during a system scan (like
2703                // the rest of the commands above) because there's precious little we
2704                // can do about it. A settings error is reported, though.
2705                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2706                        false /* boot complete */);
2707            }
2708
2709            // Now that we know all the packages we are keeping,
2710            // read and update their last usage times.
2711            mPackageUsage.readLP();
2712
2713            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2714                    SystemClock.uptimeMillis());
2715            Slog.i(TAG, "Time to scan packages: "
2716                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2717                    + " seconds");
2718
2719            // If the platform SDK has changed since the last time we booted,
2720            // we need to re-grant app permission to catch any new ones that
2721            // appear.  This is really a hack, and means that apps can in some
2722            // cases get permissions that the user didn't initially explicitly
2723            // allow...  it would be nice to have some better way to handle
2724            // this situation.
2725            int updateFlags = UPDATE_PERMISSIONS_ALL;
2726            if (ver.sdkVersion != mSdkVersion) {
2727                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2728                        + mSdkVersion + "; regranting permissions for internal storage");
2729                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2730            }
2731            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2732            ver.sdkVersion = mSdkVersion;
2733
2734            // If this is the first boot or an update from pre-M, and it is a normal
2735            // boot, then we need to initialize the default preferred apps across
2736            // all defined users.
2737            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2738                for (UserInfo user : sUserManager.getUsers(true)) {
2739                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2740                    applyFactoryDefaultBrowserLPw(user.id);
2741                    primeDomainVerificationsLPw(user.id);
2742                }
2743            }
2744
2745            // Prepare storage for system user really early during boot,
2746            // since core system apps like SettingsProvider and SystemUI
2747            // can't wait for user to start
2748            final int storageFlags;
2749            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2750                storageFlags = StorageManager.FLAG_STORAGE_DE;
2751            } else {
2752                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2753            }
2754            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2755                    storageFlags);
2756
2757            // If this is first boot after an OTA, and a normal boot, then
2758            // we need to clear code cache directories.
2759            // Note that we do *not* clear the application profiles. These remain valid
2760            // across OTAs and are used to drive profile verification (post OTA) and
2761            // profile compilation (without waiting to collect a fresh set of profiles).
2762            if (mIsUpgrade && !onlyCore) {
2763                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2764                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2765                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2766                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2767                        // No apps are running this early, so no need to freeze
2768                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2769                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2770                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2771                    }
2772                }
2773                ver.fingerprint = Build.FINGERPRINT;
2774            }
2775
2776            checkDefaultBrowser();
2777
2778            // clear only after permissions and other defaults have been updated
2779            mExistingSystemPackages.clear();
2780            mPromoteSystemApps = false;
2781
2782            // All the changes are done during package scanning.
2783            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2784
2785            // can downgrade to reader
2786            mSettings.writeLPr();
2787
2788            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2789            // early on (before the package manager declares itself as early) because other
2790            // components in the system server might ask for package contexts for these apps.
2791            //
2792            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2793            // (i.e, that the data partition is unavailable).
2794            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2795                long start = System.nanoTime();
2796                List<PackageParser.Package> coreApps = new ArrayList<>();
2797                for (PackageParser.Package pkg : mPackages.values()) {
2798                    if (pkg.coreApp) {
2799                        coreApps.add(pkg);
2800                    }
2801                }
2802
2803                int[] stats = performDexOpt(coreApps, false,
2804                        getCompilerFilterForReason(REASON_CORE_APP));
2805
2806                final int elapsedTimeSeconds =
2807                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2808                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2809
2810                if (DEBUG_DEXOPT) {
2811                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2812                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2813                }
2814
2815
2816                // TODO: Should we log these stats to tron too ?
2817                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2818                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2819                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2820                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2821            }
2822
2823            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2824                    SystemClock.uptimeMillis());
2825
2826            if (!mOnlyCore) {
2827                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2828                mRequiredInstallerPackage = getRequiredInstallerLPr();
2829                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2830                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2831                        mIntentFilterVerifierComponent);
2832                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2833                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2834                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2835                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2836            } else {
2837                mRequiredVerifierPackage = null;
2838                mRequiredInstallerPackage = null;
2839                mIntentFilterVerifierComponent = null;
2840                mIntentFilterVerifier = null;
2841                mServicesSystemSharedLibraryPackageName = null;
2842                mSharedSystemSharedLibraryPackageName = null;
2843            }
2844
2845            mInstallerService = new PackageInstallerService(context, this);
2846
2847            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2848            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2849            // both the installer and resolver must be present to enable ephemeral
2850            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2851                if (DEBUG_EPHEMERAL) {
2852                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2853                            + " installer:" + ephemeralInstallerComponent);
2854                }
2855                mEphemeralResolverComponent = ephemeralResolverComponent;
2856                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2857                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2858                mEphemeralResolverConnection =
2859                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2860            } else {
2861                if (DEBUG_EPHEMERAL) {
2862                    final String missingComponent =
2863                            (ephemeralResolverComponent == null)
2864                            ? (ephemeralInstallerComponent == null)
2865                                    ? "resolver and installer"
2866                                    : "resolver"
2867                            : "installer";
2868                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2869                }
2870                mEphemeralResolverComponent = null;
2871                mEphemeralInstallerComponent = null;
2872                mEphemeralResolverConnection = null;
2873            }
2874
2875            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2876        } // synchronized (mPackages)
2877        } // synchronized (mInstallLock)
2878
2879        // Now after opening every single application zip, make sure they
2880        // are all flushed.  Not really needed, but keeps things nice and
2881        // tidy.
2882        Runtime.getRuntime().gc();
2883
2884        // The initial scanning above does many calls into installd while
2885        // holding the mPackages lock, but we're mostly interested in yelling
2886        // once we have a booted system.
2887        mInstaller.setWarnIfHeld(mPackages);
2888
2889        // Expose private service for system components to use.
2890        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2891    }
2892
2893    @Override
2894    public boolean isFirstBoot() {
2895        return mFirstBoot;
2896    }
2897
2898    @Override
2899    public boolean isOnlyCoreApps() {
2900        return mOnlyCore;
2901    }
2902
2903    @Override
2904    public boolean isUpgrade() {
2905        return mIsUpgrade;
2906    }
2907
2908    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2909        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2910
2911        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2912                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2913                UserHandle.USER_SYSTEM);
2914        if (matches.size() == 1) {
2915            return matches.get(0).getComponentInfo().packageName;
2916        } else {
2917            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2918            return null;
2919        }
2920    }
2921
2922    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2923        synchronized (mPackages) {
2924            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2925            if (libraryEntry == null) {
2926                throw new IllegalStateException("Missing required shared library:" + libraryName);
2927            }
2928            return libraryEntry.apk;
2929        }
2930    }
2931
2932    private @NonNull String getRequiredInstallerLPr() {
2933        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2934        intent.addCategory(Intent.CATEGORY_DEFAULT);
2935        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2936
2937        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2938                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2939                UserHandle.USER_SYSTEM);
2940        if (matches.size() == 1) {
2941            ResolveInfo resolveInfo = matches.get(0);
2942            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2943                throw new RuntimeException("The installer must be a privileged app");
2944            }
2945            return matches.get(0).getComponentInfo().packageName;
2946        } else {
2947            throw new RuntimeException("There must be exactly one installer; found " + matches);
2948        }
2949    }
2950
2951    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2952        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2953
2954        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2955                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2956                UserHandle.USER_SYSTEM);
2957        ResolveInfo best = null;
2958        final int N = matches.size();
2959        for (int i = 0; i < N; i++) {
2960            final ResolveInfo cur = matches.get(i);
2961            final String packageName = cur.getComponentInfo().packageName;
2962            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2963                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2964                continue;
2965            }
2966
2967            if (best == null || cur.priority > best.priority) {
2968                best = cur;
2969            }
2970        }
2971
2972        if (best != null) {
2973            return best.getComponentInfo().getComponentName();
2974        } else {
2975            throw new RuntimeException("There must be at least one intent filter verifier");
2976        }
2977    }
2978
2979    private @Nullable ComponentName getEphemeralResolverLPr() {
2980        final String[] packageArray =
2981                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2982        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2983            if (DEBUG_EPHEMERAL) {
2984                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2985            }
2986            return null;
2987        }
2988
2989        final int resolveFlags =
2990                MATCH_DIRECT_BOOT_AWARE
2991                | MATCH_DIRECT_BOOT_UNAWARE
2992                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2993        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2994        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2995                resolveFlags, UserHandle.USER_SYSTEM);
2996
2997        final int N = resolvers.size();
2998        if (N == 0) {
2999            if (DEBUG_EPHEMERAL) {
3000                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3001            }
3002            return null;
3003        }
3004
3005        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3006        for (int i = 0; i < N; i++) {
3007            final ResolveInfo info = resolvers.get(i);
3008
3009            if (info.serviceInfo == null) {
3010                continue;
3011            }
3012
3013            final String packageName = info.serviceInfo.packageName;
3014            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3015                if (DEBUG_EPHEMERAL) {
3016                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3017                            + " pkg: " + packageName + ", info:" + info);
3018                }
3019                continue;
3020            }
3021
3022            if (DEBUG_EPHEMERAL) {
3023                Slog.v(TAG, "Ephemeral resolver found;"
3024                        + " pkg: " + packageName + ", info:" + info);
3025            }
3026            return new ComponentName(packageName, info.serviceInfo.name);
3027        }
3028        if (DEBUG_EPHEMERAL) {
3029            Slog.v(TAG, "Ephemeral resolver NOT found");
3030        }
3031        return null;
3032    }
3033
3034    private @Nullable ComponentName getEphemeralInstallerLPr() {
3035        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3036        intent.addCategory(Intent.CATEGORY_DEFAULT);
3037        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3038
3039        final int resolveFlags =
3040                MATCH_DIRECT_BOOT_AWARE
3041                | MATCH_DIRECT_BOOT_UNAWARE
3042                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3043        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3044                resolveFlags, UserHandle.USER_SYSTEM);
3045        if (matches.size() == 0) {
3046            return null;
3047        } else if (matches.size() == 1) {
3048            return matches.get(0).getComponentInfo().getComponentName();
3049        } else {
3050            throw new RuntimeException(
3051                    "There must be at most one ephemeral installer; found " + matches);
3052        }
3053    }
3054
3055    private void primeDomainVerificationsLPw(int userId) {
3056        if (DEBUG_DOMAIN_VERIFICATION) {
3057            Slog.d(TAG, "Priming domain verifications in user " + userId);
3058        }
3059
3060        SystemConfig systemConfig = SystemConfig.getInstance();
3061        ArraySet<String> packages = systemConfig.getLinkedApps();
3062        ArraySet<String> domains = new ArraySet<String>();
3063
3064        for (String packageName : packages) {
3065            PackageParser.Package pkg = mPackages.get(packageName);
3066            if (pkg != null) {
3067                if (!pkg.isSystemApp()) {
3068                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3069                    continue;
3070                }
3071
3072                domains.clear();
3073                for (PackageParser.Activity a : pkg.activities) {
3074                    for (ActivityIntentInfo filter : a.intents) {
3075                        if (hasValidDomains(filter)) {
3076                            domains.addAll(filter.getHostsList());
3077                        }
3078                    }
3079                }
3080
3081                if (domains.size() > 0) {
3082                    if (DEBUG_DOMAIN_VERIFICATION) {
3083                        Slog.v(TAG, "      + " + packageName);
3084                    }
3085                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3086                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3087                    // and then 'always' in the per-user state actually used for intent resolution.
3088                    final IntentFilterVerificationInfo ivi;
3089                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3090                            new ArrayList<String>(domains));
3091                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3092                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3093                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3094                } else {
3095                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3096                            + "' does not handle web links");
3097                }
3098            } else {
3099                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3100            }
3101        }
3102
3103        scheduleWritePackageRestrictionsLocked(userId);
3104        scheduleWriteSettingsLocked();
3105    }
3106
3107    private void applyFactoryDefaultBrowserLPw(int userId) {
3108        // The default browser app's package name is stored in a string resource,
3109        // with a product-specific overlay used for vendor customization.
3110        String browserPkg = mContext.getResources().getString(
3111                com.android.internal.R.string.default_browser);
3112        if (!TextUtils.isEmpty(browserPkg)) {
3113            // non-empty string => required to be a known package
3114            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3115            if (ps == null) {
3116                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3117                browserPkg = null;
3118            } else {
3119                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3120            }
3121        }
3122
3123        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3124        // default.  If there's more than one, just leave everything alone.
3125        if (browserPkg == null) {
3126            calculateDefaultBrowserLPw(userId);
3127        }
3128    }
3129
3130    private void calculateDefaultBrowserLPw(int userId) {
3131        List<String> allBrowsers = resolveAllBrowserApps(userId);
3132        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3133        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3134    }
3135
3136    private List<String> resolveAllBrowserApps(int userId) {
3137        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3138        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3139                PackageManager.MATCH_ALL, userId);
3140
3141        final int count = list.size();
3142        List<String> result = new ArrayList<String>(count);
3143        for (int i=0; i<count; i++) {
3144            ResolveInfo info = list.get(i);
3145            if (info.activityInfo == null
3146                    || !info.handleAllWebDataURI
3147                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3148                    || result.contains(info.activityInfo.packageName)) {
3149                continue;
3150            }
3151            result.add(info.activityInfo.packageName);
3152        }
3153
3154        return result;
3155    }
3156
3157    private boolean packageIsBrowser(String packageName, int userId) {
3158        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3159                PackageManager.MATCH_ALL, userId);
3160        final int N = list.size();
3161        for (int i = 0; i < N; i++) {
3162            ResolveInfo info = list.get(i);
3163            if (packageName.equals(info.activityInfo.packageName)) {
3164                return true;
3165            }
3166        }
3167        return false;
3168    }
3169
3170    private void checkDefaultBrowser() {
3171        final int myUserId = UserHandle.myUserId();
3172        final String packageName = getDefaultBrowserPackageName(myUserId);
3173        if (packageName != null) {
3174            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3175            if (info == null) {
3176                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3177                synchronized (mPackages) {
3178                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3179                }
3180            }
3181        }
3182    }
3183
3184    @Override
3185    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3186            throws RemoteException {
3187        try {
3188            return super.onTransact(code, data, reply, flags);
3189        } catch (RuntimeException e) {
3190            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3191                Slog.wtf(TAG, "Package Manager Crash", e);
3192            }
3193            throw e;
3194        }
3195    }
3196
3197    static int[] appendInts(int[] cur, int[] add) {
3198        if (add == null) return cur;
3199        if (cur == null) return add;
3200        final int N = add.length;
3201        for (int i=0; i<N; i++) {
3202            cur = appendInt(cur, add[i]);
3203        }
3204        return cur;
3205    }
3206
3207    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3208        if (!sUserManager.exists(userId)) return null;
3209        if (ps == null) {
3210            return null;
3211        }
3212        final PackageParser.Package p = ps.pkg;
3213        if (p == null) {
3214            return null;
3215        }
3216
3217        final PermissionsState permissionsState = ps.getPermissionsState();
3218
3219        // Compute GIDs only if requested
3220        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3221                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3222        // Compute granted permissions only if package has requested permissions
3223        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3224                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3225        final PackageUserState state = ps.readUserState(userId);
3226
3227        return PackageParser.generatePackageInfo(p, gids, flags,
3228                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3229    }
3230
3231    @Override
3232    public void checkPackageStartable(String packageName, int userId) {
3233        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3234
3235        synchronized (mPackages) {
3236            final PackageSetting ps = mSettings.mPackages.get(packageName);
3237            if (ps == null) {
3238                throw new SecurityException("Package " + packageName + " was not found!");
3239            }
3240
3241            if (!ps.getInstalled(userId)) {
3242                throw new SecurityException(
3243                        "Package " + packageName + " was not installed for user " + userId + "!");
3244            }
3245
3246            if (mSafeMode && !ps.isSystem()) {
3247                throw new SecurityException("Package " + packageName + " not a system app!");
3248            }
3249
3250            if (mFrozenPackages.contains(packageName)) {
3251                throw new SecurityException("Package " + packageName + " is currently frozen!");
3252            }
3253
3254            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3255                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3256                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3257            }
3258        }
3259    }
3260
3261    @Override
3262    public boolean isPackageAvailable(String packageName, int userId) {
3263        if (!sUserManager.exists(userId)) return false;
3264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3265                false /* requireFullPermission */, false /* checkShell */, "is package available");
3266        synchronized (mPackages) {
3267            PackageParser.Package p = mPackages.get(packageName);
3268            if (p != null) {
3269                final PackageSetting ps = (PackageSetting) p.mExtras;
3270                if (ps != null) {
3271                    final PackageUserState state = ps.readUserState(userId);
3272                    if (state != null) {
3273                        return PackageParser.isAvailable(state);
3274                    }
3275                }
3276            }
3277        }
3278        return false;
3279    }
3280
3281    @Override
3282    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3283        if (!sUserManager.exists(userId)) return null;
3284        flags = updateFlagsForPackage(flags, userId, packageName);
3285        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3286                false /* requireFullPermission */, false /* checkShell */, "get package info");
3287        // reader
3288        synchronized (mPackages) {
3289            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3290            PackageParser.Package p = null;
3291            if (matchFactoryOnly) {
3292                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3293                if (ps != null) {
3294                    return generatePackageInfo(ps, flags, userId);
3295                }
3296            }
3297            if (p == null) {
3298                p = mPackages.get(packageName);
3299                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3300                    return null;
3301                }
3302            }
3303            if (DEBUG_PACKAGE_INFO)
3304                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3305            if (p != null) {
3306                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3307            }
3308            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3309                final PackageSetting ps = mSettings.mPackages.get(packageName);
3310                return generatePackageInfo(ps, flags, userId);
3311            }
3312        }
3313        return null;
3314    }
3315
3316    @Override
3317    public String[] currentToCanonicalPackageNames(String[] names) {
3318        String[] out = new String[names.length];
3319        // reader
3320        synchronized (mPackages) {
3321            for (int i=names.length-1; i>=0; i--) {
3322                PackageSetting ps = mSettings.mPackages.get(names[i]);
3323                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3324            }
3325        }
3326        return out;
3327    }
3328
3329    @Override
3330    public String[] canonicalToCurrentPackageNames(String[] names) {
3331        String[] out = new String[names.length];
3332        // reader
3333        synchronized (mPackages) {
3334            for (int i=names.length-1; i>=0; i--) {
3335                String cur = mSettings.mRenamedPackages.get(names[i]);
3336                out[i] = cur != null ? cur : names[i];
3337            }
3338        }
3339        return out;
3340    }
3341
3342    @Override
3343    public int getPackageUid(String packageName, int flags, int userId) {
3344        if (!sUserManager.exists(userId)) return -1;
3345        flags = updateFlagsForPackage(flags, userId, packageName);
3346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3347                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3348
3349        // reader
3350        synchronized (mPackages) {
3351            final PackageParser.Package p = mPackages.get(packageName);
3352            if (p != null && p.isMatch(flags)) {
3353                return UserHandle.getUid(userId, p.applicationInfo.uid);
3354            }
3355            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3356                final PackageSetting ps = mSettings.mPackages.get(packageName);
3357                if (ps != null && ps.isMatch(flags)) {
3358                    return UserHandle.getUid(userId, ps.appId);
3359                }
3360            }
3361        }
3362
3363        return -1;
3364    }
3365
3366    @Override
3367    public int[] getPackageGids(String packageName, int flags, int userId) {
3368        if (!sUserManager.exists(userId)) return null;
3369        flags = updateFlagsForPackage(flags, userId, packageName);
3370        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3371                false /* requireFullPermission */, false /* checkShell */,
3372                "getPackageGids");
3373
3374        // reader
3375        synchronized (mPackages) {
3376            final PackageParser.Package p = mPackages.get(packageName);
3377            if (p != null && p.isMatch(flags)) {
3378                PackageSetting ps = (PackageSetting) p.mExtras;
3379                return ps.getPermissionsState().computeGids(userId);
3380            }
3381            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3382                final PackageSetting ps = mSettings.mPackages.get(packageName);
3383                if (ps != null && ps.isMatch(flags)) {
3384                    return ps.getPermissionsState().computeGids(userId);
3385                }
3386            }
3387        }
3388
3389        return null;
3390    }
3391
3392    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3393        if (bp.perm != null) {
3394            return PackageParser.generatePermissionInfo(bp.perm, flags);
3395        }
3396        PermissionInfo pi = new PermissionInfo();
3397        pi.name = bp.name;
3398        pi.packageName = bp.sourcePackage;
3399        pi.nonLocalizedLabel = bp.name;
3400        pi.protectionLevel = bp.protectionLevel;
3401        return pi;
3402    }
3403
3404    @Override
3405    public PermissionInfo getPermissionInfo(String name, int flags) {
3406        // reader
3407        synchronized (mPackages) {
3408            final BasePermission p = mSettings.mPermissions.get(name);
3409            if (p != null) {
3410                return generatePermissionInfo(p, flags);
3411            }
3412            return null;
3413        }
3414    }
3415
3416    @Override
3417    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3418            int flags) {
3419        // reader
3420        synchronized (mPackages) {
3421            if (group != null && !mPermissionGroups.containsKey(group)) {
3422                // This is thrown as NameNotFoundException
3423                return null;
3424            }
3425
3426            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3427            for (BasePermission p : mSettings.mPermissions.values()) {
3428                if (group == null) {
3429                    if (p.perm == null || p.perm.info.group == null) {
3430                        out.add(generatePermissionInfo(p, flags));
3431                    }
3432                } else {
3433                    if (p.perm != null && group.equals(p.perm.info.group)) {
3434                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3435                    }
3436                }
3437            }
3438            return new ParceledListSlice<>(out);
3439        }
3440    }
3441
3442    @Override
3443    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3444        // reader
3445        synchronized (mPackages) {
3446            return PackageParser.generatePermissionGroupInfo(
3447                    mPermissionGroups.get(name), flags);
3448        }
3449    }
3450
3451    @Override
3452    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3453        // reader
3454        synchronized (mPackages) {
3455            final int N = mPermissionGroups.size();
3456            ArrayList<PermissionGroupInfo> out
3457                    = new ArrayList<PermissionGroupInfo>(N);
3458            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3459                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3460            }
3461            return new ParceledListSlice<>(out);
3462        }
3463    }
3464
3465    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3466            int userId) {
3467        if (!sUserManager.exists(userId)) return null;
3468        PackageSetting ps = mSettings.mPackages.get(packageName);
3469        if (ps != null) {
3470            if (ps.pkg == null) {
3471                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3472                if (pInfo != null) {
3473                    return pInfo.applicationInfo;
3474                }
3475                return null;
3476            }
3477            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3478                    ps.readUserState(userId), userId);
3479        }
3480        return null;
3481    }
3482
3483    @Override
3484    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3485        if (!sUserManager.exists(userId)) return null;
3486        flags = updateFlagsForApplication(flags, userId, packageName);
3487        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3488                false /* requireFullPermission */, false /* checkShell */, "get application info");
3489        // writer
3490        synchronized (mPackages) {
3491            PackageParser.Package p = mPackages.get(packageName);
3492            if (DEBUG_PACKAGE_INFO) Log.v(
3493                    TAG, "getApplicationInfo " + packageName
3494                    + ": " + p);
3495            if (p != null) {
3496                PackageSetting ps = mSettings.mPackages.get(packageName);
3497                if (ps == null) return null;
3498                // Note: isEnabledLP() does not apply here - always return info
3499                return PackageParser.generateApplicationInfo(
3500                        p, flags, ps.readUserState(userId), userId);
3501            }
3502            if ("android".equals(packageName)||"system".equals(packageName)) {
3503                return mAndroidApplication;
3504            }
3505            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3506                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3507            }
3508        }
3509        return null;
3510    }
3511
3512    @Override
3513    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3514            final IPackageDataObserver observer) {
3515        mContext.enforceCallingOrSelfPermission(
3516                android.Manifest.permission.CLEAR_APP_CACHE, null);
3517        // Queue up an async operation since clearing cache may take a little while.
3518        mHandler.post(new Runnable() {
3519            public void run() {
3520                mHandler.removeCallbacks(this);
3521                boolean success = true;
3522                synchronized (mInstallLock) {
3523                    try {
3524                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3525                    } catch (InstallerException e) {
3526                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3527                        success = false;
3528                    }
3529                }
3530                if (observer != null) {
3531                    try {
3532                        observer.onRemoveCompleted(null, success);
3533                    } catch (RemoteException e) {
3534                        Slog.w(TAG, "RemoveException when invoking call back");
3535                    }
3536                }
3537            }
3538        });
3539    }
3540
3541    @Override
3542    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3543            final IntentSender pi) {
3544        mContext.enforceCallingOrSelfPermission(
3545                android.Manifest.permission.CLEAR_APP_CACHE, null);
3546        // Queue up an async operation since clearing cache may take a little while.
3547        mHandler.post(new Runnable() {
3548            public void run() {
3549                mHandler.removeCallbacks(this);
3550                boolean success = true;
3551                synchronized (mInstallLock) {
3552                    try {
3553                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3554                    } catch (InstallerException e) {
3555                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3556                        success = false;
3557                    }
3558                }
3559                if(pi != null) {
3560                    try {
3561                        // Callback via pending intent
3562                        int code = success ? 1 : 0;
3563                        pi.sendIntent(null, code, null,
3564                                null, null);
3565                    } catch (SendIntentException e1) {
3566                        Slog.i(TAG, "Failed to send pending intent");
3567                    }
3568                }
3569            }
3570        });
3571    }
3572
3573    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3574        synchronized (mInstallLock) {
3575            try {
3576                mInstaller.freeCache(volumeUuid, freeStorageSize);
3577            } catch (InstallerException e) {
3578                throw new IOException("Failed to free enough space", e);
3579            }
3580        }
3581    }
3582
3583    /**
3584     * Update given flags based on encryption status of current user.
3585     */
3586    private int updateFlags(int flags, int userId) {
3587        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3588                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3589            // Caller expressed an explicit opinion about what encryption
3590            // aware/unaware components they want to see, so fall through and
3591            // give them what they want
3592        } else {
3593            // Caller expressed no opinion, so match based on user state
3594            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3595                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3596            } else {
3597                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3598            }
3599        }
3600        return flags;
3601    }
3602
3603    private UserManagerInternal getUserManagerInternal() {
3604        if (mUserManagerInternal == null) {
3605            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3606        }
3607        return mUserManagerInternal;
3608    }
3609
3610    /**
3611     * Update given flags when being used to request {@link PackageInfo}.
3612     */
3613    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3614        boolean triaged = true;
3615        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3616                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3617            // Caller is asking for component details, so they'd better be
3618            // asking for specific encryption matching behavior, or be triaged
3619            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3620                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3621                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3622                triaged = false;
3623            }
3624        }
3625        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3626                | PackageManager.MATCH_SYSTEM_ONLY
3627                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3628            triaged = false;
3629        }
3630        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3631            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3632                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3633        }
3634        return updateFlags(flags, userId);
3635    }
3636
3637    /**
3638     * Update given flags when being used to request {@link ApplicationInfo}.
3639     */
3640    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3641        return updateFlagsForPackage(flags, userId, cookie);
3642    }
3643
3644    /**
3645     * Update given flags when being used to request {@link ComponentInfo}.
3646     */
3647    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3648        if (cookie instanceof Intent) {
3649            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3650                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3651            }
3652        }
3653
3654        boolean triaged = true;
3655        // Caller is asking for component details, so they'd better be
3656        // asking for specific encryption matching behavior, or be triaged
3657        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3658                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3659                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3660            triaged = false;
3661        }
3662        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3663            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3664                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3665        }
3666
3667        return updateFlags(flags, userId);
3668    }
3669
3670    /**
3671     * Update given flags when being used to request {@link ResolveInfo}.
3672     */
3673    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3674        // Safe mode means we shouldn't match any third-party components
3675        if (mSafeMode) {
3676            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3677        }
3678
3679        return updateFlagsForComponent(flags, userId, cookie);
3680    }
3681
3682    @Override
3683    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3684        if (!sUserManager.exists(userId)) return null;
3685        flags = updateFlagsForComponent(flags, userId, component);
3686        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3687                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3688        synchronized (mPackages) {
3689            PackageParser.Activity a = mActivities.mActivities.get(component);
3690
3691            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3692            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3693                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3694                if (ps == null) return null;
3695                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3696                        userId);
3697            }
3698            if (mResolveComponentName.equals(component)) {
3699                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3700                        new PackageUserState(), userId);
3701            }
3702        }
3703        return null;
3704    }
3705
3706    @Override
3707    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3708            String resolvedType) {
3709        synchronized (mPackages) {
3710            if (component.equals(mResolveComponentName)) {
3711                // The resolver supports EVERYTHING!
3712                return true;
3713            }
3714            PackageParser.Activity a = mActivities.mActivities.get(component);
3715            if (a == null) {
3716                return false;
3717            }
3718            for (int i=0; i<a.intents.size(); i++) {
3719                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3720                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3721                    return true;
3722                }
3723            }
3724            return false;
3725        }
3726    }
3727
3728    @Override
3729    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3730        if (!sUserManager.exists(userId)) return null;
3731        flags = updateFlagsForComponent(flags, userId, component);
3732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3733                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3734        synchronized (mPackages) {
3735            PackageParser.Activity a = mReceivers.mActivities.get(component);
3736            if (DEBUG_PACKAGE_INFO) Log.v(
3737                TAG, "getReceiverInfo " + component + ": " + a);
3738            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3739                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3740                if (ps == null) return null;
3741                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3742                        userId);
3743            }
3744        }
3745        return null;
3746    }
3747
3748    @Override
3749    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3750        if (!sUserManager.exists(userId)) return null;
3751        flags = updateFlagsForComponent(flags, userId, component);
3752        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3753                false /* requireFullPermission */, false /* checkShell */, "get service info");
3754        synchronized (mPackages) {
3755            PackageParser.Service s = mServices.mServices.get(component);
3756            if (DEBUG_PACKAGE_INFO) Log.v(
3757                TAG, "getServiceInfo " + component + ": " + s);
3758            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3759                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3760                if (ps == null) return null;
3761                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3762                        userId);
3763            }
3764        }
3765        return null;
3766    }
3767
3768    @Override
3769    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3770        if (!sUserManager.exists(userId)) return null;
3771        flags = updateFlagsForComponent(flags, userId, component);
3772        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3773                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3774        synchronized (mPackages) {
3775            PackageParser.Provider p = mProviders.mProviders.get(component);
3776            if (DEBUG_PACKAGE_INFO) Log.v(
3777                TAG, "getProviderInfo " + component + ": " + p);
3778            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3779                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3780                if (ps == null) return null;
3781                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3782                        userId);
3783            }
3784        }
3785        return null;
3786    }
3787
3788    @Override
3789    public String[] getSystemSharedLibraryNames() {
3790        Set<String> libSet;
3791        synchronized (mPackages) {
3792            libSet = mSharedLibraries.keySet();
3793            int size = libSet.size();
3794            if (size > 0) {
3795                String[] libs = new String[size];
3796                libSet.toArray(libs);
3797                return libs;
3798            }
3799        }
3800        return null;
3801    }
3802
3803    @Override
3804    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3805        synchronized (mPackages) {
3806            return mServicesSystemSharedLibraryPackageName;
3807        }
3808    }
3809
3810    @Override
3811    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3812        synchronized (mPackages) {
3813            return mSharedSystemSharedLibraryPackageName;
3814        }
3815    }
3816
3817    @Override
3818    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3819        synchronized (mPackages) {
3820            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3821
3822            final FeatureInfo fi = new FeatureInfo();
3823            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3824                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3825            res.add(fi);
3826
3827            return new ParceledListSlice<>(res);
3828        }
3829    }
3830
3831    @Override
3832    public boolean hasSystemFeature(String name, int version) {
3833        synchronized (mPackages) {
3834            final FeatureInfo feat = mAvailableFeatures.get(name);
3835            if (feat == null) {
3836                return false;
3837            } else {
3838                return feat.version >= version;
3839            }
3840        }
3841    }
3842
3843    @Override
3844    public int checkPermission(String permName, String pkgName, int userId) {
3845        if (!sUserManager.exists(userId)) {
3846            return PackageManager.PERMISSION_DENIED;
3847        }
3848
3849        synchronized (mPackages) {
3850            final PackageParser.Package p = mPackages.get(pkgName);
3851            if (p != null && p.mExtras != null) {
3852                final PackageSetting ps = (PackageSetting) p.mExtras;
3853                final PermissionsState permissionsState = ps.getPermissionsState();
3854                if (permissionsState.hasPermission(permName, userId)) {
3855                    return PackageManager.PERMISSION_GRANTED;
3856                }
3857                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3858                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3859                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3860                    return PackageManager.PERMISSION_GRANTED;
3861                }
3862            }
3863        }
3864
3865        return PackageManager.PERMISSION_DENIED;
3866    }
3867
3868    @Override
3869    public int checkUidPermission(String permName, int uid) {
3870        final int userId = UserHandle.getUserId(uid);
3871
3872        if (!sUserManager.exists(userId)) {
3873            return PackageManager.PERMISSION_DENIED;
3874        }
3875
3876        synchronized (mPackages) {
3877            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3878            if (obj != null) {
3879                final SettingBase ps = (SettingBase) obj;
3880                final PermissionsState permissionsState = ps.getPermissionsState();
3881                if (permissionsState.hasPermission(permName, userId)) {
3882                    return PackageManager.PERMISSION_GRANTED;
3883                }
3884                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3885                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3886                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3887                    return PackageManager.PERMISSION_GRANTED;
3888                }
3889            } else {
3890                ArraySet<String> perms = mSystemPermissions.get(uid);
3891                if (perms != null) {
3892                    if (perms.contains(permName)) {
3893                        return PackageManager.PERMISSION_GRANTED;
3894                    }
3895                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3896                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3897                        return PackageManager.PERMISSION_GRANTED;
3898                    }
3899                }
3900            }
3901        }
3902
3903        return PackageManager.PERMISSION_DENIED;
3904    }
3905
3906    @Override
3907    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3908        if (UserHandle.getCallingUserId() != userId) {
3909            mContext.enforceCallingPermission(
3910                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3911                    "isPermissionRevokedByPolicy for user " + userId);
3912        }
3913
3914        if (checkPermission(permission, packageName, userId)
3915                == PackageManager.PERMISSION_GRANTED) {
3916            return false;
3917        }
3918
3919        final long identity = Binder.clearCallingIdentity();
3920        try {
3921            final int flags = getPermissionFlags(permission, packageName, userId);
3922            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3923        } finally {
3924            Binder.restoreCallingIdentity(identity);
3925        }
3926    }
3927
3928    @Override
3929    public String getPermissionControllerPackageName() {
3930        synchronized (mPackages) {
3931            return mRequiredInstallerPackage;
3932        }
3933    }
3934
3935    /**
3936     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3937     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3938     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3939     * @param message the message to log on security exception
3940     */
3941    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3942            boolean checkShell, String message) {
3943        if (userId < 0) {
3944            throw new IllegalArgumentException("Invalid userId " + userId);
3945        }
3946        if (checkShell) {
3947            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3948        }
3949        if (userId == UserHandle.getUserId(callingUid)) return;
3950        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3951            if (requireFullPermission) {
3952                mContext.enforceCallingOrSelfPermission(
3953                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3954            } else {
3955                try {
3956                    mContext.enforceCallingOrSelfPermission(
3957                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3958                } catch (SecurityException se) {
3959                    mContext.enforceCallingOrSelfPermission(
3960                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3961                }
3962            }
3963        }
3964    }
3965
3966    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3967        if (callingUid == Process.SHELL_UID) {
3968            if (userHandle >= 0
3969                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3970                throw new SecurityException("Shell does not have permission to access user "
3971                        + userHandle);
3972            } else if (userHandle < 0) {
3973                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3974                        + Debug.getCallers(3));
3975            }
3976        }
3977    }
3978
3979    private BasePermission findPermissionTreeLP(String permName) {
3980        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3981            if (permName.startsWith(bp.name) &&
3982                    permName.length() > bp.name.length() &&
3983                    permName.charAt(bp.name.length()) == '.') {
3984                return bp;
3985            }
3986        }
3987        return null;
3988    }
3989
3990    private BasePermission checkPermissionTreeLP(String permName) {
3991        if (permName != null) {
3992            BasePermission bp = findPermissionTreeLP(permName);
3993            if (bp != null) {
3994                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3995                    return bp;
3996                }
3997                throw new SecurityException("Calling uid "
3998                        + Binder.getCallingUid()
3999                        + " is not allowed to add to permission tree "
4000                        + bp.name + " owned by uid " + bp.uid);
4001            }
4002        }
4003        throw new SecurityException("No permission tree found for " + permName);
4004    }
4005
4006    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4007        if (s1 == null) {
4008            return s2 == null;
4009        }
4010        if (s2 == null) {
4011            return false;
4012        }
4013        if (s1.getClass() != s2.getClass()) {
4014            return false;
4015        }
4016        return s1.equals(s2);
4017    }
4018
4019    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4020        if (pi1.icon != pi2.icon) return false;
4021        if (pi1.logo != pi2.logo) return false;
4022        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4023        if (!compareStrings(pi1.name, pi2.name)) return false;
4024        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4025        // We'll take care of setting this one.
4026        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4027        // These are not currently stored in settings.
4028        //if (!compareStrings(pi1.group, pi2.group)) return false;
4029        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4030        //if (pi1.labelRes != pi2.labelRes) return false;
4031        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4032        return true;
4033    }
4034
4035    int permissionInfoFootprint(PermissionInfo info) {
4036        int size = info.name.length();
4037        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4038        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4039        return size;
4040    }
4041
4042    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4043        int size = 0;
4044        for (BasePermission perm : mSettings.mPermissions.values()) {
4045            if (perm.uid == tree.uid) {
4046                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4047            }
4048        }
4049        return size;
4050    }
4051
4052    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4053        // We calculate the max size of permissions defined by this uid and throw
4054        // if that plus the size of 'info' would exceed our stated maximum.
4055        if (tree.uid != Process.SYSTEM_UID) {
4056            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4057            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4058                throw new SecurityException("Permission tree size cap exceeded");
4059            }
4060        }
4061    }
4062
4063    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4064        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4065            throw new SecurityException("Label must be specified in permission");
4066        }
4067        BasePermission tree = checkPermissionTreeLP(info.name);
4068        BasePermission bp = mSettings.mPermissions.get(info.name);
4069        boolean added = bp == null;
4070        boolean changed = true;
4071        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4072        if (added) {
4073            enforcePermissionCapLocked(info, tree);
4074            bp = new BasePermission(info.name, tree.sourcePackage,
4075                    BasePermission.TYPE_DYNAMIC);
4076        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4077            throw new SecurityException(
4078                    "Not allowed to modify non-dynamic permission "
4079                    + info.name);
4080        } else {
4081            if (bp.protectionLevel == fixedLevel
4082                    && bp.perm.owner.equals(tree.perm.owner)
4083                    && bp.uid == tree.uid
4084                    && comparePermissionInfos(bp.perm.info, info)) {
4085                changed = false;
4086            }
4087        }
4088        bp.protectionLevel = fixedLevel;
4089        info = new PermissionInfo(info);
4090        info.protectionLevel = fixedLevel;
4091        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4092        bp.perm.info.packageName = tree.perm.info.packageName;
4093        bp.uid = tree.uid;
4094        if (added) {
4095            mSettings.mPermissions.put(info.name, bp);
4096        }
4097        if (changed) {
4098            if (!async) {
4099                mSettings.writeLPr();
4100            } else {
4101                scheduleWriteSettingsLocked();
4102            }
4103        }
4104        return added;
4105    }
4106
4107    @Override
4108    public boolean addPermission(PermissionInfo info) {
4109        synchronized (mPackages) {
4110            return addPermissionLocked(info, false);
4111        }
4112    }
4113
4114    @Override
4115    public boolean addPermissionAsync(PermissionInfo info) {
4116        synchronized (mPackages) {
4117            return addPermissionLocked(info, true);
4118        }
4119    }
4120
4121    @Override
4122    public void removePermission(String name) {
4123        synchronized (mPackages) {
4124            checkPermissionTreeLP(name);
4125            BasePermission bp = mSettings.mPermissions.get(name);
4126            if (bp != null) {
4127                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4128                    throw new SecurityException(
4129                            "Not allowed to modify non-dynamic permission "
4130                            + name);
4131                }
4132                mSettings.mPermissions.remove(name);
4133                mSettings.writeLPr();
4134            }
4135        }
4136    }
4137
4138    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4139            BasePermission bp) {
4140        int index = pkg.requestedPermissions.indexOf(bp.name);
4141        if (index == -1) {
4142            throw new SecurityException("Package " + pkg.packageName
4143                    + " has not requested permission " + bp.name);
4144        }
4145        if (!bp.isRuntime() && !bp.isDevelopment()) {
4146            throw new SecurityException("Permission " + bp.name
4147                    + " is not a changeable permission type");
4148        }
4149    }
4150
4151    @Override
4152    public void grantRuntimePermission(String packageName, String name, final int userId) {
4153        if (!sUserManager.exists(userId)) {
4154            Log.e(TAG, "No such user:" + userId);
4155            return;
4156        }
4157
4158        mContext.enforceCallingOrSelfPermission(
4159                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4160                "grantRuntimePermission");
4161
4162        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4163                true /* requireFullPermission */, true /* checkShell */,
4164                "grantRuntimePermission");
4165
4166        final int uid;
4167        final SettingBase sb;
4168
4169        synchronized (mPackages) {
4170            final PackageParser.Package pkg = mPackages.get(packageName);
4171            if (pkg == null) {
4172                throw new IllegalArgumentException("Unknown package: " + packageName);
4173            }
4174
4175            final BasePermission bp = mSettings.mPermissions.get(name);
4176            if (bp == null) {
4177                throw new IllegalArgumentException("Unknown permission: " + name);
4178            }
4179
4180            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4181
4182            // If a permission review is required for legacy apps we represent
4183            // their permissions as always granted runtime ones since we need
4184            // to keep the review required permission flag per user while an
4185            // install permission's state is shared across all users.
4186            if (Build.PERMISSIONS_REVIEW_REQUIRED
4187                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4188                    && bp.isRuntime()) {
4189                return;
4190            }
4191
4192            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4193            sb = (SettingBase) pkg.mExtras;
4194            if (sb == null) {
4195                throw new IllegalArgumentException("Unknown package: " + packageName);
4196            }
4197
4198            final PermissionsState permissionsState = sb.getPermissionsState();
4199
4200            final int flags = permissionsState.getPermissionFlags(name, userId);
4201            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4202                throw new SecurityException("Cannot grant system fixed permission "
4203                        + name + " for package " + packageName);
4204            }
4205
4206            if (bp.isDevelopment()) {
4207                // Development permissions must be handled specially, since they are not
4208                // normal runtime permissions.  For now they apply to all users.
4209                if (permissionsState.grantInstallPermission(bp) !=
4210                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4211                    scheduleWriteSettingsLocked();
4212                }
4213                return;
4214            }
4215
4216            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4217                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4218                return;
4219            }
4220
4221            final int result = permissionsState.grantRuntimePermission(bp, userId);
4222            switch (result) {
4223                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4224                    return;
4225                }
4226
4227                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4228                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4229                    mHandler.post(new Runnable() {
4230                        @Override
4231                        public void run() {
4232                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4233                        }
4234                    });
4235                }
4236                break;
4237            }
4238
4239            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4240
4241            // Not critical if that is lost - app has to request again.
4242            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4243        }
4244
4245        // Only need to do this if user is initialized. Otherwise it's a new user
4246        // and there are no processes running as the user yet and there's no need
4247        // to make an expensive call to remount processes for the changed permissions.
4248        if (READ_EXTERNAL_STORAGE.equals(name)
4249                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4250            final long token = Binder.clearCallingIdentity();
4251            try {
4252                if (sUserManager.isInitialized(userId)) {
4253                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4254                            MountServiceInternal.class);
4255                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4256                }
4257            } finally {
4258                Binder.restoreCallingIdentity(token);
4259            }
4260        }
4261    }
4262
4263    @Override
4264    public void revokeRuntimePermission(String packageName, String name, int userId) {
4265        if (!sUserManager.exists(userId)) {
4266            Log.e(TAG, "No such user:" + userId);
4267            return;
4268        }
4269
4270        mContext.enforceCallingOrSelfPermission(
4271                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4272                "revokeRuntimePermission");
4273
4274        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4275                true /* requireFullPermission */, true /* checkShell */,
4276                "revokeRuntimePermission");
4277
4278        final int appId;
4279
4280        synchronized (mPackages) {
4281            final PackageParser.Package pkg = mPackages.get(packageName);
4282            if (pkg == null) {
4283                throw new IllegalArgumentException("Unknown package: " + packageName);
4284            }
4285
4286            final BasePermission bp = mSettings.mPermissions.get(name);
4287            if (bp == null) {
4288                throw new IllegalArgumentException("Unknown permission: " + name);
4289            }
4290
4291            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4292
4293            // If a permission review is required for legacy apps we represent
4294            // their permissions as always granted runtime ones since we need
4295            // to keep the review required permission flag per user while an
4296            // install permission's state is shared across all users.
4297            if (Build.PERMISSIONS_REVIEW_REQUIRED
4298                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4299                    && bp.isRuntime()) {
4300                return;
4301            }
4302
4303            SettingBase sb = (SettingBase) pkg.mExtras;
4304            if (sb == null) {
4305                throw new IllegalArgumentException("Unknown package: " + packageName);
4306            }
4307
4308            final PermissionsState permissionsState = sb.getPermissionsState();
4309
4310            final int flags = permissionsState.getPermissionFlags(name, userId);
4311            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4312                throw new SecurityException("Cannot revoke system fixed permission "
4313                        + name + " for package " + packageName);
4314            }
4315
4316            if (bp.isDevelopment()) {
4317                // Development permissions must be handled specially, since they are not
4318                // normal runtime permissions.  For now they apply to all users.
4319                if (permissionsState.revokeInstallPermission(bp) !=
4320                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4321                    scheduleWriteSettingsLocked();
4322                }
4323                return;
4324            }
4325
4326            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4327                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4328                return;
4329            }
4330
4331            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4332
4333            // Critical, after this call app should never have the permission.
4334            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4335
4336            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4337        }
4338
4339        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4340    }
4341
4342    @Override
4343    public void resetRuntimePermissions() {
4344        mContext.enforceCallingOrSelfPermission(
4345                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4346                "revokeRuntimePermission");
4347
4348        int callingUid = Binder.getCallingUid();
4349        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4350            mContext.enforceCallingOrSelfPermission(
4351                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4352                    "resetRuntimePermissions");
4353        }
4354
4355        synchronized (mPackages) {
4356            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4357            for (int userId : UserManagerService.getInstance().getUserIds()) {
4358                final int packageCount = mPackages.size();
4359                for (int i = 0; i < packageCount; i++) {
4360                    PackageParser.Package pkg = mPackages.valueAt(i);
4361                    if (!(pkg.mExtras instanceof PackageSetting)) {
4362                        continue;
4363                    }
4364                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4365                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4366                }
4367            }
4368        }
4369    }
4370
4371    @Override
4372    public int getPermissionFlags(String name, String packageName, int userId) {
4373        if (!sUserManager.exists(userId)) {
4374            return 0;
4375        }
4376
4377        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4378
4379        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4380                true /* requireFullPermission */, false /* checkShell */,
4381                "getPermissionFlags");
4382
4383        synchronized (mPackages) {
4384            final PackageParser.Package pkg = mPackages.get(packageName);
4385            if (pkg == null) {
4386                return 0;
4387            }
4388
4389            final BasePermission bp = mSettings.mPermissions.get(name);
4390            if (bp == null) {
4391                return 0;
4392            }
4393
4394            SettingBase sb = (SettingBase) pkg.mExtras;
4395            if (sb == null) {
4396                return 0;
4397            }
4398
4399            PermissionsState permissionsState = sb.getPermissionsState();
4400            return permissionsState.getPermissionFlags(name, userId);
4401        }
4402    }
4403
4404    @Override
4405    public void updatePermissionFlags(String name, String packageName, int flagMask,
4406            int flagValues, int userId) {
4407        if (!sUserManager.exists(userId)) {
4408            return;
4409        }
4410
4411        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4412
4413        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4414                true /* requireFullPermission */, true /* checkShell */,
4415                "updatePermissionFlags");
4416
4417        // Only the system can change these flags and nothing else.
4418        if (getCallingUid() != Process.SYSTEM_UID) {
4419            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4420            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4421            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4422            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4423            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4424        }
4425
4426        synchronized (mPackages) {
4427            final PackageParser.Package pkg = mPackages.get(packageName);
4428            if (pkg == null) {
4429                throw new IllegalArgumentException("Unknown package: " + packageName);
4430            }
4431
4432            final BasePermission bp = mSettings.mPermissions.get(name);
4433            if (bp == null) {
4434                throw new IllegalArgumentException("Unknown permission: " + name);
4435            }
4436
4437            SettingBase sb = (SettingBase) pkg.mExtras;
4438            if (sb == null) {
4439                throw new IllegalArgumentException("Unknown package: " + packageName);
4440            }
4441
4442            PermissionsState permissionsState = sb.getPermissionsState();
4443
4444            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4445
4446            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4447                // Install and runtime permissions are stored in different places,
4448                // so figure out what permission changed and persist the change.
4449                if (permissionsState.getInstallPermissionState(name) != null) {
4450                    scheduleWriteSettingsLocked();
4451                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4452                        || hadState) {
4453                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4454                }
4455            }
4456        }
4457    }
4458
4459    /**
4460     * Update the permission flags for all packages and runtime permissions of a user in order
4461     * to allow device or profile owner to remove POLICY_FIXED.
4462     */
4463    @Override
4464    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4465        if (!sUserManager.exists(userId)) {
4466            return;
4467        }
4468
4469        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4470
4471        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4472                true /* requireFullPermission */, true /* checkShell */,
4473                "updatePermissionFlagsForAllApps");
4474
4475        // Only the system can change system fixed flags.
4476        if (getCallingUid() != Process.SYSTEM_UID) {
4477            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4478            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4479        }
4480
4481        synchronized (mPackages) {
4482            boolean changed = false;
4483            final int packageCount = mPackages.size();
4484            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4485                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4486                SettingBase sb = (SettingBase) pkg.mExtras;
4487                if (sb == null) {
4488                    continue;
4489                }
4490                PermissionsState permissionsState = sb.getPermissionsState();
4491                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4492                        userId, flagMask, flagValues);
4493            }
4494            if (changed) {
4495                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4496            }
4497        }
4498    }
4499
4500    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4501        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4502                != PackageManager.PERMISSION_GRANTED
4503            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4504                != PackageManager.PERMISSION_GRANTED) {
4505            throw new SecurityException(message + " requires "
4506                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4507                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4508        }
4509    }
4510
4511    @Override
4512    public boolean shouldShowRequestPermissionRationale(String permissionName,
4513            String packageName, int userId) {
4514        if (UserHandle.getCallingUserId() != userId) {
4515            mContext.enforceCallingPermission(
4516                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4517                    "canShowRequestPermissionRationale for user " + userId);
4518        }
4519
4520        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4521        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4522            return false;
4523        }
4524
4525        if (checkPermission(permissionName, packageName, userId)
4526                == PackageManager.PERMISSION_GRANTED) {
4527            return false;
4528        }
4529
4530        final int flags;
4531
4532        final long identity = Binder.clearCallingIdentity();
4533        try {
4534            flags = getPermissionFlags(permissionName,
4535                    packageName, userId);
4536        } finally {
4537            Binder.restoreCallingIdentity(identity);
4538        }
4539
4540        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4541                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4542                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4543
4544        if ((flags & fixedFlags) != 0) {
4545            return false;
4546        }
4547
4548        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4549    }
4550
4551    @Override
4552    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4553        mContext.enforceCallingOrSelfPermission(
4554                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4555                "addOnPermissionsChangeListener");
4556
4557        synchronized (mPackages) {
4558            mOnPermissionChangeListeners.addListenerLocked(listener);
4559        }
4560    }
4561
4562    @Override
4563    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4564        synchronized (mPackages) {
4565            mOnPermissionChangeListeners.removeListenerLocked(listener);
4566        }
4567    }
4568
4569    @Override
4570    public boolean isProtectedBroadcast(String actionName) {
4571        synchronized (mPackages) {
4572            if (mProtectedBroadcasts.contains(actionName)) {
4573                return true;
4574            } else if (actionName != null) {
4575                // TODO: remove these terrible hacks
4576                if (actionName.startsWith("android.net.netmon.lingerExpired")
4577                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4578                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4579                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4580                    return true;
4581                }
4582            }
4583        }
4584        return false;
4585    }
4586
4587    @Override
4588    public int checkSignatures(String pkg1, String pkg2) {
4589        synchronized (mPackages) {
4590            final PackageParser.Package p1 = mPackages.get(pkg1);
4591            final PackageParser.Package p2 = mPackages.get(pkg2);
4592            if (p1 == null || p1.mExtras == null
4593                    || p2 == null || p2.mExtras == null) {
4594                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4595            }
4596            return compareSignatures(p1.mSignatures, p2.mSignatures);
4597        }
4598    }
4599
4600    @Override
4601    public int checkUidSignatures(int uid1, int uid2) {
4602        // Map to base uids.
4603        uid1 = UserHandle.getAppId(uid1);
4604        uid2 = UserHandle.getAppId(uid2);
4605        // reader
4606        synchronized (mPackages) {
4607            Signature[] s1;
4608            Signature[] s2;
4609            Object obj = mSettings.getUserIdLPr(uid1);
4610            if (obj != null) {
4611                if (obj instanceof SharedUserSetting) {
4612                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4613                } else if (obj instanceof PackageSetting) {
4614                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4615                } else {
4616                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4617                }
4618            } else {
4619                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4620            }
4621            obj = mSettings.getUserIdLPr(uid2);
4622            if (obj != null) {
4623                if (obj instanceof SharedUserSetting) {
4624                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4625                } else if (obj instanceof PackageSetting) {
4626                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4627                } else {
4628                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4629                }
4630            } else {
4631                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4632            }
4633            return compareSignatures(s1, s2);
4634        }
4635    }
4636
4637    /**
4638     * This method should typically only be used when granting or revoking
4639     * permissions, since the app may immediately restart after this call.
4640     * <p>
4641     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4642     * guard your work against the app being relaunched.
4643     */
4644    private void killUid(int appId, int userId, String reason) {
4645        final long identity = Binder.clearCallingIdentity();
4646        try {
4647            IActivityManager am = ActivityManagerNative.getDefault();
4648            if (am != null) {
4649                try {
4650                    am.killUid(appId, userId, reason);
4651                } catch (RemoteException e) {
4652                    /* ignore - same process */
4653                }
4654            }
4655        } finally {
4656            Binder.restoreCallingIdentity(identity);
4657        }
4658    }
4659
4660    /**
4661     * Compares two sets of signatures. Returns:
4662     * <br />
4663     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4664     * <br />
4665     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4666     * <br />
4667     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4668     * <br />
4669     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4670     * <br />
4671     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4672     */
4673    static int compareSignatures(Signature[] s1, Signature[] s2) {
4674        if (s1 == null) {
4675            return s2 == null
4676                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4677                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4678        }
4679
4680        if (s2 == null) {
4681            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4682        }
4683
4684        if (s1.length != s2.length) {
4685            return PackageManager.SIGNATURE_NO_MATCH;
4686        }
4687
4688        // Since both signature sets are of size 1, we can compare without HashSets.
4689        if (s1.length == 1) {
4690            return s1[0].equals(s2[0]) ?
4691                    PackageManager.SIGNATURE_MATCH :
4692                    PackageManager.SIGNATURE_NO_MATCH;
4693        }
4694
4695        ArraySet<Signature> set1 = new ArraySet<Signature>();
4696        for (Signature sig : s1) {
4697            set1.add(sig);
4698        }
4699        ArraySet<Signature> set2 = new ArraySet<Signature>();
4700        for (Signature sig : s2) {
4701            set2.add(sig);
4702        }
4703        // Make sure s2 contains all signatures in s1.
4704        if (set1.equals(set2)) {
4705            return PackageManager.SIGNATURE_MATCH;
4706        }
4707        return PackageManager.SIGNATURE_NO_MATCH;
4708    }
4709
4710    /**
4711     * If the database version for this type of package (internal storage or
4712     * external storage) is less than the version where package signatures
4713     * were updated, return true.
4714     */
4715    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4716        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4717        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4718    }
4719
4720    /**
4721     * Used for backward compatibility to make sure any packages with
4722     * certificate chains get upgraded to the new style. {@code existingSigs}
4723     * will be in the old format (since they were stored on disk from before the
4724     * system upgrade) and {@code scannedSigs} will be in the newer format.
4725     */
4726    private int compareSignaturesCompat(PackageSignatures existingSigs,
4727            PackageParser.Package scannedPkg) {
4728        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4729            return PackageManager.SIGNATURE_NO_MATCH;
4730        }
4731
4732        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4733        for (Signature sig : existingSigs.mSignatures) {
4734            existingSet.add(sig);
4735        }
4736        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4737        for (Signature sig : scannedPkg.mSignatures) {
4738            try {
4739                Signature[] chainSignatures = sig.getChainSignatures();
4740                for (Signature chainSig : chainSignatures) {
4741                    scannedCompatSet.add(chainSig);
4742                }
4743            } catch (CertificateEncodingException e) {
4744                scannedCompatSet.add(sig);
4745            }
4746        }
4747        /*
4748         * Make sure the expanded scanned set contains all signatures in the
4749         * existing one.
4750         */
4751        if (scannedCompatSet.equals(existingSet)) {
4752            // Migrate the old signatures to the new scheme.
4753            existingSigs.assignSignatures(scannedPkg.mSignatures);
4754            // The new KeySets will be re-added later in the scanning process.
4755            synchronized (mPackages) {
4756                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4757            }
4758            return PackageManager.SIGNATURE_MATCH;
4759        }
4760        return PackageManager.SIGNATURE_NO_MATCH;
4761    }
4762
4763    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4764        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4765        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4766    }
4767
4768    private int compareSignaturesRecover(PackageSignatures existingSigs,
4769            PackageParser.Package scannedPkg) {
4770        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4771            return PackageManager.SIGNATURE_NO_MATCH;
4772        }
4773
4774        String msg = null;
4775        try {
4776            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4777                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4778                        + scannedPkg.packageName);
4779                return PackageManager.SIGNATURE_MATCH;
4780            }
4781        } catch (CertificateException e) {
4782            msg = e.getMessage();
4783        }
4784
4785        logCriticalInfo(Log.INFO,
4786                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4787        return PackageManager.SIGNATURE_NO_MATCH;
4788    }
4789
4790    @Override
4791    public List<String> getAllPackages() {
4792        synchronized (mPackages) {
4793            return new ArrayList<String>(mPackages.keySet());
4794        }
4795    }
4796
4797    @Override
4798    public String[] getPackagesForUid(int uid) {
4799        uid = UserHandle.getAppId(uid);
4800        // reader
4801        synchronized (mPackages) {
4802            Object obj = mSettings.getUserIdLPr(uid);
4803            if (obj instanceof SharedUserSetting) {
4804                final SharedUserSetting sus = (SharedUserSetting) obj;
4805                final int N = sus.packages.size();
4806                final String[] res = new String[N];
4807                for (int i = 0; i < N; i++) {
4808                    res[i] = sus.packages.valueAt(i).name;
4809                }
4810                return res;
4811            } else if (obj instanceof PackageSetting) {
4812                final PackageSetting ps = (PackageSetting) obj;
4813                return new String[] { ps.name };
4814            }
4815        }
4816        return null;
4817    }
4818
4819    @Override
4820    public String getNameForUid(int uid) {
4821        // reader
4822        synchronized (mPackages) {
4823            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4824            if (obj instanceof SharedUserSetting) {
4825                final SharedUserSetting sus = (SharedUserSetting) obj;
4826                return sus.name + ":" + sus.userId;
4827            } else if (obj instanceof PackageSetting) {
4828                final PackageSetting ps = (PackageSetting) obj;
4829                return ps.name;
4830            }
4831        }
4832        return null;
4833    }
4834
4835    @Override
4836    public int getUidForSharedUser(String sharedUserName) {
4837        if(sharedUserName == null) {
4838            return -1;
4839        }
4840        // reader
4841        synchronized (mPackages) {
4842            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4843            if (suid == null) {
4844                return -1;
4845            }
4846            return suid.userId;
4847        }
4848    }
4849
4850    @Override
4851    public int getFlagsForUid(int uid) {
4852        synchronized (mPackages) {
4853            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4854            if (obj instanceof SharedUserSetting) {
4855                final SharedUserSetting sus = (SharedUserSetting) obj;
4856                return sus.pkgFlags;
4857            } else if (obj instanceof PackageSetting) {
4858                final PackageSetting ps = (PackageSetting) obj;
4859                return ps.pkgFlags;
4860            }
4861        }
4862        return 0;
4863    }
4864
4865    @Override
4866    public int getPrivateFlagsForUid(int uid) {
4867        synchronized (mPackages) {
4868            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4869            if (obj instanceof SharedUserSetting) {
4870                final SharedUserSetting sus = (SharedUserSetting) obj;
4871                return sus.pkgPrivateFlags;
4872            } else if (obj instanceof PackageSetting) {
4873                final PackageSetting ps = (PackageSetting) obj;
4874                return ps.pkgPrivateFlags;
4875            }
4876        }
4877        return 0;
4878    }
4879
4880    @Override
4881    public boolean isUidPrivileged(int uid) {
4882        uid = UserHandle.getAppId(uid);
4883        // reader
4884        synchronized (mPackages) {
4885            Object obj = mSettings.getUserIdLPr(uid);
4886            if (obj instanceof SharedUserSetting) {
4887                final SharedUserSetting sus = (SharedUserSetting) obj;
4888                final Iterator<PackageSetting> it = sus.packages.iterator();
4889                while (it.hasNext()) {
4890                    if (it.next().isPrivileged()) {
4891                        return true;
4892                    }
4893                }
4894            } else if (obj instanceof PackageSetting) {
4895                final PackageSetting ps = (PackageSetting) obj;
4896                return ps.isPrivileged();
4897            }
4898        }
4899        return false;
4900    }
4901
4902    @Override
4903    public String[] getAppOpPermissionPackages(String permissionName) {
4904        synchronized (mPackages) {
4905            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4906            if (pkgs == null) {
4907                return null;
4908            }
4909            return pkgs.toArray(new String[pkgs.size()]);
4910        }
4911    }
4912
4913    @Override
4914    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4915            int flags, int userId) {
4916        try {
4917            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4918
4919            if (!sUserManager.exists(userId)) return null;
4920            flags = updateFlagsForResolve(flags, userId, intent);
4921            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4922                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4923
4924            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4925            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4926                    flags, userId);
4927            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4928
4929            final ResolveInfo bestChoice =
4930                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4931
4932            if (isEphemeralAllowed(intent, query, userId)) {
4933                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4934                final EphemeralResolveInfo ai =
4935                        getEphemeralResolveInfo(intent, resolvedType, userId);
4936                if (ai != null) {
4937                    if (DEBUG_EPHEMERAL) {
4938                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4939                    }
4940                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4941                    bestChoice.ephemeralResolveInfo = ai;
4942                }
4943                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4944            }
4945            return bestChoice;
4946        } finally {
4947            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4948        }
4949    }
4950
4951    @Override
4952    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4953            IntentFilter filter, int match, ComponentName activity) {
4954        final int userId = UserHandle.getCallingUserId();
4955        if (DEBUG_PREFERRED) {
4956            Log.v(TAG, "setLastChosenActivity intent=" + intent
4957                + " resolvedType=" + resolvedType
4958                + " flags=" + flags
4959                + " filter=" + filter
4960                + " match=" + match
4961                + " activity=" + activity);
4962            filter.dump(new PrintStreamPrinter(System.out), "    ");
4963        }
4964        intent.setComponent(null);
4965        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4966                userId);
4967        // Find any earlier preferred or last chosen entries and nuke them
4968        findPreferredActivity(intent, resolvedType,
4969                flags, query, 0, false, true, false, userId);
4970        // Add the new activity as the last chosen for this filter
4971        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4972                "Setting last chosen");
4973    }
4974
4975    @Override
4976    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4977        final int userId = UserHandle.getCallingUserId();
4978        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4979        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4980                userId);
4981        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4982                false, false, false, userId);
4983    }
4984
4985
4986    private boolean isEphemeralAllowed(
4987            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4988        // Short circuit and return early if possible.
4989        if (DISABLE_EPHEMERAL_APPS) {
4990            return false;
4991        }
4992        final int callingUser = UserHandle.getCallingUserId();
4993        if (callingUser != UserHandle.USER_SYSTEM) {
4994            return false;
4995        }
4996        if (mEphemeralResolverConnection == null) {
4997            return false;
4998        }
4999        if (intent.getComponent() != null) {
5000            return false;
5001        }
5002        if (intent.getPackage() != null) {
5003            return false;
5004        }
5005        final boolean isWebUri = hasWebURI(intent);
5006        if (!isWebUri) {
5007            return false;
5008        }
5009        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5010        synchronized (mPackages) {
5011            final int count = resolvedActivites.size();
5012            for (int n = 0; n < count; n++) {
5013                ResolveInfo info = resolvedActivites.get(n);
5014                String packageName = info.activityInfo.packageName;
5015                PackageSetting ps = mSettings.mPackages.get(packageName);
5016                if (ps != null) {
5017                    // Try to get the status from User settings first
5018                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5019                    int status = (int) (packedStatus >> 32);
5020                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5021                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5022                        if (DEBUG_EPHEMERAL) {
5023                            Slog.v(TAG, "DENY ephemeral apps;"
5024                                + " pkg: " + packageName + ", status: " + status);
5025                        }
5026                        return false;
5027                    }
5028                }
5029            }
5030        }
5031        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5032        return true;
5033    }
5034
5035    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
5036            int userId) {
5037        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
5038                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
5039        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
5040                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
5041        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
5042                ephemeralPrefixCount);
5043        final int[] shaPrefix = digest.getDigestPrefix();
5044        final byte[][] digestBytes = digest.getDigestBytes();
5045        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5046                mEphemeralResolverConnection.getEphemeralResolveInfoList(
5047                        shaPrefix, ephemeralPrefixMask);
5048        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5049            // No hash prefix match; there are no ephemeral apps for this domain.
5050            return null;
5051        }
5052
5053        // Go in reverse order so we match the narrowest scope first.
5054        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
5055            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
5056                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
5057                    continue;
5058                }
5059                final List<IntentFilter> filters = ephemeralApplication.getFilters();
5060                // No filters; this should never happen.
5061                if (filters.isEmpty()) {
5062                    continue;
5063                }
5064                // We have a domain match; resolve the filters to see if anything matches.
5065                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5066                for (int j = filters.size() - 1; j >= 0; --j) {
5067                    final EphemeralResolveIntentInfo intentInfo =
5068                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5069                    ephemeralResolver.addFilter(intentInfo);
5070                }
5071                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5072                        intent, resolvedType, false /*defaultOnly*/, userId);
5073                if (!matchedResolveInfoList.isEmpty()) {
5074                    return matchedResolveInfoList.get(0);
5075                }
5076            }
5077        }
5078        // Hash or filter mis-match; no ephemeral apps for this domain.
5079        return null;
5080    }
5081
5082    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5083            int flags, List<ResolveInfo> query, int userId) {
5084        if (query != null) {
5085            final int N = query.size();
5086            if (N == 1) {
5087                return query.get(0);
5088            } else if (N > 1) {
5089                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5090                // If there is more than one activity with the same priority,
5091                // then let the user decide between them.
5092                ResolveInfo r0 = query.get(0);
5093                ResolveInfo r1 = query.get(1);
5094                if (DEBUG_INTENT_MATCHING || debug) {
5095                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5096                            + r1.activityInfo.name + "=" + r1.priority);
5097                }
5098                // If the first activity has a higher priority, or a different
5099                // default, then it is always desirable to pick it.
5100                if (r0.priority != r1.priority
5101                        || r0.preferredOrder != r1.preferredOrder
5102                        || r0.isDefault != r1.isDefault) {
5103                    return query.get(0);
5104                }
5105                // If we have saved a preference for a preferred activity for
5106                // this Intent, use that.
5107                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5108                        flags, query, r0.priority, true, false, debug, userId);
5109                if (ri != null) {
5110                    return ri;
5111                }
5112                ri = new ResolveInfo(mResolveInfo);
5113                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5114                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5115                // If all of the options come from the same package, show the application's
5116                // label and icon instead of the generic resolver's.
5117                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5118                // and then throw away the ResolveInfo itself, meaning that the caller loses
5119                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5120                // a fallback for this case; we only set the target package's resources on
5121                // the ResolveInfo, not the ActivityInfo.
5122                final String intentPackage = intent.getPackage();
5123                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5124                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5125                    ri.resolvePackageName = intentPackage;
5126                    if (userNeedsBadging(userId)) {
5127                        ri.noResourceId = true;
5128                    } else {
5129                        ri.icon = appi.icon;
5130                    }
5131                    ri.iconResourceId = appi.icon;
5132                    ri.labelRes = appi.labelRes;
5133                }
5134                ri.activityInfo.applicationInfo = new ApplicationInfo(
5135                        ri.activityInfo.applicationInfo);
5136                if (userId != 0) {
5137                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5138                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5139                }
5140                // Make sure that the resolver is displayable in car mode
5141                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5142                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5143                return ri;
5144            }
5145        }
5146        return null;
5147    }
5148
5149    /**
5150     * Return true if the given list is not empty and all of its contents have
5151     * an activityInfo with the given package name.
5152     */
5153    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5154        if (ArrayUtils.isEmpty(list)) {
5155            return false;
5156        }
5157        for (int i = 0, N = list.size(); i < N; i++) {
5158            final ResolveInfo ri = list.get(i);
5159            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5160            if (ai == null || !packageName.equals(ai.packageName)) {
5161                return false;
5162            }
5163        }
5164        return true;
5165    }
5166
5167    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5168            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5169        final int N = query.size();
5170        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5171                .get(userId);
5172        // Get the list of persistent preferred activities that handle the intent
5173        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5174        List<PersistentPreferredActivity> pprefs = ppir != null
5175                ? ppir.queryIntent(intent, resolvedType,
5176                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5177                : null;
5178        if (pprefs != null && pprefs.size() > 0) {
5179            final int M = pprefs.size();
5180            for (int i=0; i<M; i++) {
5181                final PersistentPreferredActivity ppa = pprefs.get(i);
5182                if (DEBUG_PREFERRED || debug) {
5183                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5184                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5185                            + "\n  component=" + ppa.mComponent);
5186                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5187                }
5188                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5189                        flags | MATCH_DISABLED_COMPONENTS, userId);
5190                if (DEBUG_PREFERRED || debug) {
5191                    Slog.v(TAG, "Found persistent preferred activity:");
5192                    if (ai != null) {
5193                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5194                    } else {
5195                        Slog.v(TAG, "  null");
5196                    }
5197                }
5198                if (ai == null) {
5199                    // This previously registered persistent preferred activity
5200                    // component is no longer known. Ignore it and do NOT remove it.
5201                    continue;
5202                }
5203                for (int j=0; j<N; j++) {
5204                    final ResolveInfo ri = query.get(j);
5205                    if (!ri.activityInfo.applicationInfo.packageName
5206                            .equals(ai.applicationInfo.packageName)) {
5207                        continue;
5208                    }
5209                    if (!ri.activityInfo.name.equals(ai.name)) {
5210                        continue;
5211                    }
5212                    //  Found a persistent preference that can handle the intent.
5213                    if (DEBUG_PREFERRED || debug) {
5214                        Slog.v(TAG, "Returning persistent preferred activity: " +
5215                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5216                    }
5217                    return ri;
5218                }
5219            }
5220        }
5221        return null;
5222    }
5223
5224    // TODO: handle preferred activities missing while user has amnesia
5225    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5226            List<ResolveInfo> query, int priority, boolean always,
5227            boolean removeMatches, boolean debug, int userId) {
5228        if (!sUserManager.exists(userId)) return null;
5229        flags = updateFlagsForResolve(flags, userId, intent);
5230        // writer
5231        synchronized (mPackages) {
5232            if (intent.getSelector() != null) {
5233                intent = intent.getSelector();
5234            }
5235            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5236
5237            // Try to find a matching persistent preferred activity.
5238            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5239                    debug, userId);
5240
5241            // If a persistent preferred activity matched, use it.
5242            if (pri != null) {
5243                return pri;
5244            }
5245
5246            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5247            // Get the list of preferred activities that handle the intent
5248            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5249            List<PreferredActivity> prefs = pir != null
5250                    ? pir.queryIntent(intent, resolvedType,
5251                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5252                    : null;
5253            if (prefs != null && prefs.size() > 0) {
5254                boolean changed = false;
5255                try {
5256                    // First figure out how good the original match set is.
5257                    // We will only allow preferred activities that came
5258                    // from the same match quality.
5259                    int match = 0;
5260
5261                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5262
5263                    final int N = query.size();
5264                    for (int j=0; j<N; j++) {
5265                        final ResolveInfo ri = query.get(j);
5266                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5267                                + ": 0x" + Integer.toHexString(match));
5268                        if (ri.match > match) {
5269                            match = ri.match;
5270                        }
5271                    }
5272
5273                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5274                            + Integer.toHexString(match));
5275
5276                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5277                    final int M = prefs.size();
5278                    for (int i=0; i<M; i++) {
5279                        final PreferredActivity pa = prefs.get(i);
5280                        if (DEBUG_PREFERRED || debug) {
5281                            Slog.v(TAG, "Checking PreferredActivity ds="
5282                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5283                                    + "\n  component=" + pa.mPref.mComponent);
5284                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5285                        }
5286                        if (pa.mPref.mMatch != match) {
5287                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5288                                    + Integer.toHexString(pa.mPref.mMatch));
5289                            continue;
5290                        }
5291                        // If it's not an "always" type preferred activity and that's what we're
5292                        // looking for, skip it.
5293                        if (always && !pa.mPref.mAlways) {
5294                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5295                            continue;
5296                        }
5297                        final ActivityInfo ai = getActivityInfo(
5298                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5299                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5300                                userId);
5301                        if (DEBUG_PREFERRED || debug) {
5302                            Slog.v(TAG, "Found preferred activity:");
5303                            if (ai != null) {
5304                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5305                            } else {
5306                                Slog.v(TAG, "  null");
5307                            }
5308                        }
5309                        if (ai == null) {
5310                            // This previously registered preferred activity
5311                            // component is no longer known.  Most likely an update
5312                            // to the app was installed and in the new version this
5313                            // component no longer exists.  Clean it up by removing
5314                            // it from the preferred activities list, and skip it.
5315                            Slog.w(TAG, "Removing dangling preferred activity: "
5316                                    + pa.mPref.mComponent);
5317                            pir.removeFilter(pa);
5318                            changed = true;
5319                            continue;
5320                        }
5321                        for (int j=0; j<N; j++) {
5322                            final ResolveInfo ri = query.get(j);
5323                            if (!ri.activityInfo.applicationInfo.packageName
5324                                    .equals(ai.applicationInfo.packageName)) {
5325                                continue;
5326                            }
5327                            if (!ri.activityInfo.name.equals(ai.name)) {
5328                                continue;
5329                            }
5330
5331                            if (removeMatches) {
5332                                pir.removeFilter(pa);
5333                                changed = true;
5334                                if (DEBUG_PREFERRED) {
5335                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5336                                }
5337                                break;
5338                            }
5339
5340                            // Okay we found a previously set preferred or last chosen app.
5341                            // If the result set is different from when this
5342                            // was created, we need to clear it and re-ask the
5343                            // user their preference, if we're looking for an "always" type entry.
5344                            if (always && !pa.mPref.sameSet(query)) {
5345                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5346                                        + intent + " type " + resolvedType);
5347                                if (DEBUG_PREFERRED) {
5348                                    Slog.v(TAG, "Removing preferred activity since set changed "
5349                                            + pa.mPref.mComponent);
5350                                }
5351                                pir.removeFilter(pa);
5352                                // Re-add the filter as a "last chosen" entry (!always)
5353                                PreferredActivity lastChosen = new PreferredActivity(
5354                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5355                                pir.addFilter(lastChosen);
5356                                changed = true;
5357                                return null;
5358                            }
5359
5360                            // Yay! Either the set matched or we're looking for the last chosen
5361                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5362                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5363                            return ri;
5364                        }
5365                    }
5366                } finally {
5367                    if (changed) {
5368                        if (DEBUG_PREFERRED) {
5369                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5370                        }
5371                        scheduleWritePackageRestrictionsLocked(userId);
5372                    }
5373                }
5374            }
5375        }
5376        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5377        return null;
5378    }
5379
5380    /*
5381     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5382     */
5383    @Override
5384    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5385            int targetUserId) {
5386        mContext.enforceCallingOrSelfPermission(
5387                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5388        List<CrossProfileIntentFilter> matches =
5389                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5390        if (matches != null) {
5391            int size = matches.size();
5392            for (int i = 0; i < size; i++) {
5393                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5394            }
5395        }
5396        if (hasWebURI(intent)) {
5397            // cross-profile app linking works only towards the parent.
5398            final UserInfo parent = getProfileParent(sourceUserId);
5399            synchronized(mPackages) {
5400                int flags = updateFlagsForResolve(0, parent.id, intent);
5401                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5402                        intent, resolvedType, flags, sourceUserId, parent.id);
5403                return xpDomainInfo != null;
5404            }
5405        }
5406        return false;
5407    }
5408
5409    private UserInfo getProfileParent(int userId) {
5410        final long identity = Binder.clearCallingIdentity();
5411        try {
5412            return sUserManager.getProfileParent(userId);
5413        } finally {
5414            Binder.restoreCallingIdentity(identity);
5415        }
5416    }
5417
5418    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5419            String resolvedType, int userId) {
5420        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5421        if (resolver != null) {
5422            return resolver.queryIntent(intent, resolvedType, false, userId);
5423        }
5424        return null;
5425    }
5426
5427    @Override
5428    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5429            String resolvedType, int flags, int userId) {
5430        try {
5431            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5432
5433            return new ParceledListSlice<>(
5434                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5435        } finally {
5436            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5437        }
5438    }
5439
5440    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5441            String resolvedType, int flags, int userId) {
5442        if (!sUserManager.exists(userId)) return Collections.emptyList();
5443        flags = updateFlagsForResolve(flags, userId, intent);
5444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5445                false /* requireFullPermission */, false /* checkShell */,
5446                "query intent activities");
5447        ComponentName comp = intent.getComponent();
5448        if (comp == null) {
5449            if (intent.getSelector() != null) {
5450                intent = intent.getSelector();
5451                comp = intent.getComponent();
5452            }
5453        }
5454
5455        if (comp != null) {
5456            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5457            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5458            if (ai != null) {
5459                final ResolveInfo ri = new ResolveInfo();
5460                ri.activityInfo = ai;
5461                list.add(ri);
5462            }
5463            return list;
5464        }
5465
5466        // reader
5467        synchronized (mPackages) {
5468            final String pkgName = intent.getPackage();
5469            if (pkgName == null) {
5470                List<CrossProfileIntentFilter> matchingFilters =
5471                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5472                // Check for results that need to skip the current profile.
5473                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5474                        resolvedType, flags, userId);
5475                if (xpResolveInfo != null) {
5476                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5477                    result.add(xpResolveInfo);
5478                    return filterIfNotSystemUser(result, userId);
5479                }
5480
5481                // Check for results in the current profile.
5482                List<ResolveInfo> result = mActivities.queryIntent(
5483                        intent, resolvedType, flags, userId);
5484                result = filterIfNotSystemUser(result, userId);
5485
5486                // Check for cross profile results.
5487                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5488                xpResolveInfo = queryCrossProfileIntents(
5489                        matchingFilters, intent, resolvedType, flags, userId,
5490                        hasNonNegativePriorityResult);
5491                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5492                    boolean isVisibleToUser = filterIfNotSystemUser(
5493                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5494                    if (isVisibleToUser) {
5495                        result.add(xpResolveInfo);
5496                        Collections.sort(result, mResolvePrioritySorter);
5497                    }
5498                }
5499                if (hasWebURI(intent)) {
5500                    CrossProfileDomainInfo xpDomainInfo = null;
5501                    final UserInfo parent = getProfileParent(userId);
5502                    if (parent != null) {
5503                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5504                                flags, userId, parent.id);
5505                    }
5506                    if (xpDomainInfo != null) {
5507                        if (xpResolveInfo != null) {
5508                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5509                            // in the result.
5510                            result.remove(xpResolveInfo);
5511                        }
5512                        if (result.size() == 0) {
5513                            result.add(xpDomainInfo.resolveInfo);
5514                            return result;
5515                        }
5516                    } else if (result.size() <= 1) {
5517                        return result;
5518                    }
5519                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5520                            xpDomainInfo, userId);
5521                    Collections.sort(result, mResolvePrioritySorter);
5522                }
5523                return result;
5524            }
5525            final PackageParser.Package pkg = mPackages.get(pkgName);
5526            if (pkg != null) {
5527                return filterIfNotSystemUser(
5528                        mActivities.queryIntentForPackage(
5529                                intent, resolvedType, flags, pkg.activities, userId),
5530                        userId);
5531            }
5532            return new ArrayList<ResolveInfo>();
5533        }
5534    }
5535
5536    private static class CrossProfileDomainInfo {
5537        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5538        ResolveInfo resolveInfo;
5539        /* Best domain verification status of the activities found in the other profile */
5540        int bestDomainVerificationStatus;
5541    }
5542
5543    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5544            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5545        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5546                sourceUserId)) {
5547            return null;
5548        }
5549        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5550                resolvedType, flags, parentUserId);
5551
5552        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5553            return null;
5554        }
5555        CrossProfileDomainInfo result = null;
5556        int size = resultTargetUser.size();
5557        for (int i = 0; i < size; i++) {
5558            ResolveInfo riTargetUser = resultTargetUser.get(i);
5559            // Intent filter verification is only for filters that specify a host. So don't return
5560            // those that handle all web uris.
5561            if (riTargetUser.handleAllWebDataURI) {
5562                continue;
5563            }
5564            String packageName = riTargetUser.activityInfo.packageName;
5565            PackageSetting ps = mSettings.mPackages.get(packageName);
5566            if (ps == null) {
5567                continue;
5568            }
5569            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5570            int status = (int)(verificationState >> 32);
5571            if (result == null) {
5572                result = new CrossProfileDomainInfo();
5573                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5574                        sourceUserId, parentUserId);
5575                result.bestDomainVerificationStatus = status;
5576            } else {
5577                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5578                        result.bestDomainVerificationStatus);
5579            }
5580        }
5581        // Don't consider matches with status NEVER across profiles.
5582        if (result != null && result.bestDomainVerificationStatus
5583                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5584            return null;
5585        }
5586        return result;
5587    }
5588
5589    /**
5590     * Verification statuses are ordered from the worse to the best, except for
5591     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5592     */
5593    private int bestDomainVerificationStatus(int status1, int status2) {
5594        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5595            return status2;
5596        }
5597        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5598            return status1;
5599        }
5600        return (int) MathUtils.max(status1, status2);
5601    }
5602
5603    private boolean isUserEnabled(int userId) {
5604        long callingId = Binder.clearCallingIdentity();
5605        try {
5606            UserInfo userInfo = sUserManager.getUserInfo(userId);
5607            return userInfo != null && userInfo.isEnabled();
5608        } finally {
5609            Binder.restoreCallingIdentity(callingId);
5610        }
5611    }
5612
5613    /**
5614     * Filter out activities with systemUserOnly flag set, when current user is not System.
5615     *
5616     * @return filtered list
5617     */
5618    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5619        if (userId == UserHandle.USER_SYSTEM) {
5620            return resolveInfos;
5621        }
5622        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5623            ResolveInfo info = resolveInfos.get(i);
5624            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5625                resolveInfos.remove(i);
5626            }
5627        }
5628        return resolveInfos;
5629    }
5630
5631    /**
5632     * @param resolveInfos list of resolve infos in descending priority order
5633     * @return if the list contains a resolve info with non-negative priority
5634     */
5635    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5636        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5637    }
5638
5639    private static boolean hasWebURI(Intent intent) {
5640        if (intent.getData() == null) {
5641            return false;
5642        }
5643        final String scheme = intent.getScheme();
5644        if (TextUtils.isEmpty(scheme)) {
5645            return false;
5646        }
5647        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5648    }
5649
5650    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5651            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5652            int userId) {
5653        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5654
5655        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5656            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5657                    candidates.size());
5658        }
5659
5660        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5661        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5662        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5663        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5664        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5665        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5666
5667        synchronized (mPackages) {
5668            final int count = candidates.size();
5669            // First, try to use linked apps. Partition the candidates into four lists:
5670            // one for the final results, one for the "do not use ever", one for "undefined status"
5671            // and finally one for "browser app type".
5672            for (int n=0; n<count; n++) {
5673                ResolveInfo info = candidates.get(n);
5674                String packageName = info.activityInfo.packageName;
5675                PackageSetting ps = mSettings.mPackages.get(packageName);
5676                if (ps != null) {
5677                    // Add to the special match all list (Browser use case)
5678                    if (info.handleAllWebDataURI) {
5679                        matchAllList.add(info);
5680                        continue;
5681                    }
5682                    // Try to get the status from User settings first
5683                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5684                    int status = (int)(packedStatus >> 32);
5685                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5686                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5687                        if (DEBUG_DOMAIN_VERIFICATION) {
5688                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5689                                    + " : linkgen=" + linkGeneration);
5690                        }
5691                        // Use link-enabled generation as preferredOrder, i.e.
5692                        // prefer newly-enabled over earlier-enabled.
5693                        info.preferredOrder = linkGeneration;
5694                        alwaysList.add(info);
5695                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5696                        if (DEBUG_DOMAIN_VERIFICATION) {
5697                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5698                        }
5699                        neverList.add(info);
5700                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5701                        if (DEBUG_DOMAIN_VERIFICATION) {
5702                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5703                        }
5704                        alwaysAskList.add(info);
5705                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5706                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5707                        if (DEBUG_DOMAIN_VERIFICATION) {
5708                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5709                        }
5710                        undefinedList.add(info);
5711                    }
5712                }
5713            }
5714
5715            // We'll want to include browser possibilities in a few cases
5716            boolean includeBrowser = false;
5717
5718            // First try to add the "always" resolution(s) for the current user, if any
5719            if (alwaysList.size() > 0) {
5720                result.addAll(alwaysList);
5721            } else {
5722                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5723                result.addAll(undefinedList);
5724                // Maybe add one for the other profile.
5725                if (xpDomainInfo != null && (
5726                        xpDomainInfo.bestDomainVerificationStatus
5727                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5728                    result.add(xpDomainInfo.resolveInfo);
5729                }
5730                includeBrowser = true;
5731            }
5732
5733            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5734            // If there were 'always' entries their preferred order has been set, so we also
5735            // back that off to make the alternatives equivalent
5736            if (alwaysAskList.size() > 0) {
5737                for (ResolveInfo i : result) {
5738                    i.preferredOrder = 0;
5739                }
5740                result.addAll(alwaysAskList);
5741                includeBrowser = true;
5742            }
5743
5744            if (includeBrowser) {
5745                // Also add browsers (all of them or only the default one)
5746                if (DEBUG_DOMAIN_VERIFICATION) {
5747                    Slog.v(TAG, "   ...including browsers in candidate set");
5748                }
5749                if ((matchFlags & MATCH_ALL) != 0) {
5750                    result.addAll(matchAllList);
5751                } else {
5752                    // Browser/generic handling case.  If there's a default browser, go straight
5753                    // to that (but only if there is no other higher-priority match).
5754                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5755                    int maxMatchPrio = 0;
5756                    ResolveInfo defaultBrowserMatch = null;
5757                    final int numCandidates = matchAllList.size();
5758                    for (int n = 0; n < numCandidates; n++) {
5759                        ResolveInfo info = matchAllList.get(n);
5760                        // track the highest overall match priority...
5761                        if (info.priority > maxMatchPrio) {
5762                            maxMatchPrio = info.priority;
5763                        }
5764                        // ...and the highest-priority default browser match
5765                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5766                            if (defaultBrowserMatch == null
5767                                    || (defaultBrowserMatch.priority < info.priority)) {
5768                                if (debug) {
5769                                    Slog.v(TAG, "Considering default browser match " + info);
5770                                }
5771                                defaultBrowserMatch = info;
5772                            }
5773                        }
5774                    }
5775                    if (defaultBrowserMatch != null
5776                            && defaultBrowserMatch.priority >= maxMatchPrio
5777                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5778                    {
5779                        if (debug) {
5780                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5781                        }
5782                        result.add(defaultBrowserMatch);
5783                    } else {
5784                        result.addAll(matchAllList);
5785                    }
5786                }
5787
5788                // If there is nothing selected, add all candidates and remove the ones that the user
5789                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5790                if (result.size() == 0) {
5791                    result.addAll(candidates);
5792                    result.removeAll(neverList);
5793                }
5794            }
5795        }
5796        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5797            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5798                    result.size());
5799            for (ResolveInfo info : result) {
5800                Slog.v(TAG, "  + " + info.activityInfo);
5801            }
5802        }
5803        return result;
5804    }
5805
5806    // Returns a packed value as a long:
5807    //
5808    // high 'int'-sized word: link status: undefined/ask/never/always.
5809    // low 'int'-sized word: relative priority among 'always' results.
5810    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5811        long result = ps.getDomainVerificationStatusForUser(userId);
5812        // if none available, get the master status
5813        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5814            if (ps.getIntentFilterVerificationInfo() != null) {
5815                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5816            }
5817        }
5818        return result;
5819    }
5820
5821    private ResolveInfo querySkipCurrentProfileIntents(
5822            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5823            int flags, int sourceUserId) {
5824        if (matchingFilters != null) {
5825            int size = matchingFilters.size();
5826            for (int i = 0; i < size; i ++) {
5827                CrossProfileIntentFilter filter = matchingFilters.get(i);
5828                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5829                    // Checking if there are activities in the target user that can handle the
5830                    // intent.
5831                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5832                            resolvedType, flags, sourceUserId);
5833                    if (resolveInfo != null) {
5834                        return resolveInfo;
5835                    }
5836                }
5837            }
5838        }
5839        return null;
5840    }
5841
5842    // Return matching ResolveInfo in target user if any.
5843    private ResolveInfo queryCrossProfileIntents(
5844            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5845            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5846        if (matchingFilters != null) {
5847            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5848            // match the same intent. For performance reasons, it is better not to
5849            // run queryIntent twice for the same userId
5850            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5851            int size = matchingFilters.size();
5852            for (int i = 0; i < size; i++) {
5853                CrossProfileIntentFilter filter = matchingFilters.get(i);
5854                int targetUserId = filter.getTargetUserId();
5855                boolean skipCurrentProfile =
5856                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5857                boolean skipCurrentProfileIfNoMatchFound =
5858                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5859                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5860                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5861                    // Checking if there are activities in the target user that can handle the
5862                    // intent.
5863                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5864                            resolvedType, flags, sourceUserId);
5865                    if (resolveInfo != null) return resolveInfo;
5866                    alreadyTriedUserIds.put(targetUserId, true);
5867                }
5868            }
5869        }
5870        return null;
5871    }
5872
5873    /**
5874     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5875     * will forward the intent to the filter's target user.
5876     * Otherwise, returns null.
5877     */
5878    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5879            String resolvedType, int flags, int sourceUserId) {
5880        int targetUserId = filter.getTargetUserId();
5881        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5882                resolvedType, flags, targetUserId);
5883        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5884            // If all the matches in the target profile are suspended, return null.
5885            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5886                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5887                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5888                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5889                            targetUserId);
5890                }
5891            }
5892        }
5893        return null;
5894    }
5895
5896    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5897            int sourceUserId, int targetUserId) {
5898        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5899        long ident = Binder.clearCallingIdentity();
5900        boolean targetIsProfile;
5901        try {
5902            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5903        } finally {
5904            Binder.restoreCallingIdentity(ident);
5905        }
5906        String className;
5907        if (targetIsProfile) {
5908            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5909        } else {
5910            className = FORWARD_INTENT_TO_PARENT;
5911        }
5912        ComponentName forwardingActivityComponentName = new ComponentName(
5913                mAndroidApplication.packageName, className);
5914        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5915                sourceUserId);
5916        if (!targetIsProfile) {
5917            forwardingActivityInfo.showUserIcon = targetUserId;
5918            forwardingResolveInfo.noResourceId = true;
5919        }
5920        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5921        forwardingResolveInfo.priority = 0;
5922        forwardingResolveInfo.preferredOrder = 0;
5923        forwardingResolveInfo.match = 0;
5924        forwardingResolveInfo.isDefault = true;
5925        forwardingResolveInfo.filter = filter;
5926        forwardingResolveInfo.targetUserId = targetUserId;
5927        return forwardingResolveInfo;
5928    }
5929
5930    @Override
5931    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5932            Intent[] specifics, String[] specificTypes, Intent intent,
5933            String resolvedType, int flags, int userId) {
5934        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5935                specificTypes, intent, resolvedType, flags, userId));
5936    }
5937
5938    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5939            Intent[] specifics, String[] specificTypes, Intent intent,
5940            String resolvedType, int flags, int userId) {
5941        if (!sUserManager.exists(userId)) return Collections.emptyList();
5942        flags = updateFlagsForResolve(flags, userId, intent);
5943        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5944                false /* requireFullPermission */, false /* checkShell */,
5945                "query intent activity options");
5946        final String resultsAction = intent.getAction();
5947
5948        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5949                | PackageManager.GET_RESOLVED_FILTER, userId);
5950
5951        if (DEBUG_INTENT_MATCHING) {
5952            Log.v(TAG, "Query " + intent + ": " + results);
5953        }
5954
5955        int specificsPos = 0;
5956        int N;
5957
5958        // todo: note that the algorithm used here is O(N^2).  This
5959        // isn't a problem in our current environment, but if we start running
5960        // into situations where we have more than 5 or 10 matches then this
5961        // should probably be changed to something smarter...
5962
5963        // First we go through and resolve each of the specific items
5964        // that were supplied, taking care of removing any corresponding
5965        // duplicate items in the generic resolve list.
5966        if (specifics != null) {
5967            for (int i=0; i<specifics.length; i++) {
5968                final Intent sintent = specifics[i];
5969                if (sintent == null) {
5970                    continue;
5971                }
5972
5973                if (DEBUG_INTENT_MATCHING) {
5974                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5975                }
5976
5977                String action = sintent.getAction();
5978                if (resultsAction != null && resultsAction.equals(action)) {
5979                    // If this action was explicitly requested, then don't
5980                    // remove things that have it.
5981                    action = null;
5982                }
5983
5984                ResolveInfo ri = null;
5985                ActivityInfo ai = null;
5986
5987                ComponentName comp = sintent.getComponent();
5988                if (comp == null) {
5989                    ri = resolveIntent(
5990                        sintent,
5991                        specificTypes != null ? specificTypes[i] : null,
5992                            flags, userId);
5993                    if (ri == null) {
5994                        continue;
5995                    }
5996                    if (ri == mResolveInfo) {
5997                        // ACK!  Must do something better with this.
5998                    }
5999                    ai = ri.activityInfo;
6000                    comp = new ComponentName(ai.applicationInfo.packageName,
6001                            ai.name);
6002                } else {
6003                    ai = getActivityInfo(comp, flags, userId);
6004                    if (ai == null) {
6005                        continue;
6006                    }
6007                }
6008
6009                // Look for any generic query activities that are duplicates
6010                // of this specific one, and remove them from the results.
6011                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6012                N = results.size();
6013                int j;
6014                for (j=specificsPos; j<N; j++) {
6015                    ResolveInfo sri = results.get(j);
6016                    if ((sri.activityInfo.name.equals(comp.getClassName())
6017                            && sri.activityInfo.applicationInfo.packageName.equals(
6018                                    comp.getPackageName()))
6019                        || (action != null && sri.filter.matchAction(action))) {
6020                        results.remove(j);
6021                        if (DEBUG_INTENT_MATCHING) Log.v(
6022                            TAG, "Removing duplicate item from " + j
6023                            + " due to specific " + specificsPos);
6024                        if (ri == null) {
6025                            ri = sri;
6026                        }
6027                        j--;
6028                        N--;
6029                    }
6030                }
6031
6032                // Add this specific item to its proper place.
6033                if (ri == null) {
6034                    ri = new ResolveInfo();
6035                    ri.activityInfo = ai;
6036                }
6037                results.add(specificsPos, ri);
6038                ri.specificIndex = i;
6039                specificsPos++;
6040            }
6041        }
6042
6043        // Now we go through the remaining generic results and remove any
6044        // duplicate actions that are found here.
6045        N = results.size();
6046        for (int i=specificsPos; i<N-1; i++) {
6047            final ResolveInfo rii = results.get(i);
6048            if (rii.filter == null) {
6049                continue;
6050            }
6051
6052            // Iterate over all of the actions of this result's intent
6053            // filter...  typically this should be just one.
6054            final Iterator<String> it = rii.filter.actionsIterator();
6055            if (it == null) {
6056                continue;
6057            }
6058            while (it.hasNext()) {
6059                final String action = it.next();
6060                if (resultsAction != null && resultsAction.equals(action)) {
6061                    // If this action was explicitly requested, then don't
6062                    // remove things that have it.
6063                    continue;
6064                }
6065                for (int j=i+1; j<N; j++) {
6066                    final ResolveInfo rij = results.get(j);
6067                    if (rij.filter != null && rij.filter.hasAction(action)) {
6068                        results.remove(j);
6069                        if (DEBUG_INTENT_MATCHING) Log.v(
6070                            TAG, "Removing duplicate item from " + j
6071                            + " due to action " + action + " at " + i);
6072                        j--;
6073                        N--;
6074                    }
6075                }
6076            }
6077
6078            // If the caller didn't request filter information, drop it now
6079            // so we don't have to marshall/unmarshall it.
6080            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6081                rii.filter = null;
6082            }
6083        }
6084
6085        // Filter out the caller activity if so requested.
6086        if (caller != null) {
6087            N = results.size();
6088            for (int i=0; i<N; i++) {
6089                ActivityInfo ainfo = results.get(i).activityInfo;
6090                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6091                        && caller.getClassName().equals(ainfo.name)) {
6092                    results.remove(i);
6093                    break;
6094                }
6095            }
6096        }
6097
6098        // If the caller didn't request filter information,
6099        // drop them now so we don't have to
6100        // marshall/unmarshall it.
6101        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6102            N = results.size();
6103            for (int i=0; i<N; i++) {
6104                results.get(i).filter = null;
6105            }
6106        }
6107
6108        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6109        return results;
6110    }
6111
6112    @Override
6113    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6114            String resolvedType, int flags, int userId) {
6115        return new ParceledListSlice<>(
6116                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6117    }
6118
6119    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6120            String resolvedType, int flags, int userId) {
6121        if (!sUserManager.exists(userId)) return Collections.emptyList();
6122        flags = updateFlagsForResolve(flags, userId, intent);
6123        ComponentName comp = intent.getComponent();
6124        if (comp == null) {
6125            if (intent.getSelector() != null) {
6126                intent = intent.getSelector();
6127                comp = intent.getComponent();
6128            }
6129        }
6130        if (comp != null) {
6131            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6132            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6133            if (ai != null) {
6134                ResolveInfo ri = new ResolveInfo();
6135                ri.activityInfo = ai;
6136                list.add(ri);
6137            }
6138            return list;
6139        }
6140
6141        // reader
6142        synchronized (mPackages) {
6143            String pkgName = intent.getPackage();
6144            if (pkgName == null) {
6145                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6146            }
6147            final PackageParser.Package pkg = mPackages.get(pkgName);
6148            if (pkg != null) {
6149                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6150                        userId);
6151            }
6152            return Collections.emptyList();
6153        }
6154    }
6155
6156    @Override
6157    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6158        if (!sUserManager.exists(userId)) return null;
6159        flags = updateFlagsForResolve(flags, userId, intent);
6160        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6161        if (query != null) {
6162            if (query.size() >= 1) {
6163                // If there is more than one service with the same priority,
6164                // just arbitrarily pick the first one.
6165                return query.get(0);
6166            }
6167        }
6168        return null;
6169    }
6170
6171    @Override
6172    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6173            String resolvedType, int flags, int userId) {
6174        return new ParceledListSlice<>(
6175                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6176    }
6177
6178    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6179            String resolvedType, int flags, int userId) {
6180        if (!sUserManager.exists(userId)) return Collections.emptyList();
6181        flags = updateFlagsForResolve(flags, userId, intent);
6182        ComponentName comp = intent.getComponent();
6183        if (comp == null) {
6184            if (intent.getSelector() != null) {
6185                intent = intent.getSelector();
6186                comp = intent.getComponent();
6187            }
6188        }
6189        if (comp != null) {
6190            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6191            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6192            if (si != null) {
6193                final ResolveInfo ri = new ResolveInfo();
6194                ri.serviceInfo = si;
6195                list.add(ri);
6196            }
6197            return list;
6198        }
6199
6200        // reader
6201        synchronized (mPackages) {
6202            String pkgName = intent.getPackage();
6203            if (pkgName == null) {
6204                return mServices.queryIntent(intent, resolvedType, flags, userId);
6205            }
6206            final PackageParser.Package pkg = mPackages.get(pkgName);
6207            if (pkg != null) {
6208                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6209                        userId);
6210            }
6211            return Collections.emptyList();
6212        }
6213    }
6214
6215    @Override
6216    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6217            String resolvedType, int flags, int userId) {
6218        return new ParceledListSlice<>(
6219                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6220    }
6221
6222    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6223            Intent intent, String resolvedType, int flags, int userId) {
6224        if (!sUserManager.exists(userId)) return Collections.emptyList();
6225        flags = updateFlagsForResolve(flags, userId, intent);
6226        ComponentName comp = intent.getComponent();
6227        if (comp == null) {
6228            if (intent.getSelector() != null) {
6229                intent = intent.getSelector();
6230                comp = intent.getComponent();
6231            }
6232        }
6233        if (comp != null) {
6234            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6235            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6236            if (pi != null) {
6237                final ResolveInfo ri = new ResolveInfo();
6238                ri.providerInfo = pi;
6239                list.add(ri);
6240            }
6241            return list;
6242        }
6243
6244        // reader
6245        synchronized (mPackages) {
6246            String pkgName = intent.getPackage();
6247            if (pkgName == null) {
6248                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6249            }
6250            final PackageParser.Package pkg = mPackages.get(pkgName);
6251            if (pkg != null) {
6252                return mProviders.queryIntentForPackage(
6253                        intent, resolvedType, flags, pkg.providers, userId);
6254            }
6255            return Collections.emptyList();
6256        }
6257    }
6258
6259    @Override
6260    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6261        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6262        flags = updateFlagsForPackage(flags, userId, null);
6263        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6265                true /* requireFullPermission */, false /* checkShell */,
6266                "get installed packages");
6267
6268        // writer
6269        synchronized (mPackages) {
6270            ArrayList<PackageInfo> list;
6271            if (listUninstalled) {
6272                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6273                for (PackageSetting ps : mSettings.mPackages.values()) {
6274                    final PackageInfo pi;
6275                    if (ps.pkg != null) {
6276                        pi = generatePackageInfo(ps, flags, userId);
6277                    } else {
6278                        pi = generatePackageInfo(ps, flags, userId);
6279                    }
6280                    if (pi != null) {
6281                        list.add(pi);
6282                    }
6283                }
6284            } else {
6285                list = new ArrayList<PackageInfo>(mPackages.size());
6286                for (PackageParser.Package p : mPackages.values()) {
6287                    final PackageInfo pi =
6288                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6289                    if (pi != null) {
6290                        list.add(pi);
6291                    }
6292                }
6293            }
6294
6295            return new ParceledListSlice<PackageInfo>(list);
6296        }
6297    }
6298
6299    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6300            String[] permissions, boolean[] tmp, int flags, int userId) {
6301        int numMatch = 0;
6302        final PermissionsState permissionsState = ps.getPermissionsState();
6303        for (int i=0; i<permissions.length; i++) {
6304            final String permission = permissions[i];
6305            if (permissionsState.hasPermission(permission, userId)) {
6306                tmp[i] = true;
6307                numMatch++;
6308            } else {
6309                tmp[i] = false;
6310            }
6311        }
6312        if (numMatch == 0) {
6313            return;
6314        }
6315        final PackageInfo pi;
6316        if (ps.pkg != null) {
6317            pi = generatePackageInfo(ps, flags, userId);
6318        } else {
6319            pi = generatePackageInfo(ps, flags, userId);
6320        }
6321        // The above might return null in cases of uninstalled apps or install-state
6322        // skew across users/profiles.
6323        if (pi != null) {
6324            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6325                if (numMatch == permissions.length) {
6326                    pi.requestedPermissions = permissions;
6327                } else {
6328                    pi.requestedPermissions = new String[numMatch];
6329                    numMatch = 0;
6330                    for (int i=0; i<permissions.length; i++) {
6331                        if (tmp[i]) {
6332                            pi.requestedPermissions[numMatch] = permissions[i];
6333                            numMatch++;
6334                        }
6335                    }
6336                }
6337            }
6338            list.add(pi);
6339        }
6340    }
6341
6342    @Override
6343    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6344            String[] permissions, int flags, int userId) {
6345        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6346        flags = updateFlagsForPackage(flags, userId, permissions);
6347        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6348
6349        // writer
6350        synchronized (mPackages) {
6351            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6352            boolean[] tmpBools = new boolean[permissions.length];
6353            if (listUninstalled) {
6354                for (PackageSetting ps : mSettings.mPackages.values()) {
6355                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6356                }
6357            } else {
6358                for (PackageParser.Package pkg : mPackages.values()) {
6359                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6360                    if (ps != null) {
6361                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6362                                userId);
6363                    }
6364                }
6365            }
6366
6367            return new ParceledListSlice<PackageInfo>(list);
6368        }
6369    }
6370
6371    @Override
6372    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6373        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6374        flags = updateFlagsForApplication(flags, userId, null);
6375        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6376
6377        // writer
6378        synchronized (mPackages) {
6379            ArrayList<ApplicationInfo> list;
6380            if (listUninstalled) {
6381                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6382                for (PackageSetting ps : mSettings.mPackages.values()) {
6383                    ApplicationInfo ai;
6384                    if (ps.pkg != null) {
6385                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6386                                ps.readUserState(userId), userId);
6387                    } else {
6388                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6389                    }
6390                    if (ai != null) {
6391                        list.add(ai);
6392                    }
6393                }
6394            } else {
6395                list = new ArrayList<ApplicationInfo>(mPackages.size());
6396                for (PackageParser.Package p : mPackages.values()) {
6397                    if (p.mExtras != null) {
6398                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6399                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6400                        if (ai != null) {
6401                            list.add(ai);
6402                        }
6403                    }
6404                }
6405            }
6406
6407            return new ParceledListSlice<ApplicationInfo>(list);
6408        }
6409    }
6410
6411    @Override
6412    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6413        if (DISABLE_EPHEMERAL_APPS) {
6414            return null;
6415        }
6416
6417        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6418                "getEphemeralApplications");
6419        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6420                true /* requireFullPermission */, false /* checkShell */,
6421                "getEphemeralApplications");
6422        synchronized (mPackages) {
6423            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6424                    .getEphemeralApplicationsLPw(userId);
6425            if (ephemeralApps != null) {
6426                return new ParceledListSlice<>(ephemeralApps);
6427            }
6428        }
6429        return null;
6430    }
6431
6432    @Override
6433    public boolean isEphemeralApplication(String packageName, int userId) {
6434        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6435                true /* requireFullPermission */, false /* checkShell */,
6436                "isEphemeral");
6437        if (DISABLE_EPHEMERAL_APPS) {
6438            return false;
6439        }
6440
6441        if (!isCallerSameApp(packageName)) {
6442            return false;
6443        }
6444        synchronized (mPackages) {
6445            PackageParser.Package pkg = mPackages.get(packageName);
6446            if (pkg != null) {
6447                return pkg.applicationInfo.isEphemeralApp();
6448            }
6449        }
6450        return false;
6451    }
6452
6453    @Override
6454    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6455        if (DISABLE_EPHEMERAL_APPS) {
6456            return null;
6457        }
6458
6459        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6460                true /* requireFullPermission */, false /* checkShell */,
6461                "getCookie");
6462        if (!isCallerSameApp(packageName)) {
6463            return null;
6464        }
6465        synchronized (mPackages) {
6466            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6467                    packageName, userId);
6468        }
6469    }
6470
6471    @Override
6472    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6473        if (DISABLE_EPHEMERAL_APPS) {
6474            return true;
6475        }
6476
6477        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6478                true /* requireFullPermission */, true /* checkShell */,
6479                "setCookie");
6480        if (!isCallerSameApp(packageName)) {
6481            return false;
6482        }
6483        synchronized (mPackages) {
6484            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6485                    packageName, cookie, userId);
6486        }
6487    }
6488
6489    @Override
6490    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6491        if (DISABLE_EPHEMERAL_APPS) {
6492            return null;
6493        }
6494
6495        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6496                "getEphemeralApplicationIcon");
6497        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6498                true /* requireFullPermission */, false /* checkShell */,
6499                "getEphemeralApplicationIcon");
6500        synchronized (mPackages) {
6501            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6502                    packageName, userId);
6503        }
6504    }
6505
6506    private boolean isCallerSameApp(String packageName) {
6507        PackageParser.Package pkg = mPackages.get(packageName);
6508        return pkg != null
6509                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6510    }
6511
6512    @Override
6513    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6514        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6515    }
6516
6517    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6518        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6519
6520        // reader
6521        synchronized (mPackages) {
6522            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6523            final int userId = UserHandle.getCallingUserId();
6524            while (i.hasNext()) {
6525                final PackageParser.Package p = i.next();
6526                if (p.applicationInfo == null) continue;
6527
6528                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6529                        && !p.applicationInfo.isDirectBootAware();
6530                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6531                        && p.applicationInfo.isDirectBootAware();
6532
6533                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6534                        && (!mSafeMode || isSystemApp(p))
6535                        && (matchesUnaware || matchesAware)) {
6536                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6537                    if (ps != null) {
6538                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6539                                ps.readUserState(userId), userId);
6540                        if (ai != null) {
6541                            finalList.add(ai);
6542                        }
6543                    }
6544                }
6545            }
6546        }
6547
6548        return finalList;
6549    }
6550
6551    @Override
6552    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6553        if (!sUserManager.exists(userId)) return null;
6554        flags = updateFlagsForComponent(flags, userId, name);
6555        // reader
6556        synchronized (mPackages) {
6557            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6558            PackageSetting ps = provider != null
6559                    ? mSettings.mPackages.get(provider.owner.packageName)
6560                    : null;
6561            return ps != null
6562                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6563                    ? PackageParser.generateProviderInfo(provider, flags,
6564                            ps.readUserState(userId), userId)
6565                    : null;
6566        }
6567    }
6568
6569    /**
6570     * @deprecated
6571     */
6572    @Deprecated
6573    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6574        // reader
6575        synchronized (mPackages) {
6576            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6577                    .entrySet().iterator();
6578            final int userId = UserHandle.getCallingUserId();
6579            while (i.hasNext()) {
6580                Map.Entry<String, PackageParser.Provider> entry = i.next();
6581                PackageParser.Provider p = entry.getValue();
6582                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6583
6584                if (ps != null && p.syncable
6585                        && (!mSafeMode || (p.info.applicationInfo.flags
6586                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6587                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6588                            ps.readUserState(userId), userId);
6589                    if (info != null) {
6590                        outNames.add(entry.getKey());
6591                        outInfo.add(info);
6592                    }
6593                }
6594            }
6595        }
6596    }
6597
6598    @Override
6599    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6600            int uid, int flags) {
6601        final int userId = processName != null ? UserHandle.getUserId(uid)
6602                : UserHandle.getCallingUserId();
6603        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6604        flags = updateFlagsForComponent(flags, userId, processName);
6605
6606        ArrayList<ProviderInfo> finalList = null;
6607        // reader
6608        synchronized (mPackages) {
6609            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6610            while (i.hasNext()) {
6611                final PackageParser.Provider p = i.next();
6612                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6613                if (ps != null && p.info.authority != null
6614                        && (processName == null
6615                                || (p.info.processName.equals(processName)
6616                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6617                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6618                    if (finalList == null) {
6619                        finalList = new ArrayList<ProviderInfo>(3);
6620                    }
6621                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6622                            ps.readUserState(userId), userId);
6623                    if (info != null) {
6624                        finalList.add(info);
6625                    }
6626                }
6627            }
6628        }
6629
6630        if (finalList != null) {
6631            Collections.sort(finalList, mProviderInitOrderSorter);
6632            return new ParceledListSlice<ProviderInfo>(finalList);
6633        }
6634
6635        return ParceledListSlice.emptyList();
6636    }
6637
6638    @Override
6639    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6640        // reader
6641        synchronized (mPackages) {
6642            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6643            return PackageParser.generateInstrumentationInfo(i, flags);
6644        }
6645    }
6646
6647    @Override
6648    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6649            String targetPackage, int flags) {
6650        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6651    }
6652
6653    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6654            int flags) {
6655        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6656
6657        // reader
6658        synchronized (mPackages) {
6659            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6660            while (i.hasNext()) {
6661                final PackageParser.Instrumentation p = i.next();
6662                if (targetPackage == null
6663                        || targetPackage.equals(p.info.targetPackage)) {
6664                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6665                            flags);
6666                    if (ii != null) {
6667                        finalList.add(ii);
6668                    }
6669                }
6670            }
6671        }
6672
6673        return finalList;
6674    }
6675
6676    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6677        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6678        if (overlays == null) {
6679            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6680            return;
6681        }
6682        for (PackageParser.Package opkg : overlays.values()) {
6683            // Not much to do if idmap fails: we already logged the error
6684            // and we certainly don't want to abort installation of pkg simply
6685            // because an overlay didn't fit properly. For these reasons,
6686            // ignore the return value of createIdmapForPackagePairLI.
6687            createIdmapForPackagePairLI(pkg, opkg);
6688        }
6689    }
6690
6691    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6692            PackageParser.Package opkg) {
6693        if (!opkg.mTrustedOverlay) {
6694            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6695                    opkg.baseCodePath + ": overlay not trusted");
6696            return false;
6697        }
6698        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6699        if (overlaySet == null) {
6700            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6701                    opkg.baseCodePath + " but target package has no known overlays");
6702            return false;
6703        }
6704        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6705        // TODO: generate idmap for split APKs
6706        try {
6707            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6708        } catch (InstallerException e) {
6709            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6710                    + opkg.baseCodePath);
6711            return false;
6712        }
6713        PackageParser.Package[] overlayArray =
6714            overlaySet.values().toArray(new PackageParser.Package[0]);
6715        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6716            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6717                return p1.mOverlayPriority - p2.mOverlayPriority;
6718            }
6719        };
6720        Arrays.sort(overlayArray, cmp);
6721
6722        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6723        int i = 0;
6724        for (PackageParser.Package p : overlayArray) {
6725            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6726        }
6727        return true;
6728    }
6729
6730    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6731        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6732        try {
6733            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6734        } finally {
6735            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6736        }
6737    }
6738
6739    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6740        final File[] files = dir.listFiles();
6741        if (ArrayUtils.isEmpty(files)) {
6742            Log.d(TAG, "No files in app dir " + dir);
6743            return;
6744        }
6745
6746        if (DEBUG_PACKAGE_SCANNING) {
6747            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6748                    + " flags=0x" + Integer.toHexString(parseFlags));
6749        }
6750
6751        for (File file : files) {
6752            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6753                    && !PackageInstallerService.isStageName(file.getName());
6754            if (!isPackage) {
6755                // Ignore entries which are not packages
6756                continue;
6757            }
6758            try {
6759                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6760                        scanFlags, currentTime, null);
6761            } catch (PackageManagerException e) {
6762                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6763
6764                // Delete invalid userdata apps
6765                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6766                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6767                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6768                    removeCodePathLI(file);
6769                }
6770            }
6771        }
6772    }
6773
6774    private static File getSettingsProblemFile() {
6775        File dataDir = Environment.getDataDirectory();
6776        File systemDir = new File(dataDir, "system");
6777        File fname = new File(systemDir, "uiderrors.txt");
6778        return fname;
6779    }
6780
6781    static void reportSettingsProblem(int priority, String msg) {
6782        logCriticalInfo(priority, msg);
6783    }
6784
6785    static void logCriticalInfo(int priority, String msg) {
6786        Slog.println(priority, TAG, msg);
6787        EventLogTags.writePmCriticalInfo(msg);
6788        try {
6789            File fname = getSettingsProblemFile();
6790            FileOutputStream out = new FileOutputStream(fname, true);
6791            PrintWriter pw = new FastPrintWriter(out);
6792            SimpleDateFormat formatter = new SimpleDateFormat();
6793            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6794            pw.println(dateString + ": " + msg);
6795            pw.close();
6796            FileUtils.setPermissions(
6797                    fname.toString(),
6798                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6799                    -1, -1);
6800        } catch (java.io.IOException e) {
6801        }
6802    }
6803
6804    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6805        if (srcFile.isDirectory()) {
6806            final File baseFile = new File(pkg.baseCodePath);
6807            long maxModifiedTime = baseFile.lastModified();
6808            if (pkg.splitCodePaths != null) {
6809                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6810                    final File splitFile = new File(pkg.splitCodePaths[i]);
6811                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6812                }
6813            }
6814            return maxModifiedTime;
6815        }
6816        return srcFile.lastModified();
6817    }
6818
6819    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6820            final int policyFlags) throws PackageManagerException {
6821        if (ps != null
6822                && ps.codePath.equals(srcFile)
6823                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6824                && !isCompatSignatureUpdateNeeded(pkg)
6825                && !isRecoverSignatureUpdateNeeded(pkg)) {
6826            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6827            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6828            ArraySet<PublicKey> signingKs;
6829            synchronized (mPackages) {
6830                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6831            }
6832            if (ps.signatures.mSignatures != null
6833                    && ps.signatures.mSignatures.length != 0
6834                    && signingKs != null) {
6835                // Optimization: reuse the existing cached certificates
6836                // if the package appears to be unchanged.
6837                pkg.mSignatures = ps.signatures.mSignatures;
6838                pkg.mSigningKeys = signingKs;
6839                return;
6840            }
6841
6842            Slog.w(TAG, "PackageSetting for " + ps.name
6843                    + " is missing signatures.  Collecting certs again to recover them.");
6844        } else {
6845            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6846        }
6847
6848        try {
6849            PackageParser.collectCertificates(pkg, policyFlags);
6850        } catch (PackageParserException e) {
6851            throw PackageManagerException.from(e);
6852        }
6853    }
6854
6855    /**
6856     *  Traces a package scan.
6857     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6858     */
6859    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6860            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6861        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6862        try {
6863            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6864        } finally {
6865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6866        }
6867    }
6868
6869    /**
6870     *  Scans a package and returns the newly parsed package.
6871     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6872     */
6873    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6874            long currentTime, UserHandle user) throws PackageManagerException {
6875        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6876        PackageParser pp = new PackageParser();
6877        pp.setSeparateProcesses(mSeparateProcesses);
6878        pp.setOnlyCoreApps(mOnlyCore);
6879        pp.setDisplayMetrics(mMetrics);
6880
6881        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6882            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6883        }
6884
6885        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6886        final PackageParser.Package pkg;
6887        try {
6888            pkg = pp.parsePackage(scanFile, parseFlags);
6889        } catch (PackageParserException e) {
6890            throw PackageManagerException.from(e);
6891        } finally {
6892            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6893        }
6894
6895        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6896    }
6897
6898    /**
6899     *  Scans a package and returns the newly parsed package.
6900     *  @throws PackageManagerException on a parse error.
6901     */
6902    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6903            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6904            throws PackageManagerException {
6905        // If the package has children and this is the first dive in the function
6906        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6907        // packages (parent and children) would be successfully scanned before the
6908        // actual scan since scanning mutates internal state and we want to atomically
6909        // install the package and its children.
6910        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6911            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6912                scanFlags |= SCAN_CHECK_ONLY;
6913            }
6914        } else {
6915            scanFlags &= ~SCAN_CHECK_ONLY;
6916        }
6917
6918        // Scan the parent
6919        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6920                scanFlags, currentTime, user);
6921
6922        // Scan the children
6923        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6924        for (int i = 0; i < childCount; i++) {
6925            PackageParser.Package childPackage = pkg.childPackages.get(i);
6926            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6927                    currentTime, user);
6928        }
6929
6930
6931        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6932            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6933        }
6934
6935        return scannedPkg;
6936    }
6937
6938    /**
6939     *  Scans a package and returns the newly parsed package.
6940     *  @throws PackageManagerException on a parse error.
6941     */
6942    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6943            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6944            throws PackageManagerException {
6945        PackageSetting ps = null;
6946        PackageSetting updatedPkg;
6947        // reader
6948        synchronized (mPackages) {
6949            // Look to see if we already know about this package.
6950            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6951            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6952                // This package has been renamed to its original name.  Let's
6953                // use that.
6954                ps = mSettings.peekPackageLPr(oldName);
6955            }
6956            // If there was no original package, see one for the real package name.
6957            if (ps == null) {
6958                ps = mSettings.peekPackageLPr(pkg.packageName);
6959            }
6960            // Check to see if this package could be hiding/updating a system
6961            // package.  Must look for it either under the original or real
6962            // package name depending on our state.
6963            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6964            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6965
6966            // If this is a package we don't know about on the system partition, we
6967            // may need to remove disabled child packages on the system partition
6968            // or may need to not add child packages if the parent apk is updated
6969            // on the data partition and no longer defines this child package.
6970            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6971                // If this is a parent package for an updated system app and this system
6972                // app got an OTA update which no longer defines some of the child packages
6973                // we have to prune them from the disabled system packages.
6974                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6975                if (disabledPs != null) {
6976                    final int scannedChildCount = (pkg.childPackages != null)
6977                            ? pkg.childPackages.size() : 0;
6978                    final int disabledChildCount = disabledPs.childPackageNames != null
6979                            ? disabledPs.childPackageNames.size() : 0;
6980                    for (int i = 0; i < disabledChildCount; i++) {
6981                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6982                        boolean disabledPackageAvailable = false;
6983                        for (int j = 0; j < scannedChildCount; j++) {
6984                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6985                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6986                                disabledPackageAvailable = true;
6987                                break;
6988                            }
6989                         }
6990                         if (!disabledPackageAvailable) {
6991                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6992                         }
6993                    }
6994                }
6995            }
6996        }
6997
6998        boolean updatedPkgBetter = false;
6999        // First check if this is a system package that may involve an update
7000        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7001            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7002            // it needs to drop FLAG_PRIVILEGED.
7003            if (locationIsPrivileged(scanFile)) {
7004                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7005            } else {
7006                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7007            }
7008
7009            if (ps != null && !ps.codePath.equals(scanFile)) {
7010                // The path has changed from what was last scanned...  check the
7011                // version of the new path against what we have stored to determine
7012                // what to do.
7013                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7014                if (pkg.mVersionCode <= ps.versionCode) {
7015                    // The system package has been updated and the code path does not match
7016                    // Ignore entry. Skip it.
7017                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7018                            + " ignored: updated version " + ps.versionCode
7019                            + " better than this " + pkg.mVersionCode);
7020                    if (!updatedPkg.codePath.equals(scanFile)) {
7021                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7022                                + ps.name + " changing from " + updatedPkg.codePathString
7023                                + " to " + scanFile);
7024                        updatedPkg.codePath = scanFile;
7025                        updatedPkg.codePathString = scanFile.toString();
7026                        updatedPkg.resourcePath = scanFile;
7027                        updatedPkg.resourcePathString = scanFile.toString();
7028                    }
7029                    updatedPkg.pkg = pkg;
7030                    updatedPkg.versionCode = pkg.mVersionCode;
7031
7032                    // Update the disabled system child packages to point to the package too.
7033                    final int childCount = updatedPkg.childPackageNames != null
7034                            ? updatedPkg.childPackageNames.size() : 0;
7035                    for (int i = 0; i < childCount; i++) {
7036                        String childPackageName = updatedPkg.childPackageNames.get(i);
7037                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7038                                childPackageName);
7039                        if (updatedChildPkg != null) {
7040                            updatedChildPkg.pkg = pkg;
7041                            updatedChildPkg.versionCode = pkg.mVersionCode;
7042                        }
7043                    }
7044
7045                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7046                            + scanFile + " ignored: updated version " + ps.versionCode
7047                            + " better than this " + pkg.mVersionCode);
7048                } else {
7049                    // The current app on the system partition is better than
7050                    // what we have updated to on the data partition; switch
7051                    // back to the system partition version.
7052                    // At this point, its safely assumed that package installation for
7053                    // apps in system partition will go through. If not there won't be a working
7054                    // version of the app
7055                    // writer
7056                    synchronized (mPackages) {
7057                        // Just remove the loaded entries from package lists.
7058                        mPackages.remove(ps.name);
7059                    }
7060
7061                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7062                            + " reverting from " + ps.codePathString
7063                            + ": new version " + pkg.mVersionCode
7064                            + " better than installed " + ps.versionCode);
7065
7066                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7067                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7068                    synchronized (mInstallLock) {
7069                        args.cleanUpResourcesLI();
7070                    }
7071                    synchronized (mPackages) {
7072                        mSettings.enableSystemPackageLPw(ps.name);
7073                    }
7074                    updatedPkgBetter = true;
7075                }
7076            }
7077        }
7078
7079        if (updatedPkg != null) {
7080            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7081            // initially
7082            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7083
7084            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7085            // flag set initially
7086            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7087                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7088            }
7089        }
7090
7091        // Verify certificates against what was last scanned
7092        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7093
7094        /*
7095         * A new system app appeared, but we already had a non-system one of the
7096         * same name installed earlier.
7097         */
7098        boolean shouldHideSystemApp = false;
7099        if (updatedPkg == null && ps != null
7100                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7101            /*
7102             * Check to make sure the signatures match first. If they don't,
7103             * wipe the installed application and its data.
7104             */
7105            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7106                    != PackageManager.SIGNATURE_MATCH) {
7107                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7108                        + " signatures don't match existing userdata copy; removing");
7109                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7110                        "scanPackageInternalLI")) {
7111                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7112                }
7113                ps = null;
7114            } else {
7115                /*
7116                 * If the newly-added system app is an older version than the
7117                 * already installed version, hide it. It will be scanned later
7118                 * and re-added like an update.
7119                 */
7120                if (pkg.mVersionCode <= ps.versionCode) {
7121                    shouldHideSystemApp = true;
7122                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7123                            + " but new version " + pkg.mVersionCode + " better than installed "
7124                            + ps.versionCode + "; hiding system");
7125                } else {
7126                    /*
7127                     * The newly found system app is a newer version that the
7128                     * one previously installed. Simply remove the
7129                     * already-installed application and replace it with our own
7130                     * while keeping the application data.
7131                     */
7132                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7133                            + " reverting from " + ps.codePathString + ": new version "
7134                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7135                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7136                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7137                    synchronized (mInstallLock) {
7138                        args.cleanUpResourcesLI();
7139                    }
7140                }
7141            }
7142        }
7143
7144        // The apk is forward locked (not public) if its code and resources
7145        // are kept in different files. (except for app in either system or
7146        // vendor path).
7147        // TODO grab this value from PackageSettings
7148        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7149            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7150                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7151            }
7152        }
7153
7154        // TODO: extend to support forward-locked splits
7155        String resourcePath = null;
7156        String baseResourcePath = null;
7157        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7158            if (ps != null && ps.resourcePathString != null) {
7159                resourcePath = ps.resourcePathString;
7160                baseResourcePath = ps.resourcePathString;
7161            } else {
7162                // Should not happen at all. Just log an error.
7163                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7164            }
7165        } else {
7166            resourcePath = pkg.codePath;
7167            baseResourcePath = pkg.baseCodePath;
7168        }
7169
7170        // Set application objects path explicitly.
7171        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7172        pkg.setApplicationInfoCodePath(pkg.codePath);
7173        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7174        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7175        pkg.setApplicationInfoResourcePath(resourcePath);
7176        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7177        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7178
7179        // Note that we invoke the following method only if we are about to unpack an application
7180        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7181                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7182
7183        /*
7184         * If the system app should be overridden by a previously installed
7185         * data, hide the system app now and let the /data/app scan pick it up
7186         * again.
7187         */
7188        if (shouldHideSystemApp) {
7189            synchronized (mPackages) {
7190                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7191            }
7192        }
7193
7194        return scannedPkg;
7195    }
7196
7197    private static String fixProcessName(String defProcessName,
7198            String processName, int uid) {
7199        if (processName == null) {
7200            return defProcessName;
7201        }
7202        return processName;
7203    }
7204
7205    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7206            throws PackageManagerException {
7207        if (pkgSetting.signatures.mSignatures != null) {
7208            // Already existing package. Make sure signatures match
7209            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7210                    == PackageManager.SIGNATURE_MATCH;
7211            if (!match) {
7212                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7213                        == PackageManager.SIGNATURE_MATCH;
7214            }
7215            if (!match) {
7216                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7217                        == PackageManager.SIGNATURE_MATCH;
7218            }
7219            if (!match) {
7220                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7221                        + pkg.packageName + " signatures do not match the "
7222                        + "previously installed version; ignoring!");
7223            }
7224        }
7225
7226        // Check for shared user signatures
7227        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7228            // Already existing package. Make sure signatures match
7229            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7230                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7231            if (!match) {
7232                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7233                        == PackageManager.SIGNATURE_MATCH;
7234            }
7235            if (!match) {
7236                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7237                        == PackageManager.SIGNATURE_MATCH;
7238            }
7239            if (!match) {
7240                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7241                        "Package " + pkg.packageName
7242                        + " has no signatures that match those in shared user "
7243                        + pkgSetting.sharedUser.name + "; ignoring!");
7244            }
7245        }
7246    }
7247
7248    /**
7249     * Enforces that only the system UID or root's UID can call a method exposed
7250     * via Binder.
7251     *
7252     * @param message used as message if SecurityException is thrown
7253     * @throws SecurityException if the caller is not system or root
7254     */
7255    private static final void enforceSystemOrRoot(String message) {
7256        final int uid = Binder.getCallingUid();
7257        if (uid != Process.SYSTEM_UID && uid != 0) {
7258            throw new SecurityException(message);
7259        }
7260    }
7261
7262    @Override
7263    public void performFstrimIfNeeded() {
7264        enforceSystemOrRoot("Only the system can request fstrim");
7265
7266        // Before everything else, see whether we need to fstrim.
7267        try {
7268            IMountService ms = PackageHelper.getMountService();
7269            if (ms != null) {
7270                final boolean isUpgrade = isUpgrade();
7271                boolean doTrim = isUpgrade;
7272                if (doTrim) {
7273                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7274                } else {
7275                    final long interval = android.provider.Settings.Global.getLong(
7276                            mContext.getContentResolver(),
7277                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7278                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7279                    if (interval > 0) {
7280                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7281                        if (timeSinceLast > interval) {
7282                            doTrim = true;
7283                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7284                                    + "; running immediately");
7285                        }
7286                    }
7287                }
7288                if (doTrim) {
7289                    if (!isFirstBoot()) {
7290                        try {
7291                            ActivityManagerNative.getDefault().showBootMessage(
7292                                    mContext.getResources().getString(
7293                                            R.string.android_upgrading_fstrim), true);
7294                        } catch (RemoteException e) {
7295                        }
7296                    }
7297                    ms.runMaintenance();
7298                }
7299            } else {
7300                Slog.e(TAG, "Mount service unavailable!");
7301            }
7302        } catch (RemoteException e) {
7303            // Can't happen; MountService is local
7304        }
7305    }
7306
7307    @Override
7308    public void updatePackagesIfNeeded() {
7309        enforceSystemOrRoot("Only the system can request package update");
7310
7311        // We need to re-extract after an OTA.
7312        boolean causeUpgrade = isUpgrade();
7313
7314        // First boot or factory reset.
7315        // Note: we also handle devices that are upgrading to N right now as if it is their
7316        //       first boot, as they do not have profile data.
7317        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7318
7319        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7320        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7321
7322        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7323            return;
7324        }
7325
7326        List<PackageParser.Package> pkgs;
7327        synchronized (mPackages) {
7328            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7329        }
7330
7331        final long startTime = System.nanoTime();
7332        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7333                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7334
7335        final int elapsedTimeSeconds =
7336                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7337
7338        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7339        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7340        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7341        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7342        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7343    }
7344
7345    /**
7346     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7347     * containing statistics about the invocation. The array consists of three elements,
7348     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7349     * and {@code numberOfPackagesFailed}.
7350     */
7351    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7352            String compilerFilter) {
7353
7354        int numberOfPackagesVisited = 0;
7355        int numberOfPackagesOptimized = 0;
7356        int numberOfPackagesSkipped = 0;
7357        int numberOfPackagesFailed = 0;
7358        final int numberOfPackagesToDexopt = pkgs.size();
7359
7360        for (PackageParser.Package pkg : pkgs) {
7361            numberOfPackagesVisited++;
7362
7363            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7364                if (DEBUG_DEXOPT) {
7365                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7366                }
7367                numberOfPackagesSkipped++;
7368                continue;
7369            }
7370
7371            if (DEBUG_DEXOPT) {
7372                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7373                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7374            }
7375
7376            if (showDialog) {
7377                try {
7378                    ActivityManagerNative.getDefault().showBootMessage(
7379                            mContext.getResources().getString(R.string.android_upgrading_apk,
7380                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7381                } catch (RemoteException e) {
7382                }
7383            }
7384
7385            // checkProfiles is false to avoid merging profiles during boot which
7386            // might interfere with background compilation (b/28612421).
7387            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7388            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7389            // trade-off worth doing to save boot time work.
7390            int dexOptStatus = performDexOptTraced(pkg.packageName,
7391                    false /* checkProfiles */,
7392                    compilerFilter,
7393                    false /* force */);
7394            switch (dexOptStatus) {
7395                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7396                    numberOfPackagesOptimized++;
7397                    break;
7398                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7399                    numberOfPackagesSkipped++;
7400                    break;
7401                case PackageDexOptimizer.DEX_OPT_FAILED:
7402                    numberOfPackagesFailed++;
7403                    break;
7404                default:
7405                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7406                    break;
7407            }
7408        }
7409
7410        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7411                numberOfPackagesFailed };
7412    }
7413
7414    @Override
7415    public void notifyPackageUse(String packageName, int reason) {
7416        synchronized (mPackages) {
7417            PackageParser.Package p = mPackages.get(packageName);
7418            if (p == null) {
7419                return;
7420            }
7421            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7422        }
7423    }
7424
7425    // TODO: this is not used nor needed. Delete it.
7426    @Override
7427    public boolean performDexOptIfNeeded(String packageName) {
7428        int dexOptStatus = performDexOptTraced(packageName,
7429                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7430        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7431    }
7432
7433    @Override
7434    public boolean performDexOpt(String packageName,
7435            boolean checkProfiles, int compileReason, boolean force) {
7436        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7437                getCompilerFilterForReason(compileReason), force);
7438        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7439    }
7440
7441    @Override
7442    public boolean performDexOptMode(String packageName,
7443            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7444        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7445                targetCompilerFilter, force);
7446        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7447    }
7448
7449    private int performDexOptTraced(String packageName,
7450                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7451        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7452        try {
7453            return performDexOptInternal(packageName, checkProfiles,
7454                    targetCompilerFilter, force);
7455        } finally {
7456            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7457        }
7458    }
7459
7460    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7461    // if the package can now be considered up to date for the given filter.
7462    private int performDexOptInternal(String packageName,
7463                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7464        PackageParser.Package p;
7465        synchronized (mPackages) {
7466            p = mPackages.get(packageName);
7467            if (p == null) {
7468                // Package could not be found. Report failure.
7469                return PackageDexOptimizer.DEX_OPT_FAILED;
7470            }
7471            mPackageUsage.write(false);
7472        }
7473        long callingId = Binder.clearCallingIdentity();
7474        try {
7475            synchronized (mInstallLock) {
7476                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7477                        targetCompilerFilter, force);
7478            }
7479        } finally {
7480            Binder.restoreCallingIdentity(callingId);
7481        }
7482    }
7483
7484    public ArraySet<String> getOptimizablePackages() {
7485        ArraySet<String> pkgs = new ArraySet<String>();
7486        synchronized (mPackages) {
7487            for (PackageParser.Package p : mPackages.values()) {
7488                if (PackageDexOptimizer.canOptimizePackage(p)) {
7489                    pkgs.add(p.packageName);
7490                }
7491            }
7492        }
7493        return pkgs;
7494    }
7495
7496    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7497            boolean checkProfiles, String targetCompilerFilter,
7498            boolean force) {
7499        // Select the dex optimizer based on the force parameter.
7500        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7501        //       allocate an object here.
7502        PackageDexOptimizer pdo = force
7503                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7504                : mPackageDexOptimizer;
7505
7506        // Optimize all dependencies first. Note: we ignore the return value and march on
7507        // on errors.
7508        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7509        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7510        if (!deps.isEmpty()) {
7511            for (PackageParser.Package depPackage : deps) {
7512                // TODO: Analyze and investigate if we (should) profile libraries.
7513                // Currently this will do a full compilation of the library by default.
7514                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7515                        false /* checkProfiles */,
7516                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7517            }
7518        }
7519        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7520                targetCompilerFilter);
7521    }
7522
7523    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7524        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7525            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7526            Set<String> collectedNames = new HashSet<>();
7527            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7528
7529            retValue.remove(p);
7530
7531            return retValue;
7532        } else {
7533            return Collections.emptyList();
7534        }
7535    }
7536
7537    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7538            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7539        if (!collectedNames.contains(p.packageName)) {
7540            collectedNames.add(p.packageName);
7541            collected.add(p);
7542
7543            if (p.usesLibraries != null) {
7544                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7545            }
7546            if (p.usesOptionalLibraries != null) {
7547                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7548                        collectedNames);
7549            }
7550        }
7551    }
7552
7553    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7554            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7555        for (String libName : libs) {
7556            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7557            if (libPkg != null) {
7558                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7559            }
7560        }
7561    }
7562
7563    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7564        synchronized (mPackages) {
7565            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7566            if (lib != null && lib.apk != null) {
7567                return mPackages.get(lib.apk);
7568            }
7569        }
7570        return null;
7571    }
7572
7573    public void shutdown() {
7574        mPackageUsage.write(true);
7575    }
7576
7577    @Override
7578    public void dumpProfiles(String packageName) {
7579        PackageParser.Package pkg;
7580        synchronized (mPackages) {
7581            pkg = mPackages.get(packageName);
7582            if (pkg == null) {
7583                throw new IllegalArgumentException("Unknown package: " + packageName);
7584            }
7585        }
7586        /* Only the shell, root, or the app user should be able to dump profiles. */
7587        int callingUid = Binder.getCallingUid();
7588        if (callingUid != Process.SHELL_UID &&
7589            callingUid != Process.ROOT_UID &&
7590            callingUid != pkg.applicationInfo.uid) {
7591            throw new SecurityException("dumpProfiles");
7592        }
7593
7594        synchronized (mInstallLock) {
7595            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7596            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7597            try {
7598                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7599                String gid = Integer.toString(sharedGid);
7600                String codePaths = TextUtils.join(";", allCodePaths);
7601                mInstaller.dumpProfiles(gid, packageName, codePaths);
7602            } catch (InstallerException e) {
7603                Slog.w(TAG, "Failed to dump profiles", e);
7604            }
7605            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7606        }
7607    }
7608
7609    @Override
7610    public void forceDexOpt(String packageName) {
7611        enforceSystemOrRoot("forceDexOpt");
7612
7613        PackageParser.Package pkg;
7614        synchronized (mPackages) {
7615            pkg = mPackages.get(packageName);
7616            if (pkg == null) {
7617                throw new IllegalArgumentException("Unknown package: " + packageName);
7618            }
7619        }
7620
7621        synchronized (mInstallLock) {
7622            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7623
7624            // Whoever is calling forceDexOpt wants a fully compiled package.
7625            // Don't use profiles since that may cause compilation to be skipped.
7626            final int res = performDexOptInternalWithDependenciesLI(pkg,
7627                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7628                    true /* force */);
7629
7630            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7631            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7632                throw new IllegalStateException("Failed to dexopt: " + res);
7633            }
7634        }
7635    }
7636
7637    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7638        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7639            Slog.w(TAG, "Unable to update from " + oldPkg.name
7640                    + " to " + newPkg.packageName
7641                    + ": old package not in system partition");
7642            return false;
7643        } else if (mPackages.get(oldPkg.name) != null) {
7644            Slog.w(TAG, "Unable to update from " + oldPkg.name
7645                    + " to " + newPkg.packageName
7646                    + ": old package still exists");
7647            return false;
7648        }
7649        return true;
7650    }
7651
7652    void removeCodePathLI(File codePath) {
7653        if (codePath.isDirectory()) {
7654            try {
7655                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7656            } catch (InstallerException e) {
7657                Slog.w(TAG, "Failed to remove code path", e);
7658            }
7659        } else {
7660            codePath.delete();
7661        }
7662    }
7663
7664    private int[] resolveUserIds(int userId) {
7665        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7666    }
7667
7668    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7669        if (pkg == null) {
7670            Slog.wtf(TAG, "Package was null!", new Throwable());
7671            return;
7672        }
7673        clearAppDataLeafLIF(pkg, userId, flags);
7674        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7675        for (int i = 0; i < childCount; i++) {
7676            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7677        }
7678    }
7679
7680    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7681        final PackageSetting ps;
7682        synchronized (mPackages) {
7683            ps = mSettings.mPackages.get(pkg.packageName);
7684        }
7685        for (int realUserId : resolveUserIds(userId)) {
7686            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7687            try {
7688                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7689                        ceDataInode);
7690            } catch (InstallerException e) {
7691                Slog.w(TAG, String.valueOf(e));
7692            }
7693        }
7694    }
7695
7696    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7697        if (pkg == null) {
7698            Slog.wtf(TAG, "Package was null!", new Throwable());
7699            return;
7700        }
7701        destroyAppDataLeafLIF(pkg, userId, flags);
7702        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7703        for (int i = 0; i < childCount; i++) {
7704            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7705        }
7706    }
7707
7708    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7709        final PackageSetting ps;
7710        synchronized (mPackages) {
7711            ps = mSettings.mPackages.get(pkg.packageName);
7712        }
7713        for (int realUserId : resolveUserIds(userId)) {
7714            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7715            try {
7716                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7717                        ceDataInode);
7718            } catch (InstallerException e) {
7719                Slog.w(TAG, String.valueOf(e));
7720            }
7721        }
7722    }
7723
7724    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7725        if (pkg == null) {
7726            Slog.wtf(TAG, "Package was null!", new Throwable());
7727            return;
7728        }
7729        destroyAppProfilesLeafLIF(pkg);
7730        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7731        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7732        for (int i = 0; i < childCount; i++) {
7733            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7734            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7735                    true /* removeBaseMarker */);
7736        }
7737    }
7738
7739    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7740            boolean removeBaseMarker) {
7741        if (pkg.isForwardLocked()) {
7742            return;
7743        }
7744
7745        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7746            try {
7747                path = PackageManagerServiceUtils.realpath(new File(path));
7748            } catch (IOException e) {
7749                // TODO: Should we return early here ?
7750                Slog.w(TAG, "Failed to get canonical path", e);
7751                continue;
7752            }
7753
7754            final String useMarker = path.replace('/', '@');
7755            for (int realUserId : resolveUserIds(userId)) {
7756                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7757                if (removeBaseMarker) {
7758                    File foreignUseMark = new File(profileDir, useMarker);
7759                    if (foreignUseMark.exists()) {
7760                        if (!foreignUseMark.delete()) {
7761                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7762                                    + pkg.packageName);
7763                        }
7764                    }
7765                }
7766
7767                File[] markers = profileDir.listFiles();
7768                if (markers != null) {
7769                    final String searchString = "@" + pkg.packageName + "@";
7770                    // We also delete all markers that contain the package name we're
7771                    // uninstalling. These are associated with secondary dex-files belonging
7772                    // to the package. Reconstructing the path of these dex files is messy
7773                    // in general.
7774                    for (File marker : markers) {
7775                        if (marker.getName().indexOf(searchString) > 0) {
7776                            if (!marker.delete()) {
7777                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7778                                    + pkg.packageName);
7779                            }
7780                        }
7781                    }
7782                }
7783            }
7784        }
7785    }
7786
7787    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7788        try {
7789            mInstaller.destroyAppProfiles(pkg.packageName);
7790        } catch (InstallerException e) {
7791            Slog.w(TAG, String.valueOf(e));
7792        }
7793    }
7794
7795    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7796        if (pkg == null) {
7797            Slog.wtf(TAG, "Package was null!", new Throwable());
7798            return;
7799        }
7800        clearAppProfilesLeafLIF(pkg);
7801        // We don't remove the base foreign use marker when clearing profiles because
7802        // we will rename it when the app is updated. Unlike the actual profile contents,
7803        // the foreign use marker is good across installs.
7804        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7805        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7806        for (int i = 0; i < childCount; i++) {
7807            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7808        }
7809    }
7810
7811    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7812        try {
7813            mInstaller.clearAppProfiles(pkg.packageName);
7814        } catch (InstallerException e) {
7815            Slog.w(TAG, String.valueOf(e));
7816        }
7817    }
7818
7819    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7820            long lastUpdateTime) {
7821        // Set parent install/update time
7822        PackageSetting ps = (PackageSetting) pkg.mExtras;
7823        if (ps != null) {
7824            ps.firstInstallTime = firstInstallTime;
7825            ps.lastUpdateTime = lastUpdateTime;
7826        }
7827        // Set children install/update time
7828        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7829        for (int i = 0; i < childCount; i++) {
7830            PackageParser.Package childPkg = pkg.childPackages.get(i);
7831            ps = (PackageSetting) childPkg.mExtras;
7832            if (ps != null) {
7833                ps.firstInstallTime = firstInstallTime;
7834                ps.lastUpdateTime = lastUpdateTime;
7835            }
7836        }
7837    }
7838
7839    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7840            PackageParser.Package changingLib) {
7841        if (file.path != null) {
7842            usesLibraryFiles.add(file.path);
7843            return;
7844        }
7845        PackageParser.Package p = mPackages.get(file.apk);
7846        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7847            // If we are doing this while in the middle of updating a library apk,
7848            // then we need to make sure to use that new apk for determining the
7849            // dependencies here.  (We haven't yet finished committing the new apk
7850            // to the package manager state.)
7851            if (p == null || p.packageName.equals(changingLib.packageName)) {
7852                p = changingLib;
7853            }
7854        }
7855        if (p != null) {
7856            usesLibraryFiles.addAll(p.getAllCodePaths());
7857        }
7858    }
7859
7860    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7861            PackageParser.Package changingLib) throws PackageManagerException {
7862        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7863            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7864            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7865            for (int i=0; i<N; i++) {
7866                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7867                if (file == null) {
7868                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7869                            "Package " + pkg.packageName + " requires unavailable shared library "
7870                            + pkg.usesLibraries.get(i) + "; failing!");
7871                }
7872                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7873            }
7874            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7875            for (int i=0; i<N; i++) {
7876                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7877                if (file == null) {
7878                    Slog.w(TAG, "Package " + pkg.packageName
7879                            + " desires unavailable shared library "
7880                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7881                } else {
7882                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7883                }
7884            }
7885            N = usesLibraryFiles.size();
7886            if (N > 0) {
7887                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7888            } else {
7889                pkg.usesLibraryFiles = null;
7890            }
7891        }
7892    }
7893
7894    private static boolean hasString(List<String> list, List<String> which) {
7895        if (list == null) {
7896            return false;
7897        }
7898        for (int i=list.size()-1; i>=0; i--) {
7899            for (int j=which.size()-1; j>=0; j--) {
7900                if (which.get(j).equals(list.get(i))) {
7901                    return true;
7902                }
7903            }
7904        }
7905        return false;
7906    }
7907
7908    private void updateAllSharedLibrariesLPw() {
7909        for (PackageParser.Package pkg : mPackages.values()) {
7910            try {
7911                updateSharedLibrariesLPw(pkg, null);
7912            } catch (PackageManagerException e) {
7913                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7914            }
7915        }
7916    }
7917
7918    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7919            PackageParser.Package changingPkg) {
7920        ArrayList<PackageParser.Package> res = null;
7921        for (PackageParser.Package pkg : mPackages.values()) {
7922            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7923                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7924                if (res == null) {
7925                    res = new ArrayList<PackageParser.Package>();
7926                }
7927                res.add(pkg);
7928                try {
7929                    updateSharedLibrariesLPw(pkg, changingPkg);
7930                } catch (PackageManagerException e) {
7931                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7932                }
7933            }
7934        }
7935        return res;
7936    }
7937
7938    /**
7939     * Derive the value of the {@code cpuAbiOverride} based on the provided
7940     * value and an optional stored value from the package settings.
7941     */
7942    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7943        String cpuAbiOverride = null;
7944
7945        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7946            cpuAbiOverride = null;
7947        } else if (abiOverride != null) {
7948            cpuAbiOverride = abiOverride;
7949        } else if (settings != null) {
7950            cpuAbiOverride = settings.cpuAbiOverrideString;
7951        }
7952
7953        return cpuAbiOverride;
7954    }
7955
7956    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7957            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7958                    throws PackageManagerException {
7959        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7960        // If the package has children and this is the first dive in the function
7961        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7962        // whether all packages (parent and children) would be successfully scanned
7963        // before the actual scan since scanning mutates internal state and we want
7964        // to atomically install the package and its children.
7965        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7966            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7967                scanFlags |= SCAN_CHECK_ONLY;
7968            }
7969        } else {
7970            scanFlags &= ~SCAN_CHECK_ONLY;
7971        }
7972
7973        final PackageParser.Package scannedPkg;
7974        try {
7975            // Scan the parent
7976            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7977            // Scan the children
7978            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7979            for (int i = 0; i < childCount; i++) {
7980                PackageParser.Package childPkg = pkg.childPackages.get(i);
7981                scanPackageLI(childPkg, policyFlags,
7982                        scanFlags, currentTime, user);
7983            }
7984        } finally {
7985            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7986        }
7987
7988        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7989            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7990        }
7991
7992        return scannedPkg;
7993    }
7994
7995    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7996            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7997        boolean success = false;
7998        try {
7999            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8000                    currentTime, user);
8001            success = true;
8002            return res;
8003        } finally {
8004            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8005                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8006                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8007                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8008                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8009            }
8010        }
8011    }
8012
8013    /**
8014     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8015     */
8016    private static boolean apkHasCode(String fileName) {
8017        StrictJarFile jarFile = null;
8018        try {
8019            jarFile = new StrictJarFile(fileName,
8020                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8021            return jarFile.findEntry("classes.dex") != null;
8022        } catch (IOException ignore) {
8023        } finally {
8024            try {
8025                if (jarFile != null) {
8026                    jarFile.close();
8027                }
8028            } catch (IOException ignore) {}
8029        }
8030        return false;
8031    }
8032
8033    /**
8034     * Enforces code policy for the package. This ensures that if an APK has
8035     * declared hasCode="true" in its manifest that the APK actually contains
8036     * code.
8037     *
8038     * @throws PackageManagerException If bytecode could not be found when it should exist
8039     */
8040    private static void enforceCodePolicy(PackageParser.Package pkg)
8041            throws PackageManagerException {
8042        final boolean shouldHaveCode =
8043                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8044        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8045            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8046                    "Package " + pkg.baseCodePath + " code is missing");
8047        }
8048
8049        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8050            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8051                final boolean splitShouldHaveCode =
8052                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8053                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8054                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8055                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8056                }
8057            }
8058        }
8059    }
8060
8061    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8062            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8063            throws PackageManagerException {
8064        final File scanFile = new File(pkg.codePath);
8065        if (pkg.applicationInfo.getCodePath() == null ||
8066                pkg.applicationInfo.getResourcePath() == null) {
8067            // Bail out. The resource and code paths haven't been set.
8068            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8069                    "Code and resource paths haven't been set correctly");
8070        }
8071
8072        // Apply policy
8073        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8074            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8075            if (pkg.applicationInfo.isDirectBootAware()) {
8076                // we're direct boot aware; set for all components
8077                for (PackageParser.Service s : pkg.services) {
8078                    s.info.encryptionAware = s.info.directBootAware = true;
8079                }
8080                for (PackageParser.Provider p : pkg.providers) {
8081                    p.info.encryptionAware = p.info.directBootAware = true;
8082                }
8083                for (PackageParser.Activity a : pkg.activities) {
8084                    a.info.encryptionAware = a.info.directBootAware = true;
8085                }
8086                for (PackageParser.Activity r : pkg.receivers) {
8087                    r.info.encryptionAware = r.info.directBootAware = true;
8088                }
8089            }
8090        } else {
8091            // Only allow system apps to be flagged as core apps.
8092            pkg.coreApp = false;
8093            // clear flags not applicable to regular apps
8094            pkg.applicationInfo.privateFlags &=
8095                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8096            pkg.applicationInfo.privateFlags &=
8097                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8098        }
8099        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8100
8101        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8102            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8103        }
8104
8105        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8106            enforceCodePolicy(pkg);
8107        }
8108
8109        if (mCustomResolverComponentName != null &&
8110                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8111            setUpCustomResolverActivity(pkg);
8112        }
8113
8114        if (pkg.packageName.equals("android")) {
8115            synchronized (mPackages) {
8116                if (mAndroidApplication != null) {
8117                    Slog.w(TAG, "*************************************************");
8118                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8119                    Slog.w(TAG, " file=" + scanFile);
8120                    Slog.w(TAG, "*************************************************");
8121                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8122                            "Core android package being redefined.  Skipping.");
8123                }
8124
8125                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8126                    // Set up information for our fall-back user intent resolution activity.
8127                    mPlatformPackage = pkg;
8128                    pkg.mVersionCode = mSdkVersion;
8129                    mAndroidApplication = pkg.applicationInfo;
8130
8131                    if (!mResolverReplaced) {
8132                        mResolveActivity.applicationInfo = mAndroidApplication;
8133                        mResolveActivity.name = ResolverActivity.class.getName();
8134                        mResolveActivity.packageName = mAndroidApplication.packageName;
8135                        mResolveActivity.processName = "system:ui";
8136                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8137                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8138                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8139                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8140                        mResolveActivity.exported = true;
8141                        mResolveActivity.enabled = true;
8142                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8143                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8144                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8145                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8146                                | ActivityInfo.CONFIG_ORIENTATION
8147                                | ActivityInfo.CONFIG_KEYBOARD
8148                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8149                        mResolveInfo.activityInfo = mResolveActivity;
8150                        mResolveInfo.priority = 0;
8151                        mResolveInfo.preferredOrder = 0;
8152                        mResolveInfo.match = 0;
8153                        mResolveComponentName = new ComponentName(
8154                                mAndroidApplication.packageName, mResolveActivity.name);
8155                    }
8156                }
8157            }
8158        }
8159
8160        if (DEBUG_PACKAGE_SCANNING) {
8161            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8162                Log.d(TAG, "Scanning package " + pkg.packageName);
8163        }
8164
8165        synchronized (mPackages) {
8166            if (mPackages.containsKey(pkg.packageName)
8167                    || mSharedLibraries.containsKey(pkg.packageName)) {
8168                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8169                        "Application package " + pkg.packageName
8170                                + " already installed.  Skipping duplicate.");
8171            }
8172
8173            // If we're only installing presumed-existing packages, require that the
8174            // scanned APK is both already known and at the path previously established
8175            // for it.  Previously unknown packages we pick up normally, but if we have an
8176            // a priori expectation about this package's install presence, enforce it.
8177            // With a singular exception for new system packages. When an OTA contains
8178            // a new system package, we allow the codepath to change from a system location
8179            // to the user-installed location. If we don't allow this change, any newer,
8180            // user-installed version of the application will be ignored.
8181            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8182                if (mExpectingBetter.containsKey(pkg.packageName)) {
8183                    logCriticalInfo(Log.WARN,
8184                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8185                } else {
8186                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8187                    if (known != null) {
8188                        if (DEBUG_PACKAGE_SCANNING) {
8189                            Log.d(TAG, "Examining " + pkg.codePath
8190                                    + " and requiring known paths " + known.codePathString
8191                                    + " & " + known.resourcePathString);
8192                        }
8193                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8194                                || !pkg.applicationInfo.getResourcePath().equals(
8195                                known.resourcePathString)) {
8196                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8197                                    "Application package " + pkg.packageName
8198                                            + " found at " + pkg.applicationInfo.getCodePath()
8199                                            + " but expected at " + known.codePathString
8200                                            + "; ignoring.");
8201                        }
8202                    }
8203                }
8204            }
8205        }
8206
8207        // Initialize package source and resource directories
8208        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8209        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8210
8211        SharedUserSetting suid = null;
8212        PackageSetting pkgSetting = null;
8213
8214        if (!isSystemApp(pkg)) {
8215            // Only system apps can use these features.
8216            pkg.mOriginalPackages = null;
8217            pkg.mRealPackage = null;
8218            pkg.mAdoptPermissions = null;
8219        }
8220
8221        // Getting the package setting may have a side-effect, so if we
8222        // are only checking if scan would succeed, stash a copy of the
8223        // old setting to restore at the end.
8224        PackageSetting nonMutatedPs = null;
8225
8226        // writer
8227        synchronized (mPackages) {
8228            if (pkg.mSharedUserId != null) {
8229                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8230                if (suid == null) {
8231                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8232                            "Creating application package " + pkg.packageName
8233                            + " for shared user failed");
8234                }
8235                if (DEBUG_PACKAGE_SCANNING) {
8236                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8237                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8238                                + "): packages=" + suid.packages);
8239                }
8240            }
8241
8242            // Check if we are renaming from an original package name.
8243            PackageSetting origPackage = null;
8244            String realName = null;
8245            if (pkg.mOriginalPackages != null) {
8246                // This package may need to be renamed to a previously
8247                // installed name.  Let's check on that...
8248                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8249                if (pkg.mOriginalPackages.contains(renamed)) {
8250                    // This package had originally been installed as the
8251                    // original name, and we have already taken care of
8252                    // transitioning to the new one.  Just update the new
8253                    // one to continue using the old name.
8254                    realName = pkg.mRealPackage;
8255                    if (!pkg.packageName.equals(renamed)) {
8256                        // Callers into this function may have already taken
8257                        // care of renaming the package; only do it here if
8258                        // it is not already done.
8259                        pkg.setPackageName(renamed);
8260                    }
8261
8262                } else {
8263                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8264                        if ((origPackage = mSettings.peekPackageLPr(
8265                                pkg.mOriginalPackages.get(i))) != null) {
8266                            // We do have the package already installed under its
8267                            // original name...  should we use it?
8268                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8269                                // New package is not compatible with original.
8270                                origPackage = null;
8271                                continue;
8272                            } else if (origPackage.sharedUser != null) {
8273                                // Make sure uid is compatible between packages.
8274                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8275                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8276                                            + " to " + pkg.packageName + ": old uid "
8277                                            + origPackage.sharedUser.name
8278                                            + " differs from " + pkg.mSharedUserId);
8279                                    origPackage = null;
8280                                    continue;
8281                                }
8282                                // TODO: Add case when shared user id is added [b/28144775]
8283                            } else {
8284                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8285                                        + pkg.packageName + " to old name " + origPackage.name);
8286                            }
8287                            break;
8288                        }
8289                    }
8290                }
8291            }
8292
8293            if (mTransferedPackages.contains(pkg.packageName)) {
8294                Slog.w(TAG, "Package " + pkg.packageName
8295                        + " was transferred to another, but its .apk remains");
8296            }
8297
8298            // See comments in nonMutatedPs declaration
8299            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8300                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8301                if (foundPs != null) {
8302                    nonMutatedPs = new PackageSetting(foundPs);
8303                }
8304            }
8305
8306            // Just create the setting, don't add it yet. For already existing packages
8307            // the PkgSetting exists already and doesn't have to be created.
8308            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8309                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8310                    pkg.applicationInfo.primaryCpuAbi,
8311                    pkg.applicationInfo.secondaryCpuAbi,
8312                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8313                    user, false);
8314            if (pkgSetting == null) {
8315                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8316                        "Creating application package " + pkg.packageName + " failed");
8317            }
8318
8319            if (pkgSetting.origPackage != null) {
8320                // If we are first transitioning from an original package,
8321                // fix up the new package's name now.  We need to do this after
8322                // looking up the package under its new name, so getPackageLP
8323                // can take care of fiddling things correctly.
8324                pkg.setPackageName(origPackage.name);
8325
8326                // File a report about this.
8327                String msg = "New package " + pkgSetting.realName
8328                        + " renamed to replace old package " + pkgSetting.name;
8329                reportSettingsProblem(Log.WARN, msg);
8330
8331                // Make a note of it.
8332                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8333                    mTransferedPackages.add(origPackage.name);
8334                }
8335
8336                // No longer need to retain this.
8337                pkgSetting.origPackage = null;
8338            }
8339
8340            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8341                // Make a note of it.
8342                mTransferedPackages.add(pkg.packageName);
8343            }
8344
8345            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8346                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8347            }
8348
8349            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8350                // Check all shared libraries and map to their actual file path.
8351                // We only do this here for apps not on a system dir, because those
8352                // are the only ones that can fail an install due to this.  We
8353                // will take care of the system apps by updating all of their
8354                // library paths after the scan is done.
8355                updateSharedLibrariesLPw(pkg, null);
8356            }
8357
8358            if (mFoundPolicyFile) {
8359                SELinuxMMAC.assignSeinfoValue(pkg);
8360            }
8361
8362            pkg.applicationInfo.uid = pkgSetting.appId;
8363            pkg.mExtras = pkgSetting;
8364            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8365                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8366                    // We just determined the app is signed correctly, so bring
8367                    // over the latest parsed certs.
8368                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8369                } else {
8370                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8371                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8372                                "Package " + pkg.packageName + " upgrade keys do not match the "
8373                                + "previously installed version");
8374                    } else {
8375                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8376                        String msg = "System package " + pkg.packageName
8377                            + " signature changed; retaining data.";
8378                        reportSettingsProblem(Log.WARN, msg);
8379                    }
8380                }
8381            } else {
8382                try {
8383                    verifySignaturesLP(pkgSetting, pkg);
8384                    // We just determined the app is signed correctly, so bring
8385                    // over the latest parsed certs.
8386                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8387                } catch (PackageManagerException e) {
8388                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8389                        throw e;
8390                    }
8391                    // The signature has changed, but this package is in the system
8392                    // image...  let's recover!
8393                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8394                    // However...  if this package is part of a shared user, but it
8395                    // doesn't match the signature of the shared user, let's fail.
8396                    // What this means is that you can't change the signatures
8397                    // associated with an overall shared user, which doesn't seem all
8398                    // that unreasonable.
8399                    if (pkgSetting.sharedUser != null) {
8400                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8401                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8402                            throw new PackageManagerException(
8403                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8404                                            "Signature mismatch for shared user: "
8405                                            + pkgSetting.sharedUser);
8406                        }
8407                    }
8408                    // File a report about this.
8409                    String msg = "System package " + pkg.packageName
8410                        + " signature changed; retaining data.";
8411                    reportSettingsProblem(Log.WARN, msg);
8412                }
8413            }
8414            // Verify that this new package doesn't have any content providers
8415            // that conflict with existing packages.  Only do this if the
8416            // package isn't already installed, since we don't want to break
8417            // things that are installed.
8418            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8419                final int N = pkg.providers.size();
8420                int i;
8421                for (i=0; i<N; i++) {
8422                    PackageParser.Provider p = pkg.providers.get(i);
8423                    if (p.info.authority != null) {
8424                        String names[] = p.info.authority.split(";");
8425                        for (int j = 0; j < names.length; j++) {
8426                            if (mProvidersByAuthority.containsKey(names[j])) {
8427                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8428                                final String otherPackageName =
8429                                        ((other != null && other.getComponentName() != null) ?
8430                                                other.getComponentName().getPackageName() : "?");
8431                                throw new PackageManagerException(
8432                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8433                                                "Can't install because provider name " + names[j]
8434                                                + " (in package " + pkg.applicationInfo.packageName
8435                                                + ") is already used by " + otherPackageName);
8436                            }
8437                        }
8438                    }
8439                }
8440            }
8441
8442            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8443                // This package wants to adopt ownership of permissions from
8444                // another package.
8445                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8446                    final String origName = pkg.mAdoptPermissions.get(i);
8447                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8448                    if (orig != null) {
8449                        if (verifyPackageUpdateLPr(orig, pkg)) {
8450                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8451                                    + pkg.packageName);
8452                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8453                        }
8454                    }
8455                }
8456            }
8457        }
8458
8459        final String pkgName = pkg.packageName;
8460
8461        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8462        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8463        pkg.applicationInfo.processName = fixProcessName(
8464                pkg.applicationInfo.packageName,
8465                pkg.applicationInfo.processName,
8466                pkg.applicationInfo.uid);
8467
8468        if (pkg != mPlatformPackage) {
8469            // Get all of our default paths setup
8470            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8471        }
8472
8473        final String path = scanFile.getPath();
8474        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8475
8476        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8477            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8478
8479            // Some system apps still use directory structure for native libraries
8480            // in which case we might end up not detecting abi solely based on apk
8481            // structure. Try to detect abi based on directory structure.
8482            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8483                    pkg.applicationInfo.primaryCpuAbi == null) {
8484                setBundledAppAbisAndRoots(pkg, pkgSetting);
8485                setNativeLibraryPaths(pkg);
8486            }
8487
8488        } else {
8489            if ((scanFlags & SCAN_MOVE) != 0) {
8490                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8491                // but we already have this packages package info in the PackageSetting. We just
8492                // use that and derive the native library path based on the new codepath.
8493                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8494                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8495            }
8496
8497            // Set native library paths again. For moves, the path will be updated based on the
8498            // ABIs we've determined above. For non-moves, the path will be updated based on the
8499            // ABIs we determined during compilation, but the path will depend on the final
8500            // package path (after the rename away from the stage path).
8501            setNativeLibraryPaths(pkg);
8502        }
8503
8504        // This is a special case for the "system" package, where the ABI is
8505        // dictated by the zygote configuration (and init.rc). We should keep track
8506        // of this ABI so that we can deal with "normal" applications that run under
8507        // the same UID correctly.
8508        if (mPlatformPackage == pkg) {
8509            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8510                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8511        }
8512
8513        // If there's a mismatch between the abi-override in the package setting
8514        // and the abiOverride specified for the install. Warn about this because we
8515        // would've already compiled the app without taking the package setting into
8516        // account.
8517        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8518            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8519                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8520                        " for package " + pkg.packageName);
8521            }
8522        }
8523
8524        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8525        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8526        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8527
8528        // Copy the derived override back to the parsed package, so that we can
8529        // update the package settings accordingly.
8530        pkg.cpuAbiOverride = cpuAbiOverride;
8531
8532        if (DEBUG_ABI_SELECTION) {
8533            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8534                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8535                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8536        }
8537
8538        // Push the derived path down into PackageSettings so we know what to
8539        // clean up at uninstall time.
8540        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8541
8542        if (DEBUG_ABI_SELECTION) {
8543            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8544                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8545                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8546        }
8547
8548        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8549            // We don't do this here during boot because we can do it all
8550            // at once after scanning all existing packages.
8551            //
8552            // We also do this *before* we perform dexopt on this package, so that
8553            // we can avoid redundant dexopts, and also to make sure we've got the
8554            // code and package path correct.
8555            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8556                    pkg, true /* boot complete */);
8557        }
8558
8559        if (mFactoryTest && pkg.requestedPermissions.contains(
8560                android.Manifest.permission.FACTORY_TEST)) {
8561            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8562        }
8563
8564        ArrayList<PackageParser.Package> clientLibPkgs = null;
8565
8566        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8567            if (nonMutatedPs != null) {
8568                synchronized (mPackages) {
8569                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8570                }
8571            }
8572            return pkg;
8573        }
8574
8575        // Only privileged apps and updated privileged apps can add child packages.
8576        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8577            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8578                throw new PackageManagerException("Only privileged apps and updated "
8579                        + "privileged apps can add child packages. Ignoring package "
8580                        + pkg.packageName);
8581            }
8582            final int childCount = pkg.childPackages.size();
8583            for (int i = 0; i < childCount; i++) {
8584                PackageParser.Package childPkg = pkg.childPackages.get(i);
8585                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8586                        childPkg.packageName)) {
8587                    throw new PackageManagerException("Cannot override a child package of "
8588                            + "another disabled system app. Ignoring package " + pkg.packageName);
8589                }
8590            }
8591        }
8592
8593        // writer
8594        synchronized (mPackages) {
8595            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8596                // Only system apps can add new shared libraries.
8597                if (pkg.libraryNames != null) {
8598                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8599                        String name = pkg.libraryNames.get(i);
8600                        boolean allowed = false;
8601                        if (pkg.isUpdatedSystemApp()) {
8602                            // New library entries can only be added through the
8603                            // system image.  This is important to get rid of a lot
8604                            // of nasty edge cases: for example if we allowed a non-
8605                            // system update of the app to add a library, then uninstalling
8606                            // the update would make the library go away, and assumptions
8607                            // we made such as through app install filtering would now
8608                            // have allowed apps on the device which aren't compatible
8609                            // with it.  Better to just have the restriction here, be
8610                            // conservative, and create many fewer cases that can negatively
8611                            // impact the user experience.
8612                            final PackageSetting sysPs = mSettings
8613                                    .getDisabledSystemPkgLPr(pkg.packageName);
8614                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8615                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8616                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8617                                        allowed = true;
8618                                        break;
8619                                    }
8620                                }
8621                            }
8622                        } else {
8623                            allowed = true;
8624                        }
8625                        if (allowed) {
8626                            if (!mSharedLibraries.containsKey(name)) {
8627                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8628                            } else if (!name.equals(pkg.packageName)) {
8629                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8630                                        + name + " already exists; skipping");
8631                            }
8632                        } else {
8633                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8634                                    + name + " that is not declared on system image; skipping");
8635                        }
8636                    }
8637                    if ((scanFlags & SCAN_BOOTING) == 0) {
8638                        // If we are not booting, we need to update any applications
8639                        // that are clients of our shared library.  If we are booting,
8640                        // this will all be done once the scan is complete.
8641                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8642                    }
8643                }
8644            }
8645        }
8646
8647        if ((scanFlags & SCAN_BOOTING) != 0) {
8648            // No apps can run during boot scan, so they don't need to be frozen
8649        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8650            // Caller asked to not kill app, so it's probably not frozen
8651        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8652            // Caller asked us to ignore frozen check for some reason; they
8653            // probably didn't know the package name
8654        } else {
8655            // We're doing major surgery on this package, so it better be frozen
8656            // right now to keep it from launching
8657            checkPackageFrozen(pkgName);
8658        }
8659
8660        // Also need to kill any apps that are dependent on the library.
8661        if (clientLibPkgs != null) {
8662            for (int i=0; i<clientLibPkgs.size(); i++) {
8663                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8664                killApplication(clientPkg.applicationInfo.packageName,
8665                        clientPkg.applicationInfo.uid, "update lib");
8666            }
8667        }
8668
8669        // Make sure we're not adding any bogus keyset info
8670        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8671        ksms.assertScannedPackageValid(pkg);
8672
8673        // writer
8674        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8675
8676        boolean createIdmapFailed = false;
8677        synchronized (mPackages) {
8678            // We don't expect installation to fail beyond this point
8679
8680            if (pkgSetting.pkg != null) {
8681                // Note that |user| might be null during the initial boot scan. If a codePath
8682                // for an app has changed during a boot scan, it's due to an app update that's
8683                // part of the system partition and marker changes must be applied to all users.
8684                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8685                    (user != null) ? user : UserHandle.ALL);
8686            }
8687
8688            // Add the new setting to mSettings
8689            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8690            // Add the new setting to mPackages
8691            mPackages.put(pkg.applicationInfo.packageName, pkg);
8692            // Make sure we don't accidentally delete its data.
8693            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8694            while (iter.hasNext()) {
8695                PackageCleanItem item = iter.next();
8696                if (pkgName.equals(item.packageName)) {
8697                    iter.remove();
8698                }
8699            }
8700
8701            // Take care of first install / last update times.
8702            if (currentTime != 0) {
8703                if (pkgSetting.firstInstallTime == 0) {
8704                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8705                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8706                    pkgSetting.lastUpdateTime = currentTime;
8707                }
8708            } else if (pkgSetting.firstInstallTime == 0) {
8709                // We need *something*.  Take time time stamp of the file.
8710                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8711            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8712                if (scanFileTime != pkgSetting.timeStamp) {
8713                    // A package on the system image has changed; consider this
8714                    // to be an update.
8715                    pkgSetting.lastUpdateTime = scanFileTime;
8716                }
8717            }
8718
8719            // Add the package's KeySets to the global KeySetManagerService
8720            ksms.addScannedPackageLPw(pkg);
8721
8722            int N = pkg.providers.size();
8723            StringBuilder r = null;
8724            int i;
8725            for (i=0; i<N; i++) {
8726                PackageParser.Provider p = pkg.providers.get(i);
8727                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8728                        p.info.processName, pkg.applicationInfo.uid);
8729                mProviders.addProvider(p);
8730                p.syncable = p.info.isSyncable;
8731                if (p.info.authority != null) {
8732                    String names[] = p.info.authority.split(";");
8733                    p.info.authority = null;
8734                    for (int j = 0; j < names.length; j++) {
8735                        if (j == 1 && p.syncable) {
8736                            // We only want the first authority for a provider to possibly be
8737                            // syncable, so if we already added this provider using a different
8738                            // authority clear the syncable flag. We copy the provider before
8739                            // changing it because the mProviders object contains a reference
8740                            // to a provider that we don't want to change.
8741                            // Only do this for the second authority since the resulting provider
8742                            // object can be the same for all future authorities for this provider.
8743                            p = new PackageParser.Provider(p);
8744                            p.syncable = false;
8745                        }
8746                        if (!mProvidersByAuthority.containsKey(names[j])) {
8747                            mProvidersByAuthority.put(names[j], p);
8748                            if (p.info.authority == null) {
8749                                p.info.authority = names[j];
8750                            } else {
8751                                p.info.authority = p.info.authority + ";" + names[j];
8752                            }
8753                            if (DEBUG_PACKAGE_SCANNING) {
8754                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8755                                    Log.d(TAG, "Registered content provider: " + names[j]
8756                                            + ", className = " + p.info.name + ", isSyncable = "
8757                                            + p.info.isSyncable);
8758                            }
8759                        } else {
8760                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8761                            Slog.w(TAG, "Skipping provider name " + names[j] +
8762                                    " (in package " + pkg.applicationInfo.packageName +
8763                                    "): name already used by "
8764                                    + ((other != null && other.getComponentName() != null)
8765                                            ? other.getComponentName().getPackageName() : "?"));
8766                        }
8767                    }
8768                }
8769                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8770                    if (r == null) {
8771                        r = new StringBuilder(256);
8772                    } else {
8773                        r.append(' ');
8774                    }
8775                    r.append(p.info.name);
8776                }
8777            }
8778            if (r != null) {
8779                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8780            }
8781
8782            N = pkg.services.size();
8783            r = null;
8784            for (i=0; i<N; i++) {
8785                PackageParser.Service s = pkg.services.get(i);
8786                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8787                        s.info.processName, pkg.applicationInfo.uid);
8788                mServices.addService(s);
8789                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8790                    if (r == null) {
8791                        r = new StringBuilder(256);
8792                    } else {
8793                        r.append(' ');
8794                    }
8795                    r.append(s.info.name);
8796                }
8797            }
8798            if (r != null) {
8799                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8800            }
8801
8802            N = pkg.receivers.size();
8803            r = null;
8804            for (i=0; i<N; i++) {
8805                PackageParser.Activity a = pkg.receivers.get(i);
8806                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8807                        a.info.processName, pkg.applicationInfo.uid);
8808                mReceivers.addActivity(a, "receiver");
8809                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8810                    if (r == null) {
8811                        r = new StringBuilder(256);
8812                    } else {
8813                        r.append(' ');
8814                    }
8815                    r.append(a.info.name);
8816                }
8817            }
8818            if (r != null) {
8819                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8820            }
8821
8822            N = pkg.activities.size();
8823            r = null;
8824            for (i=0; i<N; i++) {
8825                PackageParser.Activity a = pkg.activities.get(i);
8826                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8827                        a.info.processName, pkg.applicationInfo.uid);
8828                mActivities.addActivity(a, "activity");
8829                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8830                    if (r == null) {
8831                        r = new StringBuilder(256);
8832                    } else {
8833                        r.append(' ');
8834                    }
8835                    r.append(a.info.name);
8836                }
8837            }
8838            if (r != null) {
8839                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8840            }
8841
8842            N = pkg.permissionGroups.size();
8843            r = null;
8844            for (i=0; i<N; i++) {
8845                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8846                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8847                if (cur == null) {
8848                    mPermissionGroups.put(pg.info.name, pg);
8849                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8850                        if (r == null) {
8851                            r = new StringBuilder(256);
8852                        } else {
8853                            r.append(' ');
8854                        }
8855                        r.append(pg.info.name);
8856                    }
8857                } else {
8858                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8859                            + pg.info.packageName + " ignored: original from "
8860                            + cur.info.packageName);
8861                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8862                        if (r == null) {
8863                            r = new StringBuilder(256);
8864                        } else {
8865                            r.append(' ');
8866                        }
8867                        r.append("DUP:");
8868                        r.append(pg.info.name);
8869                    }
8870                }
8871            }
8872            if (r != null) {
8873                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8874            }
8875
8876            N = pkg.permissions.size();
8877            r = null;
8878            for (i=0; i<N; i++) {
8879                PackageParser.Permission p = pkg.permissions.get(i);
8880
8881                // Assume by default that we did not install this permission into the system.
8882                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8883
8884                // Now that permission groups have a special meaning, we ignore permission
8885                // groups for legacy apps to prevent unexpected behavior. In particular,
8886                // permissions for one app being granted to someone just becase they happen
8887                // to be in a group defined by another app (before this had no implications).
8888                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8889                    p.group = mPermissionGroups.get(p.info.group);
8890                    // Warn for a permission in an unknown group.
8891                    if (p.info.group != null && p.group == null) {
8892                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8893                                + p.info.packageName + " in an unknown group " + p.info.group);
8894                    }
8895                }
8896
8897                ArrayMap<String, BasePermission> permissionMap =
8898                        p.tree ? mSettings.mPermissionTrees
8899                                : mSettings.mPermissions;
8900                BasePermission bp = permissionMap.get(p.info.name);
8901
8902                // Allow system apps to redefine non-system permissions
8903                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8904                    final boolean currentOwnerIsSystem = (bp.perm != null
8905                            && isSystemApp(bp.perm.owner));
8906                    if (isSystemApp(p.owner)) {
8907                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8908                            // It's a built-in permission and no owner, take ownership now
8909                            bp.packageSetting = pkgSetting;
8910                            bp.perm = p;
8911                            bp.uid = pkg.applicationInfo.uid;
8912                            bp.sourcePackage = p.info.packageName;
8913                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8914                        } else if (!currentOwnerIsSystem) {
8915                            String msg = "New decl " + p.owner + " of permission  "
8916                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8917                            reportSettingsProblem(Log.WARN, msg);
8918                            bp = null;
8919                        }
8920                    }
8921                }
8922
8923                if (bp == null) {
8924                    bp = new BasePermission(p.info.name, p.info.packageName,
8925                            BasePermission.TYPE_NORMAL);
8926                    permissionMap.put(p.info.name, bp);
8927                }
8928
8929                if (bp.perm == null) {
8930                    if (bp.sourcePackage == null
8931                            || bp.sourcePackage.equals(p.info.packageName)) {
8932                        BasePermission tree = findPermissionTreeLP(p.info.name);
8933                        if (tree == null
8934                                || tree.sourcePackage.equals(p.info.packageName)) {
8935                            bp.packageSetting = pkgSetting;
8936                            bp.perm = p;
8937                            bp.uid = pkg.applicationInfo.uid;
8938                            bp.sourcePackage = p.info.packageName;
8939                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8940                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8941                                if (r == null) {
8942                                    r = new StringBuilder(256);
8943                                } else {
8944                                    r.append(' ');
8945                                }
8946                                r.append(p.info.name);
8947                            }
8948                        } else {
8949                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8950                                    + p.info.packageName + " ignored: base tree "
8951                                    + tree.name + " is from package "
8952                                    + tree.sourcePackage);
8953                        }
8954                    } else {
8955                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8956                                + p.info.packageName + " ignored: original from "
8957                                + bp.sourcePackage);
8958                    }
8959                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8960                    if (r == null) {
8961                        r = new StringBuilder(256);
8962                    } else {
8963                        r.append(' ');
8964                    }
8965                    r.append("DUP:");
8966                    r.append(p.info.name);
8967                }
8968                if (bp.perm == p) {
8969                    bp.protectionLevel = p.info.protectionLevel;
8970                }
8971            }
8972
8973            if (r != null) {
8974                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8975            }
8976
8977            N = pkg.instrumentation.size();
8978            r = null;
8979            for (i=0; i<N; i++) {
8980                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8981                a.info.packageName = pkg.applicationInfo.packageName;
8982                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8983                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8984                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8985                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8986                a.info.dataDir = pkg.applicationInfo.dataDir;
8987                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8988                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8989
8990                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8991                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8992                mInstrumentation.put(a.getComponentName(), a);
8993                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8994                    if (r == null) {
8995                        r = new StringBuilder(256);
8996                    } else {
8997                        r.append(' ');
8998                    }
8999                    r.append(a.info.name);
9000                }
9001            }
9002            if (r != null) {
9003                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9004            }
9005
9006            if (pkg.protectedBroadcasts != null) {
9007                N = pkg.protectedBroadcasts.size();
9008                for (i=0; i<N; i++) {
9009                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9010                }
9011            }
9012
9013            pkgSetting.setTimeStamp(scanFileTime);
9014
9015            // Create idmap files for pairs of (packages, overlay packages).
9016            // Note: "android", ie framework-res.apk, is handled by native layers.
9017            if (pkg.mOverlayTarget != null) {
9018                // This is an overlay package.
9019                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9020                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9021                        mOverlays.put(pkg.mOverlayTarget,
9022                                new ArrayMap<String, PackageParser.Package>());
9023                    }
9024                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9025                    map.put(pkg.packageName, pkg);
9026                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9027                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9028                        createIdmapFailed = true;
9029                    }
9030                }
9031            } else if (mOverlays.containsKey(pkg.packageName) &&
9032                    !pkg.packageName.equals("android")) {
9033                // This is a regular package, with one or more known overlay packages.
9034                createIdmapsForPackageLI(pkg);
9035            }
9036        }
9037
9038        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9039
9040        if (createIdmapFailed) {
9041            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9042                    "scanPackageLI failed to createIdmap");
9043        }
9044        return pkg;
9045    }
9046
9047    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9048            PackageParser.Package update, UserHandle user) {
9049        if (existing.applicationInfo == null || update.applicationInfo == null) {
9050            // This isn't due to an app installation.
9051            return;
9052        }
9053
9054        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9055        final File newCodePath = new File(update.applicationInfo.getCodePath());
9056
9057        // The codePath hasn't changed, so there's nothing for us to do.
9058        if (Objects.equals(oldCodePath, newCodePath)) {
9059            return;
9060        }
9061
9062        File canonicalNewCodePath;
9063        try {
9064            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9065        } catch (IOException e) {
9066            Slog.w(TAG, "Failed to get canonical path.", e);
9067            return;
9068        }
9069
9070        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9071        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9072        // that the last component of the path (i.e, the name) doesn't need canonicalization
9073        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9074        // but may change in the future. Hopefully this function won't exist at that point.
9075        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9076                oldCodePath.getName());
9077
9078        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9079        // with "@".
9080        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9081        if (!oldMarkerPrefix.endsWith("@")) {
9082            oldMarkerPrefix += "@";
9083        }
9084        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9085        if (!newMarkerPrefix.endsWith("@")) {
9086            newMarkerPrefix += "@";
9087        }
9088
9089        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9090        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9091        for (String updatedPath : updatedPaths) {
9092            String updatedPathName = new File(updatedPath).getName();
9093            markerSuffixes.add(updatedPathName.replace('/', '@'));
9094        }
9095
9096        for (int userId : resolveUserIds(user.getIdentifier())) {
9097            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9098
9099            for (String markerSuffix : markerSuffixes) {
9100                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9101                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9102                if (oldForeignUseMark.exists()) {
9103                    try {
9104                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9105                                newForeignUseMark.getAbsolutePath());
9106                    } catch (ErrnoException e) {
9107                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9108                        oldForeignUseMark.delete();
9109                    }
9110                }
9111            }
9112        }
9113    }
9114
9115    /**
9116     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9117     * is derived purely on the basis of the contents of {@code scanFile} and
9118     * {@code cpuAbiOverride}.
9119     *
9120     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9121     */
9122    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9123                                 String cpuAbiOverride, boolean extractLibs)
9124            throws PackageManagerException {
9125        // TODO: We can probably be smarter about this stuff. For installed apps,
9126        // we can calculate this information at install time once and for all. For
9127        // system apps, we can probably assume that this information doesn't change
9128        // after the first boot scan. As things stand, we do lots of unnecessary work.
9129
9130        // Give ourselves some initial paths; we'll come back for another
9131        // pass once we've determined ABI below.
9132        setNativeLibraryPaths(pkg);
9133
9134        // We would never need to extract libs for forward-locked and external packages,
9135        // since the container service will do it for us. We shouldn't attempt to
9136        // extract libs from system app when it was not updated.
9137        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9138                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9139            extractLibs = false;
9140        }
9141
9142        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9143        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9144
9145        NativeLibraryHelper.Handle handle = null;
9146        try {
9147            handle = NativeLibraryHelper.Handle.create(pkg);
9148            // TODO(multiArch): This can be null for apps that didn't go through the
9149            // usual installation process. We can calculate it again, like we
9150            // do during install time.
9151            //
9152            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9153            // unnecessary.
9154            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9155
9156            // Null out the abis so that they can be recalculated.
9157            pkg.applicationInfo.primaryCpuAbi = null;
9158            pkg.applicationInfo.secondaryCpuAbi = null;
9159            if (isMultiArch(pkg.applicationInfo)) {
9160                // Warn if we've set an abiOverride for multi-lib packages..
9161                // By definition, we need to copy both 32 and 64 bit libraries for
9162                // such packages.
9163                if (pkg.cpuAbiOverride != null
9164                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9165                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9166                }
9167
9168                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9169                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9170                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9171                    if (extractLibs) {
9172                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9173                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9174                                useIsaSpecificSubdirs);
9175                    } else {
9176                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9177                    }
9178                }
9179
9180                maybeThrowExceptionForMultiArchCopy(
9181                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9182
9183                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9184                    if (extractLibs) {
9185                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9186                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9187                                useIsaSpecificSubdirs);
9188                    } else {
9189                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9190                    }
9191                }
9192
9193                maybeThrowExceptionForMultiArchCopy(
9194                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9195
9196                if (abi64 >= 0) {
9197                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9198                }
9199
9200                if (abi32 >= 0) {
9201                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9202                    if (abi64 >= 0) {
9203                        if (pkg.use32bitAbi) {
9204                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9205                            pkg.applicationInfo.primaryCpuAbi = abi;
9206                        } else {
9207                            pkg.applicationInfo.secondaryCpuAbi = abi;
9208                        }
9209                    } else {
9210                        pkg.applicationInfo.primaryCpuAbi = abi;
9211                    }
9212                }
9213
9214            } else {
9215                String[] abiList = (cpuAbiOverride != null) ?
9216                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9217
9218                // Enable gross and lame hacks for apps that are built with old
9219                // SDK tools. We must scan their APKs for renderscript bitcode and
9220                // not launch them if it's present. Don't bother checking on devices
9221                // that don't have 64 bit support.
9222                boolean needsRenderScriptOverride = false;
9223                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9224                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9225                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9226                    needsRenderScriptOverride = true;
9227                }
9228
9229                final int copyRet;
9230                if (extractLibs) {
9231                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9232                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9233                } else {
9234                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9235                }
9236
9237                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9238                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9239                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9240                }
9241
9242                if (copyRet >= 0) {
9243                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9244                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9245                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9246                } else if (needsRenderScriptOverride) {
9247                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9248                }
9249            }
9250        } catch (IOException ioe) {
9251            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9252        } finally {
9253            IoUtils.closeQuietly(handle);
9254        }
9255
9256        // Now that we've calculated the ABIs and determined if it's an internal app,
9257        // we will go ahead and populate the nativeLibraryPath.
9258        setNativeLibraryPaths(pkg);
9259    }
9260
9261    /**
9262     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9263     * i.e, so that all packages can be run inside a single process if required.
9264     *
9265     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9266     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9267     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9268     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9269     * updating a package that belongs to a shared user.
9270     *
9271     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9272     * adds unnecessary complexity.
9273     */
9274    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9275            PackageParser.Package scannedPackage, boolean bootComplete) {
9276        String requiredInstructionSet = null;
9277        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9278            requiredInstructionSet = VMRuntime.getInstructionSet(
9279                     scannedPackage.applicationInfo.primaryCpuAbi);
9280        }
9281
9282        PackageSetting requirer = null;
9283        for (PackageSetting ps : packagesForUser) {
9284            // If packagesForUser contains scannedPackage, we skip it. This will happen
9285            // when scannedPackage is an update of an existing package. Without this check,
9286            // we will never be able to change the ABI of any package belonging to a shared
9287            // user, even if it's compatible with other packages.
9288            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9289                if (ps.primaryCpuAbiString == null) {
9290                    continue;
9291                }
9292
9293                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9294                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9295                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9296                    // this but there's not much we can do.
9297                    String errorMessage = "Instruction set mismatch, "
9298                            + ((requirer == null) ? "[caller]" : requirer)
9299                            + " requires " + requiredInstructionSet + " whereas " + ps
9300                            + " requires " + instructionSet;
9301                    Slog.w(TAG, errorMessage);
9302                }
9303
9304                if (requiredInstructionSet == null) {
9305                    requiredInstructionSet = instructionSet;
9306                    requirer = ps;
9307                }
9308            }
9309        }
9310
9311        if (requiredInstructionSet != null) {
9312            String adjustedAbi;
9313            if (requirer != null) {
9314                // requirer != null implies that either scannedPackage was null or that scannedPackage
9315                // did not require an ABI, in which case we have to adjust scannedPackage to match
9316                // the ABI of the set (which is the same as requirer's ABI)
9317                adjustedAbi = requirer.primaryCpuAbiString;
9318                if (scannedPackage != null) {
9319                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9320                }
9321            } else {
9322                // requirer == null implies that we're updating all ABIs in the set to
9323                // match scannedPackage.
9324                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9325            }
9326
9327            for (PackageSetting ps : packagesForUser) {
9328                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9329                    if (ps.primaryCpuAbiString != null) {
9330                        continue;
9331                    }
9332
9333                    ps.primaryCpuAbiString = adjustedAbi;
9334                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9335                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9336                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9337                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9338                                + " (requirer="
9339                                + (requirer == null ? "null" : requirer.pkg.packageName)
9340                                + ", scannedPackage="
9341                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9342                                + ")");
9343                        try {
9344                            mInstaller.rmdex(ps.codePathString,
9345                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9346                        } catch (InstallerException ignored) {
9347                        }
9348                    }
9349                }
9350            }
9351        }
9352    }
9353
9354    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9355        synchronized (mPackages) {
9356            mResolverReplaced = true;
9357            // Set up information for custom user intent resolution activity.
9358            mResolveActivity.applicationInfo = pkg.applicationInfo;
9359            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9360            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9361            mResolveActivity.processName = pkg.applicationInfo.packageName;
9362            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9363            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9364                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9365            mResolveActivity.theme = 0;
9366            mResolveActivity.exported = true;
9367            mResolveActivity.enabled = true;
9368            mResolveInfo.activityInfo = mResolveActivity;
9369            mResolveInfo.priority = 0;
9370            mResolveInfo.preferredOrder = 0;
9371            mResolveInfo.match = 0;
9372            mResolveComponentName = mCustomResolverComponentName;
9373            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9374                    mResolveComponentName);
9375        }
9376    }
9377
9378    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9379        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9380
9381        // Set up information for ephemeral installer activity
9382        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9383        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9384        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9385        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9386        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9387        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9388                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9389        mEphemeralInstallerActivity.theme = 0;
9390        mEphemeralInstallerActivity.exported = true;
9391        mEphemeralInstallerActivity.enabled = true;
9392        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9393        mEphemeralInstallerInfo.priority = 0;
9394        mEphemeralInstallerInfo.preferredOrder = 0;
9395        mEphemeralInstallerInfo.match = 0;
9396
9397        if (DEBUG_EPHEMERAL) {
9398            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9399        }
9400    }
9401
9402    private static String calculateBundledApkRoot(final String codePathString) {
9403        final File codePath = new File(codePathString);
9404        final File codeRoot;
9405        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9406            codeRoot = Environment.getRootDirectory();
9407        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9408            codeRoot = Environment.getOemDirectory();
9409        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9410            codeRoot = Environment.getVendorDirectory();
9411        } else {
9412            // Unrecognized code path; take its top real segment as the apk root:
9413            // e.g. /something/app/blah.apk => /something
9414            try {
9415                File f = codePath.getCanonicalFile();
9416                File parent = f.getParentFile();    // non-null because codePath is a file
9417                File tmp;
9418                while ((tmp = parent.getParentFile()) != null) {
9419                    f = parent;
9420                    parent = tmp;
9421                }
9422                codeRoot = f;
9423                Slog.w(TAG, "Unrecognized code path "
9424                        + codePath + " - using " + codeRoot);
9425            } catch (IOException e) {
9426                // Can't canonicalize the code path -- shenanigans?
9427                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9428                return Environment.getRootDirectory().getPath();
9429            }
9430        }
9431        return codeRoot.getPath();
9432    }
9433
9434    /**
9435     * Derive and set the location of native libraries for the given package,
9436     * which varies depending on where and how the package was installed.
9437     */
9438    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9439        final ApplicationInfo info = pkg.applicationInfo;
9440        final String codePath = pkg.codePath;
9441        final File codeFile = new File(codePath);
9442        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9443        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9444
9445        info.nativeLibraryRootDir = null;
9446        info.nativeLibraryRootRequiresIsa = false;
9447        info.nativeLibraryDir = null;
9448        info.secondaryNativeLibraryDir = null;
9449
9450        if (isApkFile(codeFile)) {
9451            // Monolithic install
9452            if (bundledApp) {
9453                // If "/system/lib64/apkname" exists, assume that is the per-package
9454                // native library directory to use; otherwise use "/system/lib/apkname".
9455                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9456                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9457                        getPrimaryInstructionSet(info));
9458
9459                // This is a bundled system app so choose the path based on the ABI.
9460                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9461                // is just the default path.
9462                final String apkName = deriveCodePathName(codePath);
9463                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9464                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9465                        apkName).getAbsolutePath();
9466
9467                if (info.secondaryCpuAbi != null) {
9468                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9469                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9470                            secondaryLibDir, apkName).getAbsolutePath();
9471                }
9472            } else if (asecApp) {
9473                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9474                        .getAbsolutePath();
9475            } else {
9476                final String apkName = deriveCodePathName(codePath);
9477                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9478                        .getAbsolutePath();
9479            }
9480
9481            info.nativeLibraryRootRequiresIsa = false;
9482            info.nativeLibraryDir = info.nativeLibraryRootDir;
9483        } else {
9484            // Cluster install
9485            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9486            info.nativeLibraryRootRequiresIsa = true;
9487
9488            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9489                    getPrimaryInstructionSet(info)).getAbsolutePath();
9490
9491            if (info.secondaryCpuAbi != null) {
9492                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9493                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9494            }
9495        }
9496    }
9497
9498    /**
9499     * Calculate the abis and roots for a bundled app. These can uniquely
9500     * be determined from the contents of the system partition, i.e whether
9501     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9502     * of this information, and instead assume that the system was built
9503     * sensibly.
9504     */
9505    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9506                                           PackageSetting pkgSetting) {
9507        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9508
9509        // If "/system/lib64/apkname" exists, assume that is the per-package
9510        // native library directory to use; otherwise use "/system/lib/apkname".
9511        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9512        setBundledAppAbi(pkg, apkRoot, apkName);
9513        // pkgSetting might be null during rescan following uninstall of updates
9514        // to a bundled app, so accommodate that possibility.  The settings in
9515        // that case will be established later from the parsed package.
9516        //
9517        // If the settings aren't null, sync them up with what we've just derived.
9518        // note that apkRoot isn't stored in the package settings.
9519        if (pkgSetting != null) {
9520            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9521            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9522        }
9523    }
9524
9525    /**
9526     * Deduces the ABI of a bundled app and sets the relevant fields on the
9527     * parsed pkg object.
9528     *
9529     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9530     *        under which system libraries are installed.
9531     * @param apkName the name of the installed package.
9532     */
9533    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9534        final File codeFile = new File(pkg.codePath);
9535
9536        final boolean has64BitLibs;
9537        final boolean has32BitLibs;
9538        if (isApkFile(codeFile)) {
9539            // Monolithic install
9540            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9541            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9542        } else {
9543            // Cluster install
9544            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9545            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9546                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9547                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9548                has64BitLibs = (new File(rootDir, isa)).exists();
9549            } else {
9550                has64BitLibs = false;
9551            }
9552            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9553                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9554                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9555                has32BitLibs = (new File(rootDir, isa)).exists();
9556            } else {
9557                has32BitLibs = false;
9558            }
9559        }
9560
9561        if (has64BitLibs && !has32BitLibs) {
9562            // The package has 64 bit libs, but not 32 bit libs. Its primary
9563            // ABI should be 64 bit. We can safely assume here that the bundled
9564            // native libraries correspond to the most preferred ABI in the list.
9565
9566            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9567            pkg.applicationInfo.secondaryCpuAbi = null;
9568        } else if (has32BitLibs && !has64BitLibs) {
9569            // The package has 32 bit libs but not 64 bit libs. Its primary
9570            // ABI should be 32 bit.
9571
9572            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9573            pkg.applicationInfo.secondaryCpuAbi = null;
9574        } else if (has32BitLibs && has64BitLibs) {
9575            // The application has both 64 and 32 bit bundled libraries. We check
9576            // here that the app declares multiArch support, and warn if it doesn't.
9577            //
9578            // We will be lenient here and record both ABIs. The primary will be the
9579            // ABI that's higher on the list, i.e, a device that's configured to prefer
9580            // 64 bit apps will see a 64 bit primary ABI,
9581
9582            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9583                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9584            }
9585
9586            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9587                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9588                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9589            } else {
9590                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9591                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9592            }
9593        } else {
9594            pkg.applicationInfo.primaryCpuAbi = null;
9595            pkg.applicationInfo.secondaryCpuAbi = null;
9596        }
9597    }
9598
9599    private void killApplication(String pkgName, int appId, String reason) {
9600        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9601    }
9602
9603    private void killApplication(String pkgName, int appId, int userId, String reason) {
9604        // Request the ActivityManager to kill the process(only for existing packages)
9605        // so that we do not end up in a confused state while the user is still using the older
9606        // version of the application while the new one gets installed.
9607        final long token = Binder.clearCallingIdentity();
9608        try {
9609            IActivityManager am = ActivityManagerNative.getDefault();
9610            if (am != null) {
9611                try {
9612                    am.killApplication(pkgName, appId, userId, reason);
9613                } catch (RemoteException e) {
9614                }
9615            }
9616        } finally {
9617            Binder.restoreCallingIdentity(token);
9618        }
9619    }
9620
9621    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9622        // Remove the parent package setting
9623        PackageSetting ps = (PackageSetting) pkg.mExtras;
9624        if (ps != null) {
9625            removePackageLI(ps, chatty);
9626        }
9627        // Remove the child package setting
9628        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9629        for (int i = 0; i < childCount; i++) {
9630            PackageParser.Package childPkg = pkg.childPackages.get(i);
9631            ps = (PackageSetting) childPkg.mExtras;
9632            if (ps != null) {
9633                removePackageLI(ps, chatty);
9634            }
9635        }
9636    }
9637
9638    void removePackageLI(PackageSetting ps, boolean chatty) {
9639        if (DEBUG_INSTALL) {
9640            if (chatty)
9641                Log.d(TAG, "Removing package " + ps.name);
9642        }
9643
9644        // writer
9645        synchronized (mPackages) {
9646            mPackages.remove(ps.name);
9647            final PackageParser.Package pkg = ps.pkg;
9648            if (pkg != null) {
9649                cleanPackageDataStructuresLILPw(pkg, chatty);
9650            }
9651        }
9652    }
9653
9654    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9655        if (DEBUG_INSTALL) {
9656            if (chatty)
9657                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9658        }
9659
9660        // writer
9661        synchronized (mPackages) {
9662            // Remove the parent package
9663            mPackages.remove(pkg.applicationInfo.packageName);
9664            cleanPackageDataStructuresLILPw(pkg, chatty);
9665
9666            // Remove the child packages
9667            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9668            for (int i = 0; i < childCount; i++) {
9669                PackageParser.Package childPkg = pkg.childPackages.get(i);
9670                mPackages.remove(childPkg.applicationInfo.packageName);
9671                cleanPackageDataStructuresLILPw(childPkg, chatty);
9672            }
9673        }
9674    }
9675
9676    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9677        int N = pkg.providers.size();
9678        StringBuilder r = null;
9679        int i;
9680        for (i=0; i<N; i++) {
9681            PackageParser.Provider p = pkg.providers.get(i);
9682            mProviders.removeProvider(p);
9683            if (p.info.authority == null) {
9684
9685                /* There was another ContentProvider with this authority when
9686                 * this app was installed so this authority is null,
9687                 * Ignore it as we don't have to unregister the provider.
9688                 */
9689                continue;
9690            }
9691            String names[] = p.info.authority.split(";");
9692            for (int j = 0; j < names.length; j++) {
9693                if (mProvidersByAuthority.get(names[j]) == p) {
9694                    mProvidersByAuthority.remove(names[j]);
9695                    if (DEBUG_REMOVE) {
9696                        if (chatty)
9697                            Log.d(TAG, "Unregistered content provider: " + names[j]
9698                                    + ", className = " + p.info.name + ", isSyncable = "
9699                                    + p.info.isSyncable);
9700                    }
9701                }
9702            }
9703            if (DEBUG_REMOVE && chatty) {
9704                if (r == null) {
9705                    r = new StringBuilder(256);
9706                } else {
9707                    r.append(' ');
9708                }
9709                r.append(p.info.name);
9710            }
9711        }
9712        if (r != null) {
9713            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9714        }
9715
9716        N = pkg.services.size();
9717        r = null;
9718        for (i=0; i<N; i++) {
9719            PackageParser.Service s = pkg.services.get(i);
9720            mServices.removeService(s);
9721            if (chatty) {
9722                if (r == null) {
9723                    r = new StringBuilder(256);
9724                } else {
9725                    r.append(' ');
9726                }
9727                r.append(s.info.name);
9728            }
9729        }
9730        if (r != null) {
9731            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9732        }
9733
9734        N = pkg.receivers.size();
9735        r = null;
9736        for (i=0; i<N; i++) {
9737            PackageParser.Activity a = pkg.receivers.get(i);
9738            mReceivers.removeActivity(a, "receiver");
9739            if (DEBUG_REMOVE && chatty) {
9740                if (r == null) {
9741                    r = new StringBuilder(256);
9742                } else {
9743                    r.append(' ');
9744                }
9745                r.append(a.info.name);
9746            }
9747        }
9748        if (r != null) {
9749            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9750        }
9751
9752        N = pkg.activities.size();
9753        r = null;
9754        for (i=0; i<N; i++) {
9755            PackageParser.Activity a = pkg.activities.get(i);
9756            mActivities.removeActivity(a, "activity");
9757            if (DEBUG_REMOVE && chatty) {
9758                if (r == null) {
9759                    r = new StringBuilder(256);
9760                } else {
9761                    r.append(' ');
9762                }
9763                r.append(a.info.name);
9764            }
9765        }
9766        if (r != null) {
9767            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9768        }
9769
9770        N = pkg.permissions.size();
9771        r = null;
9772        for (i=0; i<N; i++) {
9773            PackageParser.Permission p = pkg.permissions.get(i);
9774            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9775            if (bp == null) {
9776                bp = mSettings.mPermissionTrees.get(p.info.name);
9777            }
9778            if (bp != null && bp.perm == p) {
9779                bp.perm = null;
9780                if (DEBUG_REMOVE && chatty) {
9781                    if (r == null) {
9782                        r = new StringBuilder(256);
9783                    } else {
9784                        r.append(' ');
9785                    }
9786                    r.append(p.info.name);
9787                }
9788            }
9789            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9790                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9791                if (appOpPkgs != null) {
9792                    appOpPkgs.remove(pkg.packageName);
9793                }
9794            }
9795        }
9796        if (r != null) {
9797            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9798        }
9799
9800        N = pkg.requestedPermissions.size();
9801        r = null;
9802        for (i=0; i<N; i++) {
9803            String perm = pkg.requestedPermissions.get(i);
9804            BasePermission bp = mSettings.mPermissions.get(perm);
9805            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9806                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9807                if (appOpPkgs != null) {
9808                    appOpPkgs.remove(pkg.packageName);
9809                    if (appOpPkgs.isEmpty()) {
9810                        mAppOpPermissionPackages.remove(perm);
9811                    }
9812                }
9813            }
9814        }
9815        if (r != null) {
9816            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9817        }
9818
9819        N = pkg.instrumentation.size();
9820        r = null;
9821        for (i=0; i<N; i++) {
9822            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9823            mInstrumentation.remove(a.getComponentName());
9824            if (DEBUG_REMOVE && chatty) {
9825                if (r == null) {
9826                    r = new StringBuilder(256);
9827                } else {
9828                    r.append(' ');
9829                }
9830                r.append(a.info.name);
9831            }
9832        }
9833        if (r != null) {
9834            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9835        }
9836
9837        r = null;
9838        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9839            // Only system apps can hold shared libraries.
9840            if (pkg.libraryNames != null) {
9841                for (i=0; i<pkg.libraryNames.size(); i++) {
9842                    String name = pkg.libraryNames.get(i);
9843                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9844                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9845                        mSharedLibraries.remove(name);
9846                        if (DEBUG_REMOVE && chatty) {
9847                            if (r == null) {
9848                                r = new StringBuilder(256);
9849                            } else {
9850                                r.append(' ');
9851                            }
9852                            r.append(name);
9853                        }
9854                    }
9855                }
9856            }
9857        }
9858        if (r != null) {
9859            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9860        }
9861    }
9862
9863    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9864        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9865            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9866                return true;
9867            }
9868        }
9869        return false;
9870    }
9871
9872    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9873    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9874    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9875
9876    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9877        // Update the parent permissions
9878        updatePermissionsLPw(pkg.packageName, pkg, flags);
9879        // Update the child permissions
9880        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9881        for (int i = 0; i < childCount; i++) {
9882            PackageParser.Package childPkg = pkg.childPackages.get(i);
9883            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9884        }
9885    }
9886
9887    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9888            int flags) {
9889        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9890        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9891    }
9892
9893    private void updatePermissionsLPw(String changingPkg,
9894            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9895        // Make sure there are no dangling permission trees.
9896        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9897        while (it.hasNext()) {
9898            final BasePermission bp = it.next();
9899            if (bp.packageSetting == null) {
9900                // We may not yet have parsed the package, so just see if
9901                // we still know about its settings.
9902                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9903            }
9904            if (bp.packageSetting == null) {
9905                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9906                        + " from package " + bp.sourcePackage);
9907                it.remove();
9908            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9909                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9910                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9911                            + " from package " + bp.sourcePackage);
9912                    flags |= UPDATE_PERMISSIONS_ALL;
9913                    it.remove();
9914                }
9915            }
9916        }
9917
9918        // Make sure all dynamic permissions have been assigned to a package,
9919        // and make sure there are no dangling permissions.
9920        it = mSettings.mPermissions.values().iterator();
9921        while (it.hasNext()) {
9922            final BasePermission bp = it.next();
9923            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9924                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9925                        + bp.name + " pkg=" + bp.sourcePackage
9926                        + " info=" + bp.pendingInfo);
9927                if (bp.packageSetting == null && bp.pendingInfo != null) {
9928                    final BasePermission tree = findPermissionTreeLP(bp.name);
9929                    if (tree != null && tree.perm != null) {
9930                        bp.packageSetting = tree.packageSetting;
9931                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9932                                new PermissionInfo(bp.pendingInfo));
9933                        bp.perm.info.packageName = tree.perm.info.packageName;
9934                        bp.perm.info.name = bp.name;
9935                        bp.uid = tree.uid;
9936                    }
9937                }
9938            }
9939            if (bp.packageSetting == null) {
9940                // We may not yet have parsed the package, so just see if
9941                // we still know about its settings.
9942                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9943            }
9944            if (bp.packageSetting == null) {
9945                Slog.w(TAG, "Removing dangling permission: " + bp.name
9946                        + " from package " + bp.sourcePackage);
9947                it.remove();
9948            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9949                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9950                    Slog.i(TAG, "Removing old permission: " + bp.name
9951                            + " from package " + bp.sourcePackage);
9952                    flags |= UPDATE_PERMISSIONS_ALL;
9953                    it.remove();
9954                }
9955            }
9956        }
9957
9958        // Now update the permissions for all packages, in particular
9959        // replace the granted permissions of the system packages.
9960        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9961            for (PackageParser.Package pkg : mPackages.values()) {
9962                if (pkg != pkgInfo) {
9963                    // Only replace for packages on requested volume
9964                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9965                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9966                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9967                    grantPermissionsLPw(pkg, replace, changingPkg);
9968                }
9969            }
9970        }
9971
9972        if (pkgInfo != null) {
9973            // Only replace for packages on requested volume
9974            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9975            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9976                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9977            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9978        }
9979    }
9980
9981    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9982            String packageOfInterest) {
9983        // IMPORTANT: There are two types of permissions: install and runtime.
9984        // Install time permissions are granted when the app is installed to
9985        // all device users and users added in the future. Runtime permissions
9986        // are granted at runtime explicitly to specific users. Normal and signature
9987        // protected permissions are install time permissions. Dangerous permissions
9988        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9989        // otherwise they are runtime permissions. This function does not manage
9990        // runtime permissions except for the case an app targeting Lollipop MR1
9991        // being upgraded to target a newer SDK, in which case dangerous permissions
9992        // are transformed from install time to runtime ones.
9993
9994        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9995        if (ps == null) {
9996            return;
9997        }
9998
9999        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10000
10001        PermissionsState permissionsState = ps.getPermissionsState();
10002        PermissionsState origPermissions = permissionsState;
10003
10004        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10005
10006        boolean runtimePermissionsRevoked = false;
10007        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10008
10009        boolean changedInstallPermission = false;
10010
10011        if (replace) {
10012            ps.installPermissionsFixed = false;
10013            if (!ps.isSharedUser()) {
10014                origPermissions = new PermissionsState(permissionsState);
10015                permissionsState.reset();
10016            } else {
10017                // We need to know only about runtime permission changes since the
10018                // calling code always writes the install permissions state but
10019                // the runtime ones are written only if changed. The only cases of
10020                // changed runtime permissions here are promotion of an install to
10021                // runtime and revocation of a runtime from a shared user.
10022                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10023                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10024                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10025                    runtimePermissionsRevoked = true;
10026                }
10027            }
10028        }
10029
10030        permissionsState.setGlobalGids(mGlobalGids);
10031
10032        final int N = pkg.requestedPermissions.size();
10033        for (int i=0; i<N; i++) {
10034            final String name = pkg.requestedPermissions.get(i);
10035            final BasePermission bp = mSettings.mPermissions.get(name);
10036
10037            if (DEBUG_INSTALL) {
10038                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10039            }
10040
10041            if (bp == null || bp.packageSetting == null) {
10042                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10043                    Slog.w(TAG, "Unknown permission " + name
10044                            + " in package " + pkg.packageName);
10045                }
10046                continue;
10047            }
10048
10049            final String perm = bp.name;
10050            boolean allowedSig = false;
10051            int grant = GRANT_DENIED;
10052
10053            // Keep track of app op permissions.
10054            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10055                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10056                if (pkgs == null) {
10057                    pkgs = new ArraySet<>();
10058                    mAppOpPermissionPackages.put(bp.name, pkgs);
10059                }
10060                pkgs.add(pkg.packageName);
10061            }
10062
10063            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10064            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10065                    >= Build.VERSION_CODES.M;
10066            switch (level) {
10067                case PermissionInfo.PROTECTION_NORMAL: {
10068                    // For all apps normal permissions are install time ones.
10069                    grant = GRANT_INSTALL;
10070                } break;
10071
10072                case PermissionInfo.PROTECTION_DANGEROUS: {
10073                    // If a permission review is required for legacy apps we represent
10074                    // their permissions as always granted runtime ones since we need
10075                    // to keep the review required permission flag per user while an
10076                    // install permission's state is shared across all users.
10077                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10078                        // For legacy apps dangerous permissions are install time ones.
10079                        grant = GRANT_INSTALL;
10080                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10081                        // For legacy apps that became modern, install becomes runtime.
10082                        grant = GRANT_UPGRADE;
10083                    } else if (mPromoteSystemApps
10084                            && isSystemApp(ps)
10085                            && mExistingSystemPackages.contains(ps.name)) {
10086                        // For legacy system apps, install becomes runtime.
10087                        // We cannot check hasInstallPermission() for system apps since those
10088                        // permissions were granted implicitly and not persisted pre-M.
10089                        grant = GRANT_UPGRADE;
10090                    } else {
10091                        // For modern apps keep runtime permissions unchanged.
10092                        grant = GRANT_RUNTIME;
10093                    }
10094                } break;
10095
10096                case PermissionInfo.PROTECTION_SIGNATURE: {
10097                    // For all apps signature permissions are install time ones.
10098                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10099                    if (allowedSig) {
10100                        grant = GRANT_INSTALL;
10101                    }
10102                } break;
10103            }
10104
10105            if (DEBUG_INSTALL) {
10106                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10107            }
10108
10109            if (grant != GRANT_DENIED) {
10110                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10111                    // If this is an existing, non-system package, then
10112                    // we can't add any new permissions to it.
10113                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10114                        // Except...  if this is a permission that was added
10115                        // to the platform (note: need to only do this when
10116                        // updating the platform).
10117                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10118                            grant = GRANT_DENIED;
10119                        }
10120                    }
10121                }
10122
10123                switch (grant) {
10124                    case GRANT_INSTALL: {
10125                        // Revoke this as runtime permission to handle the case of
10126                        // a runtime permission being downgraded to an install one.
10127                        // Also in permission review mode we keep dangerous permissions
10128                        // for legacy apps
10129                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10130                            if (origPermissions.getRuntimePermissionState(
10131                                    bp.name, userId) != null) {
10132                                // Revoke the runtime permission and clear the flags.
10133                                origPermissions.revokeRuntimePermission(bp, userId);
10134                                origPermissions.updatePermissionFlags(bp, userId,
10135                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10136                                // If we revoked a permission permission, we have to write.
10137                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10138                                        changedRuntimePermissionUserIds, userId);
10139                            }
10140                        }
10141                        // Grant an install permission.
10142                        if (permissionsState.grantInstallPermission(bp) !=
10143                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10144                            changedInstallPermission = true;
10145                        }
10146                    } break;
10147
10148                    case GRANT_RUNTIME: {
10149                        // Grant previously granted runtime permissions.
10150                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10151                            PermissionState permissionState = origPermissions
10152                                    .getRuntimePermissionState(bp.name, userId);
10153                            int flags = permissionState != null
10154                                    ? permissionState.getFlags() : 0;
10155                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10156                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10157                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10158                                    // If we cannot put the permission as it was, we have to write.
10159                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10160                                            changedRuntimePermissionUserIds, userId);
10161                                }
10162                                // If the app supports runtime permissions no need for a review.
10163                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10164                                        && appSupportsRuntimePermissions
10165                                        && (flags & PackageManager
10166                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10167                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10168                                    // Since we changed the flags, we have to write.
10169                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10170                                            changedRuntimePermissionUserIds, userId);
10171                                }
10172                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10173                                    && !appSupportsRuntimePermissions) {
10174                                // For legacy apps that need a permission review, every new
10175                                // runtime permission is granted but it is pending a review.
10176                                // We also need to review only platform defined runtime
10177                                // permissions as these are the only ones the platform knows
10178                                // how to disable the API to simulate revocation as legacy
10179                                // apps don't expect to run with revoked permissions.
10180                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10181                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10182                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10183                                        // We changed the flags, hence have to write.
10184                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10185                                                changedRuntimePermissionUserIds, userId);
10186                                    }
10187                                }
10188                                if (permissionsState.grantRuntimePermission(bp, userId)
10189                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10190                                    // We changed the permission, hence have to write.
10191                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10192                                            changedRuntimePermissionUserIds, userId);
10193                                }
10194                            }
10195                            // Propagate the permission flags.
10196                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10197                        }
10198                    } break;
10199
10200                    case GRANT_UPGRADE: {
10201                        // Grant runtime permissions for a previously held install permission.
10202                        PermissionState permissionState = origPermissions
10203                                .getInstallPermissionState(bp.name);
10204                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10205
10206                        if (origPermissions.revokeInstallPermission(bp)
10207                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10208                            // We will be transferring the permission flags, so clear them.
10209                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10210                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10211                            changedInstallPermission = true;
10212                        }
10213
10214                        // If the permission is not to be promoted to runtime we ignore it and
10215                        // also its other flags as they are not applicable to install permissions.
10216                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10217                            for (int userId : currentUserIds) {
10218                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10219                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10220                                    // Transfer the permission flags.
10221                                    permissionsState.updatePermissionFlags(bp, userId,
10222                                            flags, flags);
10223                                    // If we granted the permission, we have to write.
10224                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10225                                            changedRuntimePermissionUserIds, userId);
10226                                }
10227                            }
10228                        }
10229                    } break;
10230
10231                    default: {
10232                        if (packageOfInterest == null
10233                                || packageOfInterest.equals(pkg.packageName)) {
10234                            Slog.w(TAG, "Not granting permission " + perm
10235                                    + " to package " + pkg.packageName
10236                                    + " because it was previously installed without");
10237                        }
10238                    } break;
10239                }
10240            } else {
10241                if (permissionsState.revokeInstallPermission(bp) !=
10242                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10243                    // Also drop the permission flags.
10244                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10245                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10246                    changedInstallPermission = true;
10247                    Slog.i(TAG, "Un-granting permission " + perm
10248                            + " from package " + pkg.packageName
10249                            + " (protectionLevel=" + bp.protectionLevel
10250                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10251                            + ")");
10252                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10253                    // Don't print warning for app op permissions, since it is fine for them
10254                    // not to be granted, there is a UI for the user to decide.
10255                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10256                        Slog.w(TAG, "Not granting permission " + perm
10257                                + " to package " + pkg.packageName
10258                                + " (protectionLevel=" + bp.protectionLevel
10259                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10260                                + ")");
10261                    }
10262                }
10263            }
10264        }
10265
10266        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10267                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10268            // This is the first that we have heard about this package, so the
10269            // permissions we have now selected are fixed until explicitly
10270            // changed.
10271            ps.installPermissionsFixed = true;
10272        }
10273
10274        // Persist the runtime permissions state for users with changes. If permissions
10275        // were revoked because no app in the shared user declares them we have to
10276        // write synchronously to avoid losing runtime permissions state.
10277        for (int userId : changedRuntimePermissionUserIds) {
10278            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10279        }
10280
10281        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10282    }
10283
10284    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10285        boolean allowed = false;
10286        final int NP = PackageParser.NEW_PERMISSIONS.length;
10287        for (int ip=0; ip<NP; ip++) {
10288            final PackageParser.NewPermissionInfo npi
10289                    = PackageParser.NEW_PERMISSIONS[ip];
10290            if (npi.name.equals(perm)
10291                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10292                allowed = true;
10293                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10294                        + pkg.packageName);
10295                break;
10296            }
10297        }
10298        return allowed;
10299    }
10300
10301    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10302            BasePermission bp, PermissionsState origPermissions) {
10303        boolean allowed;
10304        allowed = (compareSignatures(
10305                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10306                        == PackageManager.SIGNATURE_MATCH)
10307                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10308                        == PackageManager.SIGNATURE_MATCH);
10309        if (!allowed && (bp.protectionLevel
10310                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10311            if (isSystemApp(pkg)) {
10312                // For updated system applications, a system permission
10313                // is granted only if it had been defined by the original application.
10314                if (pkg.isUpdatedSystemApp()) {
10315                    final PackageSetting sysPs = mSettings
10316                            .getDisabledSystemPkgLPr(pkg.packageName);
10317                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10318                        // If the original was granted this permission, we take
10319                        // that grant decision as read and propagate it to the
10320                        // update.
10321                        if (sysPs.isPrivileged()) {
10322                            allowed = true;
10323                        }
10324                    } else {
10325                        // The system apk may have been updated with an older
10326                        // version of the one on the data partition, but which
10327                        // granted a new system permission that it didn't have
10328                        // before.  In this case we do want to allow the app to
10329                        // now get the new permission if the ancestral apk is
10330                        // privileged to get it.
10331                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10332                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10333                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10334                                    allowed = true;
10335                                    break;
10336                                }
10337                            }
10338                        }
10339                        // Also if a privileged parent package on the system image or any of
10340                        // its children requested a privileged permission, the updated child
10341                        // packages can also get the permission.
10342                        if (pkg.parentPackage != null) {
10343                            final PackageSetting disabledSysParentPs = mSettings
10344                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10345                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10346                                    && disabledSysParentPs.isPrivileged()) {
10347                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10348                                    allowed = true;
10349                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10350                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10351                                    for (int i = 0; i < count; i++) {
10352                                        PackageParser.Package disabledSysChildPkg =
10353                                                disabledSysParentPs.pkg.childPackages.get(i);
10354                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10355                                                perm)) {
10356                                            allowed = true;
10357                                            break;
10358                                        }
10359                                    }
10360                                }
10361                            }
10362                        }
10363                    }
10364                } else {
10365                    allowed = isPrivilegedApp(pkg);
10366                }
10367            }
10368        }
10369        if (!allowed) {
10370            if (!allowed && (bp.protectionLevel
10371                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10372                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10373                // If this was a previously normal/dangerous permission that got moved
10374                // to a system permission as part of the runtime permission redesign, then
10375                // we still want to blindly grant it to old apps.
10376                allowed = true;
10377            }
10378            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10379                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10380                // If this permission is to be granted to the system installer and
10381                // this app is an installer, then it gets the permission.
10382                allowed = true;
10383            }
10384            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10385                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10386                // If this permission is to be granted to the system verifier and
10387                // this app is a verifier, then it gets the permission.
10388                allowed = true;
10389            }
10390            if (!allowed && (bp.protectionLevel
10391                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10392                    && isSystemApp(pkg)) {
10393                // Any pre-installed system app is allowed to get this permission.
10394                allowed = true;
10395            }
10396            if (!allowed && (bp.protectionLevel
10397                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10398                // For development permissions, a development permission
10399                // is granted only if it was already granted.
10400                allowed = origPermissions.hasInstallPermission(perm);
10401            }
10402            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10403                    && pkg.packageName.equals(mSetupWizardPackage)) {
10404                // If this permission is to be granted to the system setup wizard and
10405                // this app is a setup wizard, then it gets the permission.
10406                allowed = true;
10407            }
10408        }
10409        return allowed;
10410    }
10411
10412    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10413        final int permCount = pkg.requestedPermissions.size();
10414        for (int j = 0; j < permCount; j++) {
10415            String requestedPermission = pkg.requestedPermissions.get(j);
10416            if (permission.equals(requestedPermission)) {
10417                return true;
10418            }
10419        }
10420        return false;
10421    }
10422
10423    final class ActivityIntentResolver
10424            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10425        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10426                boolean defaultOnly, int userId) {
10427            if (!sUserManager.exists(userId)) return null;
10428            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10429            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10430        }
10431
10432        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10433                int userId) {
10434            if (!sUserManager.exists(userId)) return null;
10435            mFlags = flags;
10436            return super.queryIntent(intent, resolvedType,
10437                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10438        }
10439
10440        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10441                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10442            if (!sUserManager.exists(userId)) return null;
10443            if (packageActivities == null) {
10444                return null;
10445            }
10446            mFlags = flags;
10447            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10448            final int N = packageActivities.size();
10449            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10450                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10451
10452            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10453            for (int i = 0; i < N; ++i) {
10454                intentFilters = packageActivities.get(i).intents;
10455                if (intentFilters != null && intentFilters.size() > 0) {
10456                    PackageParser.ActivityIntentInfo[] array =
10457                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10458                    intentFilters.toArray(array);
10459                    listCut.add(array);
10460                }
10461            }
10462            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10463        }
10464
10465        /**
10466         * Finds a privileged activity that matches the specified activity names.
10467         */
10468        private PackageParser.Activity findMatchingActivity(
10469                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10470            for (PackageParser.Activity sysActivity : activityList) {
10471                if (sysActivity.info.name.equals(activityInfo.name)) {
10472                    return sysActivity;
10473                }
10474                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10475                    return sysActivity;
10476                }
10477                if (sysActivity.info.targetActivity != null) {
10478                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10479                        return sysActivity;
10480                    }
10481                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10482                        return sysActivity;
10483                    }
10484                }
10485            }
10486            return null;
10487        }
10488
10489        public class IterGenerator<E> {
10490            public Iterator<E> generate(ActivityIntentInfo info) {
10491                return null;
10492            }
10493        }
10494
10495        public class ActionIterGenerator extends IterGenerator<String> {
10496            @Override
10497            public Iterator<String> generate(ActivityIntentInfo info) {
10498                return info.actionsIterator();
10499            }
10500        }
10501
10502        public class CategoriesIterGenerator extends IterGenerator<String> {
10503            @Override
10504            public Iterator<String> generate(ActivityIntentInfo info) {
10505                return info.categoriesIterator();
10506            }
10507        }
10508
10509        public class SchemesIterGenerator extends IterGenerator<String> {
10510            @Override
10511            public Iterator<String> generate(ActivityIntentInfo info) {
10512                return info.schemesIterator();
10513            }
10514        }
10515
10516        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10517            @Override
10518            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10519                return info.authoritiesIterator();
10520            }
10521        }
10522
10523        /**
10524         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10525         * MODIFIED. Do not pass in a list that should not be changed.
10526         */
10527        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10528                IterGenerator<T> generator, Iterator<T> searchIterator) {
10529            // loop through the set of actions; every one must be found in the intent filter
10530            while (searchIterator.hasNext()) {
10531                // we must have at least one filter in the list to consider a match
10532                if (intentList.size() == 0) {
10533                    break;
10534                }
10535
10536                final T searchAction = searchIterator.next();
10537
10538                // loop through the set of intent filters
10539                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10540                while (intentIter.hasNext()) {
10541                    final ActivityIntentInfo intentInfo = intentIter.next();
10542                    boolean selectionFound = false;
10543
10544                    // loop through the intent filter's selection criteria; at least one
10545                    // of them must match the searched criteria
10546                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10547                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10548                        final T intentSelection = intentSelectionIter.next();
10549                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10550                            selectionFound = true;
10551                            break;
10552                        }
10553                    }
10554
10555                    // the selection criteria wasn't found in this filter's set; this filter
10556                    // is not a potential match
10557                    if (!selectionFound) {
10558                        intentIter.remove();
10559                    }
10560                }
10561            }
10562        }
10563
10564        private boolean isProtectedAction(ActivityIntentInfo filter) {
10565            final Iterator<String> actionsIter = filter.actionsIterator();
10566            while (actionsIter != null && actionsIter.hasNext()) {
10567                final String filterAction = actionsIter.next();
10568                if (PROTECTED_ACTIONS.contains(filterAction)) {
10569                    return true;
10570                }
10571            }
10572            return false;
10573        }
10574
10575        /**
10576         * Adjusts the priority of the given intent filter according to policy.
10577         * <p>
10578         * <ul>
10579         * <li>The priority for non privileged applications is capped to '0'</li>
10580         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10581         * <li>The priority for unbundled updates to privileged applications is capped to the
10582         *      priority defined on the system partition</li>
10583         * </ul>
10584         * <p>
10585         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10586         * allowed to obtain any priority on any action.
10587         */
10588        private void adjustPriority(
10589                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10590            // nothing to do; priority is fine as-is
10591            if (intent.getPriority() <= 0) {
10592                return;
10593            }
10594
10595            final ActivityInfo activityInfo = intent.activity.info;
10596            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10597
10598            final boolean privilegedApp =
10599                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10600            if (!privilegedApp) {
10601                // non-privileged applications can never define a priority >0
10602                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10603                        + " package: " + applicationInfo.packageName
10604                        + " activity: " + intent.activity.className
10605                        + " origPrio: " + intent.getPriority());
10606                intent.setPriority(0);
10607                return;
10608            }
10609
10610            if (systemActivities == null) {
10611                // the system package is not disabled; we're parsing the system partition
10612                if (isProtectedAction(intent)) {
10613                    if (mDeferProtectedFilters) {
10614                        // We can't deal with these just yet. No component should ever obtain a
10615                        // >0 priority for a protected actions, with ONE exception -- the setup
10616                        // wizard. The setup wizard, however, cannot be known until we're able to
10617                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10618                        // until all intent filters have been processed. Chicken, meet egg.
10619                        // Let the filter temporarily have a high priority and rectify the
10620                        // priorities after all system packages have been scanned.
10621                        mProtectedFilters.add(intent);
10622                        if (DEBUG_FILTERS) {
10623                            Slog.i(TAG, "Protected action; save for later;"
10624                                    + " package: " + applicationInfo.packageName
10625                                    + " activity: " + intent.activity.className
10626                                    + " origPrio: " + intent.getPriority());
10627                        }
10628                        return;
10629                    } else {
10630                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10631                            Slog.i(TAG, "No setup wizard;"
10632                                + " All protected intents capped to priority 0");
10633                        }
10634                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10635                            if (DEBUG_FILTERS) {
10636                                Slog.i(TAG, "Found setup wizard;"
10637                                    + " allow priority " + intent.getPriority() + ";"
10638                                    + " package: " + intent.activity.info.packageName
10639                                    + " activity: " + intent.activity.className
10640                                    + " priority: " + intent.getPriority());
10641                            }
10642                            // setup wizard gets whatever it wants
10643                            return;
10644                        }
10645                        Slog.w(TAG, "Protected action; cap priority to 0;"
10646                                + " package: " + intent.activity.info.packageName
10647                                + " activity: " + intent.activity.className
10648                                + " origPrio: " + intent.getPriority());
10649                        intent.setPriority(0);
10650                        return;
10651                    }
10652                }
10653                // privileged apps on the system image get whatever priority they request
10654                return;
10655            }
10656
10657            // privileged app unbundled update ... try to find the same activity
10658            final PackageParser.Activity foundActivity =
10659                    findMatchingActivity(systemActivities, activityInfo);
10660            if (foundActivity == null) {
10661                // this is a new activity; it cannot obtain >0 priority
10662                if (DEBUG_FILTERS) {
10663                    Slog.i(TAG, "New activity; cap priority to 0;"
10664                            + " package: " + applicationInfo.packageName
10665                            + " activity: " + intent.activity.className
10666                            + " origPrio: " + intent.getPriority());
10667                }
10668                intent.setPriority(0);
10669                return;
10670            }
10671
10672            // found activity, now check for filter equivalence
10673
10674            // a shallow copy is enough; we modify the list, not its contents
10675            final List<ActivityIntentInfo> intentListCopy =
10676                    new ArrayList<>(foundActivity.intents);
10677            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10678
10679            // find matching action subsets
10680            final Iterator<String> actionsIterator = intent.actionsIterator();
10681            if (actionsIterator != null) {
10682                getIntentListSubset(
10683                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10684                if (intentListCopy.size() == 0) {
10685                    // no more intents to match; we're not equivalent
10686                    if (DEBUG_FILTERS) {
10687                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10688                                + " package: " + applicationInfo.packageName
10689                                + " activity: " + intent.activity.className
10690                                + " origPrio: " + intent.getPriority());
10691                    }
10692                    intent.setPriority(0);
10693                    return;
10694                }
10695            }
10696
10697            // find matching category subsets
10698            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10699            if (categoriesIterator != null) {
10700                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10701                        categoriesIterator);
10702                if (intentListCopy.size() == 0) {
10703                    // no more intents to match; we're not equivalent
10704                    if (DEBUG_FILTERS) {
10705                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10706                                + " package: " + applicationInfo.packageName
10707                                + " activity: " + intent.activity.className
10708                                + " origPrio: " + intent.getPriority());
10709                    }
10710                    intent.setPriority(0);
10711                    return;
10712                }
10713            }
10714
10715            // find matching schemes subsets
10716            final Iterator<String> schemesIterator = intent.schemesIterator();
10717            if (schemesIterator != null) {
10718                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10719                        schemesIterator);
10720                if (intentListCopy.size() == 0) {
10721                    // no more intents to match; we're not equivalent
10722                    if (DEBUG_FILTERS) {
10723                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10724                                + " package: " + applicationInfo.packageName
10725                                + " activity: " + intent.activity.className
10726                                + " origPrio: " + intent.getPriority());
10727                    }
10728                    intent.setPriority(0);
10729                    return;
10730                }
10731            }
10732
10733            // find matching authorities subsets
10734            final Iterator<IntentFilter.AuthorityEntry>
10735                    authoritiesIterator = intent.authoritiesIterator();
10736            if (authoritiesIterator != null) {
10737                getIntentListSubset(intentListCopy,
10738                        new AuthoritiesIterGenerator(),
10739                        authoritiesIterator);
10740                if (intentListCopy.size() == 0) {
10741                    // no more intents to match; we're not equivalent
10742                    if (DEBUG_FILTERS) {
10743                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10744                                + " package: " + applicationInfo.packageName
10745                                + " activity: " + intent.activity.className
10746                                + " origPrio: " + intent.getPriority());
10747                    }
10748                    intent.setPriority(0);
10749                    return;
10750                }
10751            }
10752
10753            // we found matching filter(s); app gets the max priority of all intents
10754            int cappedPriority = 0;
10755            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10756                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10757            }
10758            if (intent.getPriority() > cappedPriority) {
10759                if (DEBUG_FILTERS) {
10760                    Slog.i(TAG, "Found matching filter(s);"
10761                            + " cap priority to " + cappedPriority + ";"
10762                            + " package: " + applicationInfo.packageName
10763                            + " activity: " + intent.activity.className
10764                            + " origPrio: " + intent.getPriority());
10765                }
10766                intent.setPriority(cappedPriority);
10767                return;
10768            }
10769            // all this for nothing; the requested priority was <= what was on the system
10770        }
10771
10772        public final void addActivity(PackageParser.Activity a, String type) {
10773            mActivities.put(a.getComponentName(), a);
10774            if (DEBUG_SHOW_INFO)
10775                Log.v(
10776                TAG, "  " + type + " " +
10777                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10778            if (DEBUG_SHOW_INFO)
10779                Log.v(TAG, "    Class=" + a.info.name);
10780            final int NI = a.intents.size();
10781            for (int j=0; j<NI; j++) {
10782                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10783                if ("activity".equals(type)) {
10784                    final PackageSetting ps =
10785                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10786                    final List<PackageParser.Activity> systemActivities =
10787                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10788                    adjustPriority(systemActivities, intent);
10789                }
10790                if (DEBUG_SHOW_INFO) {
10791                    Log.v(TAG, "    IntentFilter:");
10792                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10793                }
10794                if (!intent.debugCheck()) {
10795                    Log.w(TAG, "==> For Activity " + a.info.name);
10796                }
10797                addFilter(intent);
10798            }
10799        }
10800
10801        public final void removeActivity(PackageParser.Activity a, String type) {
10802            mActivities.remove(a.getComponentName());
10803            if (DEBUG_SHOW_INFO) {
10804                Log.v(TAG, "  " + type + " "
10805                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10806                                : a.info.name) + ":");
10807                Log.v(TAG, "    Class=" + a.info.name);
10808            }
10809            final int NI = a.intents.size();
10810            for (int j=0; j<NI; j++) {
10811                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10812                if (DEBUG_SHOW_INFO) {
10813                    Log.v(TAG, "    IntentFilter:");
10814                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10815                }
10816                removeFilter(intent);
10817            }
10818        }
10819
10820        @Override
10821        protected boolean allowFilterResult(
10822                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10823            ActivityInfo filterAi = filter.activity.info;
10824            for (int i=dest.size()-1; i>=0; i--) {
10825                ActivityInfo destAi = dest.get(i).activityInfo;
10826                if (destAi.name == filterAi.name
10827                        && destAi.packageName == filterAi.packageName) {
10828                    return false;
10829                }
10830            }
10831            return true;
10832        }
10833
10834        @Override
10835        protected ActivityIntentInfo[] newArray(int size) {
10836            return new ActivityIntentInfo[size];
10837        }
10838
10839        @Override
10840        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10841            if (!sUserManager.exists(userId)) return true;
10842            PackageParser.Package p = filter.activity.owner;
10843            if (p != null) {
10844                PackageSetting ps = (PackageSetting)p.mExtras;
10845                if (ps != null) {
10846                    // System apps are never considered stopped for purposes of
10847                    // filtering, because there may be no way for the user to
10848                    // actually re-launch them.
10849                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10850                            && ps.getStopped(userId);
10851                }
10852            }
10853            return false;
10854        }
10855
10856        @Override
10857        protected boolean isPackageForFilter(String packageName,
10858                PackageParser.ActivityIntentInfo info) {
10859            return packageName.equals(info.activity.owner.packageName);
10860        }
10861
10862        @Override
10863        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10864                int match, int userId) {
10865            if (!sUserManager.exists(userId)) return null;
10866            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10867                return null;
10868            }
10869            final PackageParser.Activity activity = info.activity;
10870            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10871            if (ps == null) {
10872                return null;
10873            }
10874            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10875                    ps.readUserState(userId), userId);
10876            if (ai == null) {
10877                return null;
10878            }
10879            final ResolveInfo res = new ResolveInfo();
10880            res.activityInfo = ai;
10881            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10882                res.filter = info;
10883            }
10884            if (info != null) {
10885                res.handleAllWebDataURI = info.handleAllWebDataURI();
10886            }
10887            res.priority = info.getPriority();
10888            res.preferredOrder = activity.owner.mPreferredOrder;
10889            //System.out.println("Result: " + res.activityInfo.className +
10890            //                   " = " + res.priority);
10891            res.match = match;
10892            res.isDefault = info.hasDefault;
10893            res.labelRes = info.labelRes;
10894            res.nonLocalizedLabel = info.nonLocalizedLabel;
10895            if (userNeedsBadging(userId)) {
10896                res.noResourceId = true;
10897            } else {
10898                res.icon = info.icon;
10899            }
10900            res.iconResourceId = info.icon;
10901            res.system = res.activityInfo.applicationInfo.isSystemApp();
10902            return res;
10903        }
10904
10905        @Override
10906        protected void sortResults(List<ResolveInfo> results) {
10907            Collections.sort(results, mResolvePrioritySorter);
10908        }
10909
10910        @Override
10911        protected void dumpFilter(PrintWriter out, String prefix,
10912                PackageParser.ActivityIntentInfo filter) {
10913            out.print(prefix); out.print(
10914                    Integer.toHexString(System.identityHashCode(filter.activity)));
10915                    out.print(' ');
10916                    filter.activity.printComponentShortName(out);
10917                    out.print(" filter ");
10918                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10919        }
10920
10921        @Override
10922        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10923            return filter.activity;
10924        }
10925
10926        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10927            PackageParser.Activity activity = (PackageParser.Activity)label;
10928            out.print(prefix); out.print(
10929                    Integer.toHexString(System.identityHashCode(activity)));
10930                    out.print(' ');
10931                    activity.printComponentShortName(out);
10932            if (count > 1) {
10933                out.print(" ("); out.print(count); out.print(" filters)");
10934            }
10935            out.println();
10936        }
10937
10938        // Keys are String (activity class name), values are Activity.
10939        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10940                = new ArrayMap<ComponentName, PackageParser.Activity>();
10941        private int mFlags;
10942    }
10943
10944    private final class ServiceIntentResolver
10945            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10946        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10947                boolean defaultOnly, int userId) {
10948            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10949            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10950        }
10951
10952        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10953                int userId) {
10954            if (!sUserManager.exists(userId)) return null;
10955            mFlags = flags;
10956            return super.queryIntent(intent, resolvedType,
10957                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10958        }
10959
10960        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10961                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10962            if (!sUserManager.exists(userId)) return null;
10963            if (packageServices == null) {
10964                return null;
10965            }
10966            mFlags = flags;
10967            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10968            final int N = packageServices.size();
10969            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10970                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10971
10972            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10973            for (int i = 0; i < N; ++i) {
10974                intentFilters = packageServices.get(i).intents;
10975                if (intentFilters != null && intentFilters.size() > 0) {
10976                    PackageParser.ServiceIntentInfo[] array =
10977                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10978                    intentFilters.toArray(array);
10979                    listCut.add(array);
10980                }
10981            }
10982            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10983        }
10984
10985        public final void addService(PackageParser.Service s) {
10986            mServices.put(s.getComponentName(), s);
10987            if (DEBUG_SHOW_INFO) {
10988                Log.v(TAG, "  "
10989                        + (s.info.nonLocalizedLabel != null
10990                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10991                Log.v(TAG, "    Class=" + s.info.name);
10992            }
10993            final int NI = s.intents.size();
10994            int j;
10995            for (j=0; j<NI; j++) {
10996                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10997                if (DEBUG_SHOW_INFO) {
10998                    Log.v(TAG, "    IntentFilter:");
10999                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11000                }
11001                if (!intent.debugCheck()) {
11002                    Log.w(TAG, "==> For Service " + s.info.name);
11003                }
11004                addFilter(intent);
11005            }
11006        }
11007
11008        public final void removeService(PackageParser.Service s) {
11009            mServices.remove(s.getComponentName());
11010            if (DEBUG_SHOW_INFO) {
11011                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11012                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11013                Log.v(TAG, "    Class=" + s.info.name);
11014            }
11015            final int NI = s.intents.size();
11016            int j;
11017            for (j=0; j<NI; j++) {
11018                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11019                if (DEBUG_SHOW_INFO) {
11020                    Log.v(TAG, "    IntentFilter:");
11021                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11022                }
11023                removeFilter(intent);
11024            }
11025        }
11026
11027        @Override
11028        protected boolean allowFilterResult(
11029                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11030            ServiceInfo filterSi = filter.service.info;
11031            for (int i=dest.size()-1; i>=0; i--) {
11032                ServiceInfo destAi = dest.get(i).serviceInfo;
11033                if (destAi.name == filterSi.name
11034                        && destAi.packageName == filterSi.packageName) {
11035                    return false;
11036                }
11037            }
11038            return true;
11039        }
11040
11041        @Override
11042        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11043            return new PackageParser.ServiceIntentInfo[size];
11044        }
11045
11046        @Override
11047        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11048            if (!sUserManager.exists(userId)) return true;
11049            PackageParser.Package p = filter.service.owner;
11050            if (p != null) {
11051                PackageSetting ps = (PackageSetting)p.mExtras;
11052                if (ps != null) {
11053                    // System apps are never considered stopped for purposes of
11054                    // filtering, because there may be no way for the user to
11055                    // actually re-launch them.
11056                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11057                            && ps.getStopped(userId);
11058                }
11059            }
11060            return false;
11061        }
11062
11063        @Override
11064        protected boolean isPackageForFilter(String packageName,
11065                PackageParser.ServiceIntentInfo info) {
11066            return packageName.equals(info.service.owner.packageName);
11067        }
11068
11069        @Override
11070        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11071                int match, int userId) {
11072            if (!sUserManager.exists(userId)) return null;
11073            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11074            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11075                return null;
11076            }
11077            final PackageParser.Service service = info.service;
11078            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11079            if (ps == null) {
11080                return null;
11081            }
11082            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11083                    ps.readUserState(userId), userId);
11084            if (si == null) {
11085                return null;
11086            }
11087            final ResolveInfo res = new ResolveInfo();
11088            res.serviceInfo = si;
11089            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11090                res.filter = filter;
11091            }
11092            res.priority = info.getPriority();
11093            res.preferredOrder = service.owner.mPreferredOrder;
11094            res.match = match;
11095            res.isDefault = info.hasDefault;
11096            res.labelRes = info.labelRes;
11097            res.nonLocalizedLabel = info.nonLocalizedLabel;
11098            res.icon = info.icon;
11099            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11100            return res;
11101        }
11102
11103        @Override
11104        protected void sortResults(List<ResolveInfo> results) {
11105            Collections.sort(results, mResolvePrioritySorter);
11106        }
11107
11108        @Override
11109        protected void dumpFilter(PrintWriter out, String prefix,
11110                PackageParser.ServiceIntentInfo filter) {
11111            out.print(prefix); out.print(
11112                    Integer.toHexString(System.identityHashCode(filter.service)));
11113                    out.print(' ');
11114                    filter.service.printComponentShortName(out);
11115                    out.print(" filter ");
11116                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11117        }
11118
11119        @Override
11120        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11121            return filter.service;
11122        }
11123
11124        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11125            PackageParser.Service service = (PackageParser.Service)label;
11126            out.print(prefix); out.print(
11127                    Integer.toHexString(System.identityHashCode(service)));
11128                    out.print(' ');
11129                    service.printComponentShortName(out);
11130            if (count > 1) {
11131                out.print(" ("); out.print(count); out.print(" filters)");
11132            }
11133            out.println();
11134        }
11135
11136//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11137//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11138//            final List<ResolveInfo> retList = Lists.newArrayList();
11139//            while (i.hasNext()) {
11140//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11141//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11142//                    retList.add(resolveInfo);
11143//                }
11144//            }
11145//            return retList;
11146//        }
11147
11148        // Keys are String (activity class name), values are Activity.
11149        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11150                = new ArrayMap<ComponentName, PackageParser.Service>();
11151        private int mFlags;
11152    };
11153
11154    private final class ProviderIntentResolver
11155            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11156        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11157                boolean defaultOnly, int userId) {
11158            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11159            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11160        }
11161
11162        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11163                int userId) {
11164            if (!sUserManager.exists(userId))
11165                return null;
11166            mFlags = flags;
11167            return super.queryIntent(intent, resolvedType,
11168                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11169        }
11170
11171        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11172                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11173            if (!sUserManager.exists(userId))
11174                return null;
11175            if (packageProviders == null) {
11176                return null;
11177            }
11178            mFlags = flags;
11179            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11180            final int N = packageProviders.size();
11181            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11182                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11183
11184            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11185            for (int i = 0; i < N; ++i) {
11186                intentFilters = packageProviders.get(i).intents;
11187                if (intentFilters != null && intentFilters.size() > 0) {
11188                    PackageParser.ProviderIntentInfo[] array =
11189                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11190                    intentFilters.toArray(array);
11191                    listCut.add(array);
11192                }
11193            }
11194            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11195        }
11196
11197        public final void addProvider(PackageParser.Provider p) {
11198            if (mProviders.containsKey(p.getComponentName())) {
11199                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11200                return;
11201            }
11202
11203            mProviders.put(p.getComponentName(), p);
11204            if (DEBUG_SHOW_INFO) {
11205                Log.v(TAG, "  "
11206                        + (p.info.nonLocalizedLabel != null
11207                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11208                Log.v(TAG, "    Class=" + p.info.name);
11209            }
11210            final int NI = p.intents.size();
11211            int j;
11212            for (j = 0; j < NI; j++) {
11213                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11214                if (DEBUG_SHOW_INFO) {
11215                    Log.v(TAG, "    IntentFilter:");
11216                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11217                }
11218                if (!intent.debugCheck()) {
11219                    Log.w(TAG, "==> For Provider " + p.info.name);
11220                }
11221                addFilter(intent);
11222            }
11223        }
11224
11225        public final void removeProvider(PackageParser.Provider p) {
11226            mProviders.remove(p.getComponentName());
11227            if (DEBUG_SHOW_INFO) {
11228                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11229                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11230                Log.v(TAG, "    Class=" + p.info.name);
11231            }
11232            final int NI = p.intents.size();
11233            int j;
11234            for (j = 0; j < NI; j++) {
11235                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11236                if (DEBUG_SHOW_INFO) {
11237                    Log.v(TAG, "    IntentFilter:");
11238                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11239                }
11240                removeFilter(intent);
11241            }
11242        }
11243
11244        @Override
11245        protected boolean allowFilterResult(
11246                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11247            ProviderInfo filterPi = filter.provider.info;
11248            for (int i = dest.size() - 1; i >= 0; i--) {
11249                ProviderInfo destPi = dest.get(i).providerInfo;
11250                if (destPi.name == filterPi.name
11251                        && destPi.packageName == filterPi.packageName) {
11252                    return false;
11253                }
11254            }
11255            return true;
11256        }
11257
11258        @Override
11259        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11260            return new PackageParser.ProviderIntentInfo[size];
11261        }
11262
11263        @Override
11264        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11265            if (!sUserManager.exists(userId))
11266                return true;
11267            PackageParser.Package p = filter.provider.owner;
11268            if (p != null) {
11269                PackageSetting ps = (PackageSetting) p.mExtras;
11270                if (ps != null) {
11271                    // System apps are never considered stopped for purposes of
11272                    // filtering, because there may be no way for the user to
11273                    // actually re-launch them.
11274                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11275                            && ps.getStopped(userId);
11276                }
11277            }
11278            return false;
11279        }
11280
11281        @Override
11282        protected boolean isPackageForFilter(String packageName,
11283                PackageParser.ProviderIntentInfo info) {
11284            return packageName.equals(info.provider.owner.packageName);
11285        }
11286
11287        @Override
11288        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11289                int match, int userId) {
11290            if (!sUserManager.exists(userId))
11291                return null;
11292            final PackageParser.ProviderIntentInfo info = filter;
11293            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11294                return null;
11295            }
11296            final PackageParser.Provider provider = info.provider;
11297            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11298            if (ps == null) {
11299                return null;
11300            }
11301            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11302                    ps.readUserState(userId), userId);
11303            if (pi == null) {
11304                return null;
11305            }
11306            final ResolveInfo res = new ResolveInfo();
11307            res.providerInfo = pi;
11308            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11309                res.filter = filter;
11310            }
11311            res.priority = info.getPriority();
11312            res.preferredOrder = provider.owner.mPreferredOrder;
11313            res.match = match;
11314            res.isDefault = info.hasDefault;
11315            res.labelRes = info.labelRes;
11316            res.nonLocalizedLabel = info.nonLocalizedLabel;
11317            res.icon = info.icon;
11318            res.system = res.providerInfo.applicationInfo.isSystemApp();
11319            return res;
11320        }
11321
11322        @Override
11323        protected void sortResults(List<ResolveInfo> results) {
11324            Collections.sort(results, mResolvePrioritySorter);
11325        }
11326
11327        @Override
11328        protected void dumpFilter(PrintWriter out, String prefix,
11329                PackageParser.ProviderIntentInfo filter) {
11330            out.print(prefix);
11331            out.print(
11332                    Integer.toHexString(System.identityHashCode(filter.provider)));
11333            out.print(' ');
11334            filter.provider.printComponentShortName(out);
11335            out.print(" filter ");
11336            out.println(Integer.toHexString(System.identityHashCode(filter)));
11337        }
11338
11339        @Override
11340        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11341            return filter.provider;
11342        }
11343
11344        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11345            PackageParser.Provider provider = (PackageParser.Provider)label;
11346            out.print(prefix); out.print(
11347                    Integer.toHexString(System.identityHashCode(provider)));
11348                    out.print(' ');
11349                    provider.printComponentShortName(out);
11350            if (count > 1) {
11351                out.print(" ("); out.print(count); out.print(" filters)");
11352            }
11353            out.println();
11354        }
11355
11356        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11357                = new ArrayMap<ComponentName, PackageParser.Provider>();
11358        private int mFlags;
11359    }
11360
11361    private static final class EphemeralIntentResolver
11362            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11363        @Override
11364        protected EphemeralResolveIntentInfo[] newArray(int size) {
11365            return new EphemeralResolveIntentInfo[size];
11366        }
11367
11368        @Override
11369        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11370            return true;
11371        }
11372
11373        @Override
11374        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11375                int userId) {
11376            if (!sUserManager.exists(userId)) {
11377                return null;
11378            }
11379            return info.getEphemeralResolveInfo();
11380        }
11381    }
11382
11383    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11384            new Comparator<ResolveInfo>() {
11385        public int compare(ResolveInfo r1, ResolveInfo r2) {
11386            int v1 = r1.priority;
11387            int v2 = r2.priority;
11388            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11389            if (v1 != v2) {
11390                return (v1 > v2) ? -1 : 1;
11391            }
11392            v1 = r1.preferredOrder;
11393            v2 = r2.preferredOrder;
11394            if (v1 != v2) {
11395                return (v1 > v2) ? -1 : 1;
11396            }
11397            if (r1.isDefault != r2.isDefault) {
11398                return r1.isDefault ? -1 : 1;
11399            }
11400            v1 = r1.match;
11401            v2 = r2.match;
11402            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11403            if (v1 != v2) {
11404                return (v1 > v2) ? -1 : 1;
11405            }
11406            if (r1.system != r2.system) {
11407                return r1.system ? -1 : 1;
11408            }
11409            if (r1.activityInfo != null) {
11410                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11411            }
11412            if (r1.serviceInfo != null) {
11413                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11414            }
11415            if (r1.providerInfo != null) {
11416                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11417            }
11418            return 0;
11419        }
11420    };
11421
11422    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11423            new Comparator<ProviderInfo>() {
11424        public int compare(ProviderInfo p1, ProviderInfo p2) {
11425            final int v1 = p1.initOrder;
11426            final int v2 = p2.initOrder;
11427            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11428        }
11429    };
11430
11431    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11432            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11433            final int[] userIds) {
11434        mHandler.post(new Runnable() {
11435            @Override
11436            public void run() {
11437                try {
11438                    final IActivityManager am = ActivityManagerNative.getDefault();
11439                    if (am == null) return;
11440                    final int[] resolvedUserIds;
11441                    if (userIds == null) {
11442                        resolvedUserIds = am.getRunningUserIds();
11443                    } else {
11444                        resolvedUserIds = userIds;
11445                    }
11446                    for (int id : resolvedUserIds) {
11447                        final Intent intent = new Intent(action,
11448                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11449                        if (extras != null) {
11450                            intent.putExtras(extras);
11451                        }
11452                        if (targetPkg != null) {
11453                            intent.setPackage(targetPkg);
11454                        }
11455                        // Modify the UID when posting to other users
11456                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11457                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11458                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11459                            intent.putExtra(Intent.EXTRA_UID, uid);
11460                        }
11461                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11462                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11463                        if (DEBUG_BROADCASTS) {
11464                            RuntimeException here = new RuntimeException("here");
11465                            here.fillInStackTrace();
11466                            Slog.d(TAG, "Sending to user " + id + ": "
11467                                    + intent.toShortString(false, true, false, false)
11468                                    + " " + intent.getExtras(), here);
11469                        }
11470                        am.broadcastIntent(null, intent, null, finishedReceiver,
11471                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11472                                null, finishedReceiver != null, false, id);
11473                    }
11474                } catch (RemoteException ex) {
11475                }
11476            }
11477        });
11478    }
11479
11480    /**
11481     * Check if the external storage media is available. This is true if there
11482     * is a mounted external storage medium or if the external storage is
11483     * emulated.
11484     */
11485    private boolean isExternalMediaAvailable() {
11486        return mMediaMounted || Environment.isExternalStorageEmulated();
11487    }
11488
11489    @Override
11490    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11491        // writer
11492        synchronized (mPackages) {
11493            if (!isExternalMediaAvailable()) {
11494                // If the external storage is no longer mounted at this point,
11495                // the caller may not have been able to delete all of this
11496                // packages files and can not delete any more.  Bail.
11497                return null;
11498            }
11499            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11500            if (lastPackage != null) {
11501                pkgs.remove(lastPackage);
11502            }
11503            if (pkgs.size() > 0) {
11504                return pkgs.get(0);
11505            }
11506        }
11507        return null;
11508    }
11509
11510    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11511        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11512                userId, andCode ? 1 : 0, packageName);
11513        if (mSystemReady) {
11514            msg.sendToTarget();
11515        } else {
11516            if (mPostSystemReadyMessages == null) {
11517                mPostSystemReadyMessages = new ArrayList<>();
11518            }
11519            mPostSystemReadyMessages.add(msg);
11520        }
11521    }
11522
11523    void startCleaningPackages() {
11524        // reader
11525        if (!isExternalMediaAvailable()) {
11526            return;
11527        }
11528        synchronized (mPackages) {
11529            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11530                return;
11531            }
11532        }
11533        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11534        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11535        IActivityManager am = ActivityManagerNative.getDefault();
11536        if (am != null) {
11537            try {
11538                am.startService(null, intent, null, mContext.getOpPackageName(),
11539                        UserHandle.USER_SYSTEM);
11540            } catch (RemoteException e) {
11541            }
11542        }
11543    }
11544
11545    @Override
11546    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11547            int installFlags, String installerPackageName, int userId) {
11548        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11549
11550        final int callingUid = Binder.getCallingUid();
11551        enforceCrossUserPermission(callingUid, userId,
11552                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11553
11554        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11555            try {
11556                if (observer != null) {
11557                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11558                }
11559            } catch (RemoteException re) {
11560            }
11561            return;
11562        }
11563
11564        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11565            installFlags |= PackageManager.INSTALL_FROM_ADB;
11566
11567        } else {
11568            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11569            // about installerPackageName.
11570
11571            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11572            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11573        }
11574
11575        UserHandle user;
11576        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11577            user = UserHandle.ALL;
11578        } else {
11579            user = new UserHandle(userId);
11580        }
11581
11582        // Only system components can circumvent runtime permissions when installing.
11583        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11584                && mContext.checkCallingOrSelfPermission(Manifest.permission
11585                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11586            throw new SecurityException("You need the "
11587                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11588                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11589        }
11590
11591        final File originFile = new File(originPath);
11592        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11593
11594        final Message msg = mHandler.obtainMessage(INIT_COPY);
11595        final VerificationInfo verificationInfo = new VerificationInfo(
11596                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11597        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11598                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11599                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11600                null /*certificates*/);
11601        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11602        msg.obj = params;
11603
11604        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11605                System.identityHashCode(msg.obj));
11606        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11607                System.identityHashCode(msg.obj));
11608
11609        mHandler.sendMessage(msg);
11610    }
11611
11612    void installStage(String packageName, File stagedDir, String stagedCid,
11613            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11614            String installerPackageName, int installerUid, UserHandle user,
11615            Certificate[][] certificates) {
11616        if (DEBUG_EPHEMERAL) {
11617            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11618                Slog.d(TAG, "Ephemeral install of " + packageName);
11619            }
11620        }
11621        final VerificationInfo verificationInfo = new VerificationInfo(
11622                sessionParams.originatingUri, sessionParams.referrerUri,
11623                sessionParams.originatingUid, installerUid);
11624
11625        final OriginInfo origin;
11626        if (stagedDir != null) {
11627            origin = OriginInfo.fromStagedFile(stagedDir);
11628        } else {
11629            origin = OriginInfo.fromStagedContainer(stagedCid);
11630        }
11631
11632        final Message msg = mHandler.obtainMessage(INIT_COPY);
11633        final InstallParams params = new InstallParams(origin, null, observer,
11634                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11635                verificationInfo, user, sessionParams.abiOverride,
11636                sessionParams.grantedRuntimePermissions, certificates);
11637        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11638        msg.obj = params;
11639
11640        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11641                System.identityHashCode(msg.obj));
11642        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11643                System.identityHashCode(msg.obj));
11644
11645        mHandler.sendMessage(msg);
11646    }
11647
11648    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11649            int userId) {
11650        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11651        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11652    }
11653
11654    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11655            int appId, int userId) {
11656        Bundle extras = new Bundle(1);
11657        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11658
11659        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11660                packageName, extras, 0, null, null, new int[] {userId});
11661        try {
11662            IActivityManager am = ActivityManagerNative.getDefault();
11663            if (isSystem && am.isUserRunning(userId, 0)) {
11664                // The just-installed/enabled app is bundled on the system, so presumed
11665                // to be able to run automatically without needing an explicit launch.
11666                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11667                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11668                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11669                        .setPackage(packageName);
11670                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11671                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11672            }
11673        } catch (RemoteException e) {
11674            // shouldn't happen
11675            Slog.w(TAG, "Unable to bootstrap installed package", e);
11676        }
11677    }
11678
11679    @Override
11680    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11681            int userId) {
11682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11683        PackageSetting pkgSetting;
11684        final int uid = Binder.getCallingUid();
11685        enforceCrossUserPermission(uid, userId,
11686                true /* requireFullPermission */, true /* checkShell */,
11687                "setApplicationHiddenSetting for user " + userId);
11688
11689        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11690            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11691            return false;
11692        }
11693
11694        long callingId = Binder.clearCallingIdentity();
11695        try {
11696            boolean sendAdded = false;
11697            boolean sendRemoved = false;
11698            // writer
11699            synchronized (mPackages) {
11700                pkgSetting = mSettings.mPackages.get(packageName);
11701                if (pkgSetting == null) {
11702                    return false;
11703                }
11704                // Only allow protected packages to hide themselves.
11705                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11706                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11707                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11708                    return false;
11709                }
11710                if (pkgSetting.getHidden(userId) != hidden) {
11711                    pkgSetting.setHidden(hidden, userId);
11712                    mSettings.writePackageRestrictionsLPr(userId);
11713                    if (hidden) {
11714                        sendRemoved = true;
11715                    } else {
11716                        sendAdded = true;
11717                    }
11718                }
11719            }
11720            if (sendAdded) {
11721                sendPackageAddedForUser(packageName, pkgSetting, userId);
11722                return true;
11723            }
11724            if (sendRemoved) {
11725                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11726                        "hiding pkg");
11727                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11728                return true;
11729            }
11730        } finally {
11731            Binder.restoreCallingIdentity(callingId);
11732        }
11733        return false;
11734    }
11735
11736    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11737            int userId) {
11738        final PackageRemovedInfo info = new PackageRemovedInfo();
11739        info.removedPackage = packageName;
11740        info.removedUsers = new int[] {userId};
11741        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11742        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11743    }
11744
11745    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11746        if (pkgList.length > 0) {
11747            Bundle extras = new Bundle(1);
11748            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11749
11750            sendPackageBroadcast(
11751                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11752                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11753                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11754                    new int[] {userId});
11755        }
11756    }
11757
11758    /**
11759     * Returns true if application is not found or there was an error. Otherwise it returns
11760     * the hidden state of the package for the given user.
11761     */
11762    @Override
11763    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11764        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11765        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11766                true /* requireFullPermission */, false /* checkShell */,
11767                "getApplicationHidden for user " + userId);
11768        PackageSetting pkgSetting;
11769        long callingId = Binder.clearCallingIdentity();
11770        try {
11771            // writer
11772            synchronized (mPackages) {
11773                pkgSetting = mSettings.mPackages.get(packageName);
11774                if (pkgSetting == null) {
11775                    return true;
11776                }
11777                return pkgSetting.getHidden(userId);
11778            }
11779        } finally {
11780            Binder.restoreCallingIdentity(callingId);
11781        }
11782    }
11783
11784    /**
11785     * @hide
11786     */
11787    @Override
11788    public int installExistingPackageAsUser(String packageName, int userId) {
11789        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11790                null);
11791        PackageSetting pkgSetting;
11792        final int uid = Binder.getCallingUid();
11793        enforceCrossUserPermission(uid, userId,
11794                true /* requireFullPermission */, true /* checkShell */,
11795                "installExistingPackage for user " + userId);
11796        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11797            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11798        }
11799
11800        long callingId = Binder.clearCallingIdentity();
11801        try {
11802            boolean installed = false;
11803
11804            // writer
11805            synchronized (mPackages) {
11806                pkgSetting = mSettings.mPackages.get(packageName);
11807                if (pkgSetting == null) {
11808                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11809                }
11810                if (!pkgSetting.getInstalled(userId)) {
11811                    pkgSetting.setInstalled(true, userId);
11812                    pkgSetting.setHidden(false, userId);
11813                    mSettings.writePackageRestrictionsLPr(userId);
11814                    installed = true;
11815                }
11816            }
11817
11818            if (installed) {
11819                if (pkgSetting.pkg != null) {
11820                    synchronized (mInstallLock) {
11821                        // We don't need to freeze for a brand new install
11822                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11823                    }
11824                }
11825                sendPackageAddedForUser(packageName, pkgSetting, userId);
11826            }
11827        } finally {
11828            Binder.restoreCallingIdentity(callingId);
11829        }
11830
11831        return PackageManager.INSTALL_SUCCEEDED;
11832    }
11833
11834    boolean isUserRestricted(int userId, String restrictionKey) {
11835        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11836        if (restrictions.getBoolean(restrictionKey, false)) {
11837            Log.w(TAG, "User is restricted: " + restrictionKey);
11838            return true;
11839        }
11840        return false;
11841    }
11842
11843    @Override
11844    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11845            int userId) {
11846        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11847        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11848                true /* requireFullPermission */, true /* checkShell */,
11849                "setPackagesSuspended for user " + userId);
11850
11851        if (ArrayUtils.isEmpty(packageNames)) {
11852            return packageNames;
11853        }
11854
11855        // List of package names for whom the suspended state has changed.
11856        List<String> changedPackages = new ArrayList<>(packageNames.length);
11857        // List of package names for whom the suspended state is not set as requested in this
11858        // method.
11859        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11860        long callingId = Binder.clearCallingIdentity();
11861        try {
11862            for (int i = 0; i < packageNames.length; i++) {
11863                String packageName = packageNames[i];
11864                boolean changed = false;
11865                final int appId;
11866                synchronized (mPackages) {
11867                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11868                    if (pkgSetting == null) {
11869                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11870                                + "\". Skipping suspending/un-suspending.");
11871                        unactionedPackages.add(packageName);
11872                        continue;
11873                    }
11874                    appId = pkgSetting.appId;
11875                    if (pkgSetting.getSuspended(userId) != suspended) {
11876                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11877                            unactionedPackages.add(packageName);
11878                            continue;
11879                        }
11880                        pkgSetting.setSuspended(suspended, userId);
11881                        mSettings.writePackageRestrictionsLPr(userId);
11882                        changed = true;
11883                        changedPackages.add(packageName);
11884                    }
11885                }
11886
11887                if (changed && suspended) {
11888                    killApplication(packageName, UserHandle.getUid(userId, appId),
11889                            "suspending package");
11890                }
11891            }
11892        } finally {
11893            Binder.restoreCallingIdentity(callingId);
11894        }
11895
11896        if (!changedPackages.isEmpty()) {
11897            sendPackagesSuspendedForUser(changedPackages.toArray(
11898                    new String[changedPackages.size()]), userId, suspended);
11899        }
11900
11901        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11902    }
11903
11904    @Override
11905    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11906        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11907                true /* requireFullPermission */, false /* checkShell */,
11908                "isPackageSuspendedForUser for user " + userId);
11909        synchronized (mPackages) {
11910            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11911            if (pkgSetting == null) {
11912                throw new IllegalArgumentException("Unknown target package: " + packageName);
11913            }
11914            return pkgSetting.getSuspended(userId);
11915        }
11916    }
11917
11918    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11919        if (isPackageDeviceAdmin(packageName, userId)) {
11920            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11921                    + "\": has an active device admin");
11922            return false;
11923        }
11924
11925        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11926        if (packageName.equals(activeLauncherPackageName)) {
11927            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11928                    + "\": contains the active launcher");
11929            return false;
11930        }
11931
11932        if (packageName.equals(mRequiredInstallerPackage)) {
11933            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11934                    + "\": required for package installation");
11935            return false;
11936        }
11937
11938        if (packageName.equals(mRequiredVerifierPackage)) {
11939            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11940                    + "\": required for package verification");
11941            return false;
11942        }
11943
11944        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11945            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11946                    + "\": is the default dialer");
11947            return false;
11948        }
11949
11950        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11951            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11952                    + "\": protected package");
11953            return false;
11954        }
11955
11956        return true;
11957    }
11958
11959    private String getActiveLauncherPackageName(int userId) {
11960        Intent intent = new Intent(Intent.ACTION_MAIN);
11961        intent.addCategory(Intent.CATEGORY_HOME);
11962        ResolveInfo resolveInfo = resolveIntent(
11963                intent,
11964                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11965                PackageManager.MATCH_DEFAULT_ONLY,
11966                userId);
11967
11968        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11969    }
11970
11971    private String getDefaultDialerPackageName(int userId) {
11972        synchronized (mPackages) {
11973            return mSettings.getDefaultDialerPackageNameLPw(userId);
11974        }
11975    }
11976
11977    @Override
11978    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11979        mContext.enforceCallingOrSelfPermission(
11980                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11981                "Only package verification agents can verify applications");
11982
11983        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11984        final PackageVerificationResponse response = new PackageVerificationResponse(
11985                verificationCode, Binder.getCallingUid());
11986        msg.arg1 = id;
11987        msg.obj = response;
11988        mHandler.sendMessage(msg);
11989    }
11990
11991    @Override
11992    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11993            long millisecondsToDelay) {
11994        mContext.enforceCallingOrSelfPermission(
11995                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11996                "Only package verification agents can extend verification timeouts");
11997
11998        final PackageVerificationState state = mPendingVerification.get(id);
11999        final PackageVerificationResponse response = new PackageVerificationResponse(
12000                verificationCodeAtTimeout, Binder.getCallingUid());
12001
12002        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12003            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12004        }
12005        if (millisecondsToDelay < 0) {
12006            millisecondsToDelay = 0;
12007        }
12008        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12009                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12010            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12011        }
12012
12013        if ((state != null) && !state.timeoutExtended()) {
12014            state.extendTimeout();
12015
12016            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12017            msg.arg1 = id;
12018            msg.obj = response;
12019            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12020        }
12021    }
12022
12023    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12024            int verificationCode, UserHandle user) {
12025        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12026        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12027        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12028        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12029        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12030
12031        mContext.sendBroadcastAsUser(intent, user,
12032                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12033    }
12034
12035    private ComponentName matchComponentForVerifier(String packageName,
12036            List<ResolveInfo> receivers) {
12037        ActivityInfo targetReceiver = null;
12038
12039        final int NR = receivers.size();
12040        for (int i = 0; i < NR; i++) {
12041            final ResolveInfo info = receivers.get(i);
12042            if (info.activityInfo == null) {
12043                continue;
12044            }
12045
12046            if (packageName.equals(info.activityInfo.packageName)) {
12047                targetReceiver = info.activityInfo;
12048                break;
12049            }
12050        }
12051
12052        if (targetReceiver == null) {
12053            return null;
12054        }
12055
12056        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12057    }
12058
12059    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12060            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12061        if (pkgInfo.verifiers.length == 0) {
12062            return null;
12063        }
12064
12065        final int N = pkgInfo.verifiers.length;
12066        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12067        for (int i = 0; i < N; i++) {
12068            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12069
12070            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12071                    receivers);
12072            if (comp == null) {
12073                continue;
12074            }
12075
12076            final int verifierUid = getUidForVerifier(verifierInfo);
12077            if (verifierUid == -1) {
12078                continue;
12079            }
12080
12081            if (DEBUG_VERIFY) {
12082                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12083                        + " with the correct signature");
12084            }
12085            sufficientVerifiers.add(comp);
12086            verificationState.addSufficientVerifier(verifierUid);
12087        }
12088
12089        return sufficientVerifiers;
12090    }
12091
12092    private int getUidForVerifier(VerifierInfo verifierInfo) {
12093        synchronized (mPackages) {
12094            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12095            if (pkg == null) {
12096                return -1;
12097            } else if (pkg.mSignatures.length != 1) {
12098                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12099                        + " has more than one signature; ignoring");
12100                return -1;
12101            }
12102
12103            /*
12104             * If the public key of the package's signature does not match
12105             * our expected public key, then this is a different package and
12106             * we should skip.
12107             */
12108
12109            final byte[] expectedPublicKey;
12110            try {
12111                final Signature verifierSig = pkg.mSignatures[0];
12112                final PublicKey publicKey = verifierSig.getPublicKey();
12113                expectedPublicKey = publicKey.getEncoded();
12114            } catch (CertificateException e) {
12115                return -1;
12116            }
12117
12118            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12119
12120            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12121                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12122                        + " does not have the expected public key; ignoring");
12123                return -1;
12124            }
12125
12126            return pkg.applicationInfo.uid;
12127        }
12128    }
12129
12130    @Override
12131    public void finishPackageInstall(int token, boolean didLaunch) {
12132        enforceSystemOrRoot("Only the system is allowed to finish installs");
12133
12134        if (DEBUG_INSTALL) {
12135            Slog.v(TAG, "BM finishing package install for " + token);
12136        }
12137        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12138
12139        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12140        mHandler.sendMessage(msg);
12141    }
12142
12143    /**
12144     * Get the verification agent timeout.
12145     *
12146     * @return verification timeout in milliseconds
12147     */
12148    private long getVerificationTimeout() {
12149        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12150                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12151                DEFAULT_VERIFICATION_TIMEOUT);
12152    }
12153
12154    /**
12155     * Get the default verification agent response code.
12156     *
12157     * @return default verification response code
12158     */
12159    private int getDefaultVerificationResponse() {
12160        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12161                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12162                DEFAULT_VERIFICATION_RESPONSE);
12163    }
12164
12165    /**
12166     * Check whether or not package verification has been enabled.
12167     *
12168     * @return true if verification should be performed
12169     */
12170    private boolean isVerificationEnabled(int userId, int installFlags) {
12171        if (!DEFAULT_VERIFY_ENABLE) {
12172            return false;
12173        }
12174        // Ephemeral apps don't get the full verification treatment
12175        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12176            if (DEBUG_EPHEMERAL) {
12177                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12178            }
12179            return false;
12180        }
12181
12182        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12183
12184        // Check if installing from ADB
12185        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12186            // Do not run verification in a test harness environment
12187            if (ActivityManager.isRunningInTestHarness()) {
12188                return false;
12189            }
12190            if (ensureVerifyAppsEnabled) {
12191                return true;
12192            }
12193            // Check if the developer does not want package verification for ADB installs
12194            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12195                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12196                return false;
12197            }
12198        }
12199
12200        if (ensureVerifyAppsEnabled) {
12201            return true;
12202        }
12203
12204        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12205                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12206    }
12207
12208    @Override
12209    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12210            throws RemoteException {
12211        mContext.enforceCallingOrSelfPermission(
12212                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12213                "Only intentfilter verification agents can verify applications");
12214
12215        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12216        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12217                Binder.getCallingUid(), verificationCode, failedDomains);
12218        msg.arg1 = id;
12219        msg.obj = response;
12220        mHandler.sendMessage(msg);
12221    }
12222
12223    @Override
12224    public int getIntentVerificationStatus(String packageName, int userId) {
12225        synchronized (mPackages) {
12226            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12227        }
12228    }
12229
12230    @Override
12231    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12232        mContext.enforceCallingOrSelfPermission(
12233                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12234
12235        boolean result = false;
12236        synchronized (mPackages) {
12237            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12238        }
12239        if (result) {
12240            scheduleWritePackageRestrictionsLocked(userId);
12241        }
12242        return result;
12243    }
12244
12245    @Override
12246    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12247            String packageName) {
12248        synchronized (mPackages) {
12249            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12250        }
12251    }
12252
12253    @Override
12254    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12255        if (TextUtils.isEmpty(packageName)) {
12256            return ParceledListSlice.emptyList();
12257        }
12258        synchronized (mPackages) {
12259            PackageParser.Package pkg = mPackages.get(packageName);
12260            if (pkg == null || pkg.activities == null) {
12261                return ParceledListSlice.emptyList();
12262            }
12263            final int count = pkg.activities.size();
12264            ArrayList<IntentFilter> result = new ArrayList<>();
12265            for (int n=0; n<count; n++) {
12266                PackageParser.Activity activity = pkg.activities.get(n);
12267                if (activity.intents != null && activity.intents.size() > 0) {
12268                    result.addAll(activity.intents);
12269                }
12270            }
12271            return new ParceledListSlice<>(result);
12272        }
12273    }
12274
12275    @Override
12276    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12277        mContext.enforceCallingOrSelfPermission(
12278                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12279
12280        synchronized (mPackages) {
12281            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12282            if (packageName != null) {
12283                result |= updateIntentVerificationStatus(packageName,
12284                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12285                        userId);
12286                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12287                        packageName, userId);
12288            }
12289            return result;
12290        }
12291    }
12292
12293    @Override
12294    public String getDefaultBrowserPackageName(int userId) {
12295        synchronized (mPackages) {
12296            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12297        }
12298    }
12299
12300    /**
12301     * Get the "allow unknown sources" setting.
12302     *
12303     * @return the current "allow unknown sources" setting
12304     */
12305    private int getUnknownSourcesSettings() {
12306        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12307                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12308                -1);
12309    }
12310
12311    @Override
12312    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12313        final int uid = Binder.getCallingUid();
12314        // writer
12315        synchronized (mPackages) {
12316            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12317            if (targetPackageSetting == null) {
12318                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12319            }
12320
12321            PackageSetting installerPackageSetting;
12322            if (installerPackageName != null) {
12323                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12324                if (installerPackageSetting == null) {
12325                    throw new IllegalArgumentException("Unknown installer package: "
12326                            + installerPackageName);
12327                }
12328            } else {
12329                installerPackageSetting = null;
12330            }
12331
12332            Signature[] callerSignature;
12333            Object obj = mSettings.getUserIdLPr(uid);
12334            if (obj != null) {
12335                if (obj instanceof SharedUserSetting) {
12336                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12337                } else if (obj instanceof PackageSetting) {
12338                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12339                } else {
12340                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12341                }
12342            } else {
12343                throw new SecurityException("Unknown calling UID: " + uid);
12344            }
12345
12346            // Verify: can't set installerPackageName to a package that is
12347            // not signed with the same cert as the caller.
12348            if (installerPackageSetting != null) {
12349                if (compareSignatures(callerSignature,
12350                        installerPackageSetting.signatures.mSignatures)
12351                        != PackageManager.SIGNATURE_MATCH) {
12352                    throw new SecurityException(
12353                            "Caller does not have same cert as new installer package "
12354                            + installerPackageName);
12355                }
12356            }
12357
12358            // Verify: if target already has an installer package, it must
12359            // be signed with the same cert as the caller.
12360            if (targetPackageSetting.installerPackageName != null) {
12361                PackageSetting setting = mSettings.mPackages.get(
12362                        targetPackageSetting.installerPackageName);
12363                // If the currently set package isn't valid, then it's always
12364                // okay to change it.
12365                if (setting != null) {
12366                    if (compareSignatures(callerSignature,
12367                            setting.signatures.mSignatures)
12368                            != PackageManager.SIGNATURE_MATCH) {
12369                        throw new SecurityException(
12370                                "Caller does not have same cert as old installer package "
12371                                + targetPackageSetting.installerPackageName);
12372                    }
12373                }
12374            }
12375
12376            // Okay!
12377            targetPackageSetting.installerPackageName = installerPackageName;
12378            if (installerPackageName != null) {
12379                mSettings.mInstallerPackages.add(installerPackageName);
12380            }
12381            scheduleWriteSettingsLocked();
12382        }
12383    }
12384
12385    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12386        // Queue up an async operation since the package installation may take a little while.
12387        mHandler.post(new Runnable() {
12388            public void run() {
12389                mHandler.removeCallbacks(this);
12390                 // Result object to be returned
12391                PackageInstalledInfo res = new PackageInstalledInfo();
12392                res.setReturnCode(currentStatus);
12393                res.uid = -1;
12394                res.pkg = null;
12395                res.removedInfo = null;
12396                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12397                    args.doPreInstall(res.returnCode);
12398                    synchronized (mInstallLock) {
12399                        installPackageTracedLI(args, res);
12400                    }
12401                    args.doPostInstall(res.returnCode, res.uid);
12402                }
12403
12404                // A restore should be performed at this point if (a) the install
12405                // succeeded, (b) the operation is not an update, and (c) the new
12406                // package has not opted out of backup participation.
12407                final boolean update = res.removedInfo != null
12408                        && res.removedInfo.removedPackage != null;
12409                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12410                boolean doRestore = !update
12411                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12412
12413                // Set up the post-install work request bookkeeping.  This will be used
12414                // and cleaned up by the post-install event handling regardless of whether
12415                // there's a restore pass performed.  Token values are >= 1.
12416                int token;
12417                if (mNextInstallToken < 0) mNextInstallToken = 1;
12418                token = mNextInstallToken++;
12419
12420                PostInstallData data = new PostInstallData(args, res);
12421                mRunningInstalls.put(token, data);
12422                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12423
12424                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12425                    // Pass responsibility to the Backup Manager.  It will perform a
12426                    // restore if appropriate, then pass responsibility back to the
12427                    // Package Manager to run the post-install observer callbacks
12428                    // and broadcasts.
12429                    IBackupManager bm = IBackupManager.Stub.asInterface(
12430                            ServiceManager.getService(Context.BACKUP_SERVICE));
12431                    if (bm != null) {
12432                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12433                                + " to BM for possible restore");
12434                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12435                        try {
12436                            // TODO: http://b/22388012
12437                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12438                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12439                            } else {
12440                                doRestore = false;
12441                            }
12442                        } catch (RemoteException e) {
12443                            // can't happen; the backup manager is local
12444                        } catch (Exception e) {
12445                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12446                            doRestore = false;
12447                        }
12448                    } else {
12449                        Slog.e(TAG, "Backup Manager not found!");
12450                        doRestore = false;
12451                    }
12452                }
12453
12454                if (!doRestore) {
12455                    // No restore possible, or the Backup Manager was mysteriously not
12456                    // available -- just fire the post-install work request directly.
12457                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12458
12459                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12460
12461                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12462                    mHandler.sendMessage(msg);
12463                }
12464            }
12465        });
12466    }
12467
12468    /**
12469     * Callback from PackageSettings whenever an app is first transitioned out of the
12470     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12471     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12472     * here whether the app is the target of an ongoing install, and only send the
12473     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12474     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12475     * handling.
12476     */
12477    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12478        // Serialize this with the rest of the install-process message chain.  In the
12479        // restore-at-install case, this Runnable will necessarily run before the
12480        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12481        // are coherent.  In the non-restore case, the app has already completed install
12482        // and been launched through some other means, so it is not in a problematic
12483        // state for observers to see the FIRST_LAUNCH signal.
12484        mHandler.post(new Runnable() {
12485            @Override
12486            public void run() {
12487                for (int i = 0; i < mRunningInstalls.size(); i++) {
12488                    final PostInstallData data = mRunningInstalls.valueAt(i);
12489                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12490                        // right package; but is it for the right user?
12491                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12492                            if (userId == data.res.newUsers[uIndex]) {
12493                                if (DEBUG_BACKUP) {
12494                                    Slog.i(TAG, "Package " + pkgName
12495                                            + " being restored so deferring FIRST_LAUNCH");
12496                                }
12497                                return;
12498                            }
12499                        }
12500                    }
12501                }
12502                // didn't find it, so not being restored
12503                if (DEBUG_BACKUP) {
12504                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12505                }
12506                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12507            }
12508        });
12509    }
12510
12511    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12512        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12513                installerPkg, null, userIds);
12514    }
12515
12516    private abstract class HandlerParams {
12517        private static final int MAX_RETRIES = 4;
12518
12519        /**
12520         * Number of times startCopy() has been attempted and had a non-fatal
12521         * error.
12522         */
12523        private int mRetries = 0;
12524
12525        /** User handle for the user requesting the information or installation. */
12526        private final UserHandle mUser;
12527        String traceMethod;
12528        int traceCookie;
12529
12530        HandlerParams(UserHandle user) {
12531            mUser = user;
12532        }
12533
12534        UserHandle getUser() {
12535            return mUser;
12536        }
12537
12538        HandlerParams setTraceMethod(String traceMethod) {
12539            this.traceMethod = traceMethod;
12540            return this;
12541        }
12542
12543        HandlerParams setTraceCookie(int traceCookie) {
12544            this.traceCookie = traceCookie;
12545            return this;
12546        }
12547
12548        final boolean startCopy() {
12549            boolean res;
12550            try {
12551                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12552
12553                if (++mRetries > MAX_RETRIES) {
12554                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12555                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12556                    handleServiceError();
12557                    return false;
12558                } else {
12559                    handleStartCopy();
12560                    res = true;
12561                }
12562            } catch (RemoteException e) {
12563                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12564                mHandler.sendEmptyMessage(MCS_RECONNECT);
12565                res = false;
12566            }
12567            handleReturnCode();
12568            return res;
12569        }
12570
12571        final void serviceError() {
12572            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12573            handleServiceError();
12574            handleReturnCode();
12575        }
12576
12577        abstract void handleStartCopy() throws RemoteException;
12578        abstract void handleServiceError();
12579        abstract void handleReturnCode();
12580    }
12581
12582    class MeasureParams extends HandlerParams {
12583        private final PackageStats mStats;
12584        private boolean mSuccess;
12585
12586        private final IPackageStatsObserver mObserver;
12587
12588        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12589            super(new UserHandle(stats.userHandle));
12590            mObserver = observer;
12591            mStats = stats;
12592        }
12593
12594        @Override
12595        public String toString() {
12596            return "MeasureParams{"
12597                + Integer.toHexString(System.identityHashCode(this))
12598                + " " + mStats.packageName + "}";
12599        }
12600
12601        @Override
12602        void handleStartCopy() throws RemoteException {
12603            synchronized (mInstallLock) {
12604                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12605            }
12606
12607            if (mSuccess) {
12608                boolean mounted = false;
12609                try {
12610                    final String status = Environment.getExternalStorageState();
12611                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12612                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12613                } catch (Exception e) {
12614                }
12615
12616                if (mounted) {
12617                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12618
12619                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12620                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12621
12622                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12623                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12624
12625                    // Always subtract cache size, since it's a subdirectory
12626                    mStats.externalDataSize -= mStats.externalCacheSize;
12627
12628                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12629                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12630
12631                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12632                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12633                }
12634            }
12635        }
12636
12637        @Override
12638        void handleReturnCode() {
12639            if (mObserver != null) {
12640                try {
12641                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12642                } catch (RemoteException e) {
12643                    Slog.i(TAG, "Observer no longer exists.");
12644                }
12645            }
12646        }
12647
12648        @Override
12649        void handleServiceError() {
12650            Slog.e(TAG, "Could not measure application " + mStats.packageName
12651                            + " external storage");
12652        }
12653    }
12654
12655    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12656            throws RemoteException {
12657        long result = 0;
12658        for (File path : paths) {
12659            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12660        }
12661        return result;
12662    }
12663
12664    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12665        for (File path : paths) {
12666            try {
12667                mcs.clearDirectory(path.getAbsolutePath());
12668            } catch (RemoteException e) {
12669            }
12670        }
12671    }
12672
12673    static class OriginInfo {
12674        /**
12675         * Location where install is coming from, before it has been
12676         * copied/renamed into place. This could be a single monolithic APK
12677         * file, or a cluster directory. This location may be untrusted.
12678         */
12679        final File file;
12680        final String cid;
12681
12682        /**
12683         * Flag indicating that {@link #file} or {@link #cid} has already been
12684         * staged, meaning downstream users don't need to defensively copy the
12685         * contents.
12686         */
12687        final boolean staged;
12688
12689        /**
12690         * Flag indicating that {@link #file} or {@link #cid} is an already
12691         * installed app that is being moved.
12692         */
12693        final boolean existing;
12694
12695        final String resolvedPath;
12696        final File resolvedFile;
12697
12698        static OriginInfo fromNothing() {
12699            return new OriginInfo(null, null, false, false);
12700        }
12701
12702        static OriginInfo fromUntrustedFile(File file) {
12703            return new OriginInfo(file, null, false, false);
12704        }
12705
12706        static OriginInfo fromExistingFile(File file) {
12707            return new OriginInfo(file, null, false, true);
12708        }
12709
12710        static OriginInfo fromStagedFile(File file) {
12711            return new OriginInfo(file, null, true, false);
12712        }
12713
12714        static OriginInfo fromStagedContainer(String cid) {
12715            return new OriginInfo(null, cid, true, false);
12716        }
12717
12718        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12719            this.file = file;
12720            this.cid = cid;
12721            this.staged = staged;
12722            this.existing = existing;
12723
12724            if (cid != null) {
12725                resolvedPath = PackageHelper.getSdDir(cid);
12726                resolvedFile = new File(resolvedPath);
12727            } else if (file != null) {
12728                resolvedPath = file.getAbsolutePath();
12729                resolvedFile = file;
12730            } else {
12731                resolvedPath = null;
12732                resolvedFile = null;
12733            }
12734        }
12735    }
12736
12737    static class MoveInfo {
12738        final int moveId;
12739        final String fromUuid;
12740        final String toUuid;
12741        final String packageName;
12742        final String dataAppName;
12743        final int appId;
12744        final String seinfo;
12745        final int targetSdkVersion;
12746
12747        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12748                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12749            this.moveId = moveId;
12750            this.fromUuid = fromUuid;
12751            this.toUuid = toUuid;
12752            this.packageName = packageName;
12753            this.dataAppName = dataAppName;
12754            this.appId = appId;
12755            this.seinfo = seinfo;
12756            this.targetSdkVersion = targetSdkVersion;
12757        }
12758    }
12759
12760    static class VerificationInfo {
12761        /** A constant used to indicate that a uid value is not present. */
12762        public static final int NO_UID = -1;
12763
12764        /** URI referencing where the package was downloaded from. */
12765        final Uri originatingUri;
12766
12767        /** HTTP referrer URI associated with the originatingURI. */
12768        final Uri referrer;
12769
12770        /** UID of the application that the install request originated from. */
12771        final int originatingUid;
12772
12773        /** UID of application requesting the install */
12774        final int installerUid;
12775
12776        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12777            this.originatingUri = originatingUri;
12778            this.referrer = referrer;
12779            this.originatingUid = originatingUid;
12780            this.installerUid = installerUid;
12781        }
12782    }
12783
12784    class InstallParams extends HandlerParams {
12785        final OriginInfo origin;
12786        final MoveInfo move;
12787        final IPackageInstallObserver2 observer;
12788        int installFlags;
12789        final String installerPackageName;
12790        final String volumeUuid;
12791        private InstallArgs mArgs;
12792        private int mRet;
12793        final String packageAbiOverride;
12794        final String[] grantedRuntimePermissions;
12795        final VerificationInfo verificationInfo;
12796        final Certificate[][] certificates;
12797
12798        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12799                int installFlags, String installerPackageName, String volumeUuid,
12800                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12801                String[] grantedPermissions, Certificate[][] certificates) {
12802            super(user);
12803            this.origin = origin;
12804            this.move = move;
12805            this.observer = observer;
12806            this.installFlags = installFlags;
12807            this.installerPackageName = installerPackageName;
12808            this.volumeUuid = volumeUuid;
12809            this.verificationInfo = verificationInfo;
12810            this.packageAbiOverride = packageAbiOverride;
12811            this.grantedRuntimePermissions = grantedPermissions;
12812            this.certificates = certificates;
12813        }
12814
12815        @Override
12816        public String toString() {
12817            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12818                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12819        }
12820
12821        private int installLocationPolicy(PackageInfoLite pkgLite) {
12822            String packageName = pkgLite.packageName;
12823            int installLocation = pkgLite.installLocation;
12824            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12825            // reader
12826            synchronized (mPackages) {
12827                // Currently installed package which the new package is attempting to replace or
12828                // null if no such package is installed.
12829                PackageParser.Package installedPkg = mPackages.get(packageName);
12830                // Package which currently owns the data which the new package will own if installed.
12831                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12832                // will be null whereas dataOwnerPkg will contain information about the package
12833                // which was uninstalled while keeping its data.
12834                PackageParser.Package dataOwnerPkg = installedPkg;
12835                if (dataOwnerPkg  == null) {
12836                    PackageSetting ps = mSettings.mPackages.get(packageName);
12837                    if (ps != null) {
12838                        dataOwnerPkg = ps.pkg;
12839                    }
12840                }
12841
12842                if (dataOwnerPkg != null) {
12843                    // If installed, the package will get access to data left on the device by its
12844                    // predecessor. As a security measure, this is permited only if this is not a
12845                    // version downgrade or if the predecessor package is marked as debuggable and
12846                    // a downgrade is explicitly requested.
12847                    //
12848                    // On debuggable platform builds, downgrades are permitted even for
12849                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12850                    // not offer security guarantees and thus it's OK to disable some security
12851                    // mechanisms to make debugging/testing easier on those builds. However, even on
12852                    // debuggable builds downgrades of packages are permitted only if requested via
12853                    // installFlags. This is because we aim to keep the behavior of debuggable
12854                    // platform builds as close as possible to the behavior of non-debuggable
12855                    // platform builds.
12856                    final boolean downgradeRequested =
12857                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12858                    final boolean packageDebuggable =
12859                                (dataOwnerPkg.applicationInfo.flags
12860                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12861                    final boolean downgradePermitted =
12862                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12863                    if (!downgradePermitted) {
12864                        try {
12865                            checkDowngrade(dataOwnerPkg, pkgLite);
12866                        } catch (PackageManagerException e) {
12867                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12868                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12869                        }
12870                    }
12871                }
12872
12873                if (installedPkg != null) {
12874                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12875                        // Check for updated system application.
12876                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12877                            if (onSd) {
12878                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12879                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12880                            }
12881                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12882                        } else {
12883                            if (onSd) {
12884                                // Install flag overrides everything.
12885                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12886                            }
12887                            // If current upgrade specifies particular preference
12888                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12889                                // Application explicitly specified internal.
12890                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12891                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12892                                // App explictly prefers external. Let policy decide
12893                            } else {
12894                                // Prefer previous location
12895                                if (isExternal(installedPkg)) {
12896                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12897                                }
12898                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12899                            }
12900                        }
12901                    } else {
12902                        // Invalid install. Return error code
12903                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12904                    }
12905                }
12906            }
12907            // All the special cases have been taken care of.
12908            // Return result based on recommended install location.
12909            if (onSd) {
12910                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12911            }
12912            return pkgLite.recommendedInstallLocation;
12913        }
12914
12915        /*
12916         * Invoke remote method to get package information and install
12917         * location values. Override install location based on default
12918         * policy if needed and then create install arguments based
12919         * on the install location.
12920         */
12921        public void handleStartCopy() throws RemoteException {
12922            int ret = PackageManager.INSTALL_SUCCEEDED;
12923
12924            // If we're already staged, we've firmly committed to an install location
12925            if (origin.staged) {
12926                if (origin.file != null) {
12927                    installFlags |= PackageManager.INSTALL_INTERNAL;
12928                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12929                } else if (origin.cid != null) {
12930                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12931                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12932                } else {
12933                    throw new IllegalStateException("Invalid stage location");
12934                }
12935            }
12936
12937            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12938            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12939            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12940            PackageInfoLite pkgLite = null;
12941
12942            if (onInt && onSd) {
12943                // Check if both bits are set.
12944                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12945                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12946            } else if (onSd && ephemeral) {
12947                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12948                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12949            } else {
12950                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12951                        packageAbiOverride);
12952
12953                if (DEBUG_EPHEMERAL && ephemeral) {
12954                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12955                }
12956
12957                /*
12958                 * If we have too little free space, try to free cache
12959                 * before giving up.
12960                 */
12961                if (!origin.staged && pkgLite.recommendedInstallLocation
12962                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12963                    // TODO: focus freeing disk space on the target device
12964                    final StorageManager storage = StorageManager.from(mContext);
12965                    final long lowThreshold = storage.getStorageLowBytes(
12966                            Environment.getDataDirectory());
12967
12968                    final long sizeBytes = mContainerService.calculateInstalledSize(
12969                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12970
12971                    try {
12972                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12973                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12974                                installFlags, packageAbiOverride);
12975                    } catch (InstallerException e) {
12976                        Slog.w(TAG, "Failed to free cache", e);
12977                    }
12978
12979                    /*
12980                     * The cache free must have deleted the file we
12981                     * downloaded to install.
12982                     *
12983                     * TODO: fix the "freeCache" call to not delete
12984                     *       the file we care about.
12985                     */
12986                    if (pkgLite.recommendedInstallLocation
12987                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12988                        pkgLite.recommendedInstallLocation
12989                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12990                    }
12991                }
12992            }
12993
12994            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12995                int loc = pkgLite.recommendedInstallLocation;
12996                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12997                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12998                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12999                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13000                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13001                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13002                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13003                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13004                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13005                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13006                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13007                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13008                } else {
13009                    // Override with defaults if needed.
13010                    loc = installLocationPolicy(pkgLite);
13011                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13012                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13013                    } else if (!onSd && !onInt) {
13014                        // Override install location with flags
13015                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13016                            // Set the flag to install on external media.
13017                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13018                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13019                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13020                            if (DEBUG_EPHEMERAL) {
13021                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13022                            }
13023                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13024                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13025                                    |PackageManager.INSTALL_INTERNAL);
13026                        } else {
13027                            // Make sure the flag for installing on external
13028                            // media is unset
13029                            installFlags |= PackageManager.INSTALL_INTERNAL;
13030                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13031                        }
13032                    }
13033                }
13034            }
13035
13036            final InstallArgs args = createInstallArgs(this);
13037            mArgs = args;
13038
13039            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13040                // TODO: http://b/22976637
13041                // Apps installed for "all" users use the device owner to verify the app
13042                UserHandle verifierUser = getUser();
13043                if (verifierUser == UserHandle.ALL) {
13044                    verifierUser = UserHandle.SYSTEM;
13045                }
13046
13047                /*
13048                 * Determine if we have any installed package verifiers. If we
13049                 * do, then we'll defer to them to verify the packages.
13050                 */
13051                final int requiredUid = mRequiredVerifierPackage == null ? -1
13052                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13053                                verifierUser.getIdentifier());
13054                if (!origin.existing && requiredUid != -1
13055                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13056                    final Intent verification = new Intent(
13057                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13058                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13059                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13060                            PACKAGE_MIME_TYPE);
13061                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13062
13063                    // Query all live verifiers based on current user state
13064                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13065                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13066
13067                    if (DEBUG_VERIFY) {
13068                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13069                                + verification.toString() + " with " + pkgLite.verifiers.length
13070                                + " optional verifiers");
13071                    }
13072
13073                    final int verificationId = mPendingVerificationToken++;
13074
13075                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13076
13077                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13078                            installerPackageName);
13079
13080                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13081                            installFlags);
13082
13083                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13084                            pkgLite.packageName);
13085
13086                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13087                            pkgLite.versionCode);
13088
13089                    if (verificationInfo != null) {
13090                        if (verificationInfo.originatingUri != null) {
13091                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13092                                    verificationInfo.originatingUri);
13093                        }
13094                        if (verificationInfo.referrer != null) {
13095                            verification.putExtra(Intent.EXTRA_REFERRER,
13096                                    verificationInfo.referrer);
13097                        }
13098                        if (verificationInfo.originatingUid >= 0) {
13099                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13100                                    verificationInfo.originatingUid);
13101                        }
13102                        if (verificationInfo.installerUid >= 0) {
13103                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13104                                    verificationInfo.installerUid);
13105                        }
13106                    }
13107
13108                    final PackageVerificationState verificationState = new PackageVerificationState(
13109                            requiredUid, args);
13110
13111                    mPendingVerification.append(verificationId, verificationState);
13112
13113                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13114                            receivers, verificationState);
13115
13116                    /*
13117                     * If any sufficient verifiers were listed in the package
13118                     * manifest, attempt to ask them.
13119                     */
13120                    if (sufficientVerifiers != null) {
13121                        final int N = sufficientVerifiers.size();
13122                        if (N == 0) {
13123                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13124                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13125                        } else {
13126                            for (int i = 0; i < N; i++) {
13127                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13128
13129                                final Intent sufficientIntent = new Intent(verification);
13130                                sufficientIntent.setComponent(verifierComponent);
13131                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13132                            }
13133                        }
13134                    }
13135
13136                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13137                            mRequiredVerifierPackage, receivers);
13138                    if (ret == PackageManager.INSTALL_SUCCEEDED
13139                            && mRequiredVerifierPackage != null) {
13140                        Trace.asyncTraceBegin(
13141                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13142                        /*
13143                         * Send the intent to the required verification agent,
13144                         * but only start the verification timeout after the
13145                         * target BroadcastReceivers have run.
13146                         */
13147                        verification.setComponent(requiredVerifierComponent);
13148                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13149                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13150                                new BroadcastReceiver() {
13151                                    @Override
13152                                    public void onReceive(Context context, Intent intent) {
13153                                        final Message msg = mHandler
13154                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13155                                        msg.arg1 = verificationId;
13156                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13157                                    }
13158                                }, null, 0, null, null);
13159
13160                        /*
13161                         * We don't want the copy to proceed until verification
13162                         * succeeds, so null out this field.
13163                         */
13164                        mArgs = null;
13165                    }
13166                } else {
13167                    /*
13168                     * No package verification is enabled, so immediately start
13169                     * the remote call to initiate copy using temporary file.
13170                     */
13171                    ret = args.copyApk(mContainerService, true);
13172                }
13173            }
13174
13175            mRet = ret;
13176        }
13177
13178        @Override
13179        void handleReturnCode() {
13180            // If mArgs is null, then MCS couldn't be reached. When it
13181            // reconnects, it will try again to install. At that point, this
13182            // will succeed.
13183            if (mArgs != null) {
13184                processPendingInstall(mArgs, mRet);
13185            }
13186        }
13187
13188        @Override
13189        void handleServiceError() {
13190            mArgs = createInstallArgs(this);
13191            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13192        }
13193
13194        public boolean isForwardLocked() {
13195            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13196        }
13197    }
13198
13199    /**
13200     * Used during creation of InstallArgs
13201     *
13202     * @param installFlags package installation flags
13203     * @return true if should be installed on external storage
13204     */
13205    private static boolean installOnExternalAsec(int installFlags) {
13206        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13207            return false;
13208        }
13209        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13210            return true;
13211        }
13212        return false;
13213    }
13214
13215    /**
13216     * Used during creation of InstallArgs
13217     *
13218     * @param installFlags package installation flags
13219     * @return true if should be installed as forward locked
13220     */
13221    private static boolean installForwardLocked(int installFlags) {
13222        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13223    }
13224
13225    private InstallArgs createInstallArgs(InstallParams params) {
13226        if (params.move != null) {
13227            return new MoveInstallArgs(params);
13228        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13229            return new AsecInstallArgs(params);
13230        } else {
13231            return new FileInstallArgs(params);
13232        }
13233    }
13234
13235    /**
13236     * Create args that describe an existing installed package. Typically used
13237     * when cleaning up old installs, or used as a move source.
13238     */
13239    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13240            String resourcePath, String[] instructionSets) {
13241        final boolean isInAsec;
13242        if (installOnExternalAsec(installFlags)) {
13243            /* Apps on SD card are always in ASEC containers. */
13244            isInAsec = true;
13245        } else if (installForwardLocked(installFlags)
13246                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13247            /*
13248             * Forward-locked apps are only in ASEC containers if they're the
13249             * new style
13250             */
13251            isInAsec = true;
13252        } else {
13253            isInAsec = false;
13254        }
13255
13256        if (isInAsec) {
13257            return new AsecInstallArgs(codePath, instructionSets,
13258                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13259        } else {
13260            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13261        }
13262    }
13263
13264    static abstract class InstallArgs {
13265        /** @see InstallParams#origin */
13266        final OriginInfo origin;
13267        /** @see InstallParams#move */
13268        final MoveInfo move;
13269
13270        final IPackageInstallObserver2 observer;
13271        // Always refers to PackageManager flags only
13272        final int installFlags;
13273        final String installerPackageName;
13274        final String volumeUuid;
13275        final UserHandle user;
13276        final String abiOverride;
13277        final String[] installGrantPermissions;
13278        /** If non-null, drop an async trace when the install completes */
13279        final String traceMethod;
13280        final int traceCookie;
13281        final Certificate[][] certificates;
13282
13283        // The list of instruction sets supported by this app. This is currently
13284        // only used during the rmdex() phase to clean up resources. We can get rid of this
13285        // if we move dex files under the common app path.
13286        /* nullable */ String[] instructionSets;
13287
13288        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13289                int installFlags, String installerPackageName, String volumeUuid,
13290                UserHandle user, String[] instructionSets,
13291                String abiOverride, String[] installGrantPermissions,
13292                String traceMethod, int traceCookie, Certificate[][] certificates) {
13293            this.origin = origin;
13294            this.move = move;
13295            this.installFlags = installFlags;
13296            this.observer = observer;
13297            this.installerPackageName = installerPackageName;
13298            this.volumeUuid = volumeUuid;
13299            this.user = user;
13300            this.instructionSets = instructionSets;
13301            this.abiOverride = abiOverride;
13302            this.installGrantPermissions = installGrantPermissions;
13303            this.traceMethod = traceMethod;
13304            this.traceCookie = traceCookie;
13305            this.certificates = certificates;
13306        }
13307
13308        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13309        abstract int doPreInstall(int status);
13310
13311        /**
13312         * Rename package into final resting place. All paths on the given
13313         * scanned package should be updated to reflect the rename.
13314         */
13315        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13316        abstract int doPostInstall(int status, int uid);
13317
13318        /** @see PackageSettingBase#codePathString */
13319        abstract String getCodePath();
13320        /** @see PackageSettingBase#resourcePathString */
13321        abstract String getResourcePath();
13322
13323        // Need installer lock especially for dex file removal.
13324        abstract void cleanUpResourcesLI();
13325        abstract boolean doPostDeleteLI(boolean delete);
13326
13327        /**
13328         * Called before the source arguments are copied. This is used mostly
13329         * for MoveParams when it needs to read the source file to put it in the
13330         * destination.
13331         */
13332        int doPreCopy() {
13333            return PackageManager.INSTALL_SUCCEEDED;
13334        }
13335
13336        /**
13337         * Called after the source arguments are copied. This is used mostly for
13338         * MoveParams when it needs to read the source file to put it in the
13339         * destination.
13340         */
13341        int doPostCopy(int uid) {
13342            return PackageManager.INSTALL_SUCCEEDED;
13343        }
13344
13345        protected boolean isFwdLocked() {
13346            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13347        }
13348
13349        protected boolean isExternalAsec() {
13350            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13351        }
13352
13353        protected boolean isEphemeral() {
13354            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13355        }
13356
13357        UserHandle getUser() {
13358            return user;
13359        }
13360    }
13361
13362    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13363        if (!allCodePaths.isEmpty()) {
13364            if (instructionSets == null) {
13365                throw new IllegalStateException("instructionSet == null");
13366            }
13367            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13368            for (String codePath : allCodePaths) {
13369                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13370                    try {
13371                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13372                    } catch (InstallerException ignored) {
13373                    }
13374                }
13375            }
13376        }
13377    }
13378
13379    /**
13380     * Logic to handle installation of non-ASEC applications, including copying
13381     * and renaming logic.
13382     */
13383    class FileInstallArgs extends InstallArgs {
13384        private File codeFile;
13385        private File resourceFile;
13386
13387        // Example topology:
13388        // /data/app/com.example/base.apk
13389        // /data/app/com.example/split_foo.apk
13390        // /data/app/com.example/lib/arm/libfoo.so
13391        // /data/app/com.example/lib/arm64/libfoo.so
13392        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13393
13394        /** New install */
13395        FileInstallArgs(InstallParams params) {
13396            super(params.origin, params.move, params.observer, params.installFlags,
13397                    params.installerPackageName, params.volumeUuid,
13398                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13399                    params.grantedRuntimePermissions,
13400                    params.traceMethod, params.traceCookie, params.certificates);
13401            if (isFwdLocked()) {
13402                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13403            }
13404        }
13405
13406        /** Existing install */
13407        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13408            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13409                    null, null, null, 0, null /*certificates*/);
13410            this.codeFile = (codePath != null) ? new File(codePath) : null;
13411            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13412        }
13413
13414        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13415            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13416            try {
13417                return doCopyApk(imcs, temp);
13418            } finally {
13419                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13420            }
13421        }
13422
13423        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13424            if (origin.staged) {
13425                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13426                codeFile = origin.file;
13427                resourceFile = origin.file;
13428                return PackageManager.INSTALL_SUCCEEDED;
13429            }
13430
13431            try {
13432                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13433                final File tempDir =
13434                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13435                codeFile = tempDir;
13436                resourceFile = tempDir;
13437            } catch (IOException e) {
13438                Slog.w(TAG, "Failed to create copy file: " + e);
13439                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13440            }
13441
13442            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13443                @Override
13444                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13445                    if (!FileUtils.isValidExtFilename(name)) {
13446                        throw new IllegalArgumentException("Invalid filename: " + name);
13447                    }
13448                    try {
13449                        final File file = new File(codeFile, name);
13450                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13451                                O_RDWR | O_CREAT, 0644);
13452                        Os.chmod(file.getAbsolutePath(), 0644);
13453                        return new ParcelFileDescriptor(fd);
13454                    } catch (ErrnoException e) {
13455                        throw new RemoteException("Failed to open: " + e.getMessage());
13456                    }
13457                }
13458            };
13459
13460            int ret = PackageManager.INSTALL_SUCCEEDED;
13461            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13462            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13463                Slog.e(TAG, "Failed to copy package");
13464                return ret;
13465            }
13466
13467            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13468            NativeLibraryHelper.Handle handle = null;
13469            try {
13470                handle = NativeLibraryHelper.Handle.create(codeFile);
13471                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13472                        abiOverride);
13473            } catch (IOException e) {
13474                Slog.e(TAG, "Copying native libraries failed", e);
13475                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13476            } finally {
13477                IoUtils.closeQuietly(handle);
13478            }
13479
13480            return ret;
13481        }
13482
13483        int doPreInstall(int status) {
13484            if (status != PackageManager.INSTALL_SUCCEEDED) {
13485                cleanUp();
13486            }
13487            return status;
13488        }
13489
13490        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13491            if (status != PackageManager.INSTALL_SUCCEEDED) {
13492                cleanUp();
13493                return false;
13494            }
13495
13496            final File targetDir = codeFile.getParentFile();
13497            final File beforeCodeFile = codeFile;
13498            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13499
13500            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13501            try {
13502                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13503            } catch (ErrnoException e) {
13504                Slog.w(TAG, "Failed to rename", e);
13505                return false;
13506            }
13507
13508            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13509                Slog.w(TAG, "Failed to restorecon");
13510                return false;
13511            }
13512
13513            // Reflect the rename internally
13514            codeFile = afterCodeFile;
13515            resourceFile = afterCodeFile;
13516
13517            // Reflect the rename in scanned details
13518            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13519            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13520                    afterCodeFile, pkg.baseCodePath));
13521            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13522                    afterCodeFile, pkg.splitCodePaths));
13523
13524            // Reflect the rename in app info
13525            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13526            pkg.setApplicationInfoCodePath(pkg.codePath);
13527            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13528            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13529            pkg.setApplicationInfoResourcePath(pkg.codePath);
13530            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13531            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13532
13533            return true;
13534        }
13535
13536        int doPostInstall(int status, int uid) {
13537            if (status != PackageManager.INSTALL_SUCCEEDED) {
13538                cleanUp();
13539            }
13540            return status;
13541        }
13542
13543        @Override
13544        String getCodePath() {
13545            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13546        }
13547
13548        @Override
13549        String getResourcePath() {
13550            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13551        }
13552
13553        private boolean cleanUp() {
13554            if (codeFile == null || !codeFile.exists()) {
13555                return false;
13556            }
13557
13558            removeCodePathLI(codeFile);
13559
13560            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13561                resourceFile.delete();
13562            }
13563
13564            return true;
13565        }
13566
13567        void cleanUpResourcesLI() {
13568            // Try enumerating all code paths before deleting
13569            List<String> allCodePaths = Collections.EMPTY_LIST;
13570            if (codeFile != null && codeFile.exists()) {
13571                try {
13572                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13573                    allCodePaths = pkg.getAllCodePaths();
13574                } catch (PackageParserException e) {
13575                    // Ignored; we tried our best
13576                }
13577            }
13578
13579            cleanUp();
13580            removeDexFiles(allCodePaths, instructionSets);
13581        }
13582
13583        boolean doPostDeleteLI(boolean delete) {
13584            // XXX err, shouldn't we respect the delete flag?
13585            cleanUpResourcesLI();
13586            return true;
13587        }
13588    }
13589
13590    private boolean isAsecExternal(String cid) {
13591        final String asecPath = PackageHelper.getSdFilesystem(cid);
13592        return !asecPath.startsWith(mAsecInternalPath);
13593    }
13594
13595    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13596            PackageManagerException {
13597        if (copyRet < 0) {
13598            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13599                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13600                throw new PackageManagerException(copyRet, message);
13601            }
13602        }
13603    }
13604
13605    /**
13606     * Extract the MountService "container ID" from the full code path of an
13607     * .apk.
13608     */
13609    static String cidFromCodePath(String fullCodePath) {
13610        int eidx = fullCodePath.lastIndexOf("/");
13611        String subStr1 = fullCodePath.substring(0, eidx);
13612        int sidx = subStr1.lastIndexOf("/");
13613        return subStr1.substring(sidx+1, eidx);
13614    }
13615
13616    /**
13617     * Logic to handle installation of ASEC applications, including copying and
13618     * renaming logic.
13619     */
13620    class AsecInstallArgs extends InstallArgs {
13621        static final String RES_FILE_NAME = "pkg.apk";
13622        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13623
13624        String cid;
13625        String packagePath;
13626        String resourcePath;
13627
13628        /** New install */
13629        AsecInstallArgs(InstallParams params) {
13630            super(params.origin, params.move, params.observer, params.installFlags,
13631                    params.installerPackageName, params.volumeUuid,
13632                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13633                    params.grantedRuntimePermissions,
13634                    params.traceMethod, params.traceCookie, params.certificates);
13635        }
13636
13637        /** Existing install */
13638        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13639                        boolean isExternal, boolean isForwardLocked) {
13640            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13641              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13642                    instructionSets, null, null, null, 0, null /*certificates*/);
13643            // Hackily pretend we're still looking at a full code path
13644            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13645                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13646            }
13647
13648            // Extract cid from fullCodePath
13649            int eidx = fullCodePath.lastIndexOf("/");
13650            String subStr1 = fullCodePath.substring(0, eidx);
13651            int sidx = subStr1.lastIndexOf("/");
13652            cid = subStr1.substring(sidx+1, eidx);
13653            setMountPath(subStr1);
13654        }
13655
13656        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13657            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13658              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13659                    instructionSets, null, null, null, 0, null /*certificates*/);
13660            this.cid = cid;
13661            setMountPath(PackageHelper.getSdDir(cid));
13662        }
13663
13664        void createCopyFile() {
13665            cid = mInstallerService.allocateExternalStageCidLegacy();
13666        }
13667
13668        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13669            if (origin.staged && origin.cid != null) {
13670                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13671                cid = origin.cid;
13672                setMountPath(PackageHelper.getSdDir(cid));
13673                return PackageManager.INSTALL_SUCCEEDED;
13674            }
13675
13676            if (temp) {
13677                createCopyFile();
13678            } else {
13679                /*
13680                 * Pre-emptively destroy the container since it's destroyed if
13681                 * copying fails due to it existing anyway.
13682                 */
13683                PackageHelper.destroySdDir(cid);
13684            }
13685
13686            final String newMountPath = imcs.copyPackageToContainer(
13687                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13688                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13689
13690            if (newMountPath != null) {
13691                setMountPath(newMountPath);
13692                return PackageManager.INSTALL_SUCCEEDED;
13693            } else {
13694                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13695            }
13696        }
13697
13698        @Override
13699        String getCodePath() {
13700            return packagePath;
13701        }
13702
13703        @Override
13704        String getResourcePath() {
13705            return resourcePath;
13706        }
13707
13708        int doPreInstall(int status) {
13709            if (status != PackageManager.INSTALL_SUCCEEDED) {
13710                // Destroy container
13711                PackageHelper.destroySdDir(cid);
13712            } else {
13713                boolean mounted = PackageHelper.isContainerMounted(cid);
13714                if (!mounted) {
13715                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13716                            Process.SYSTEM_UID);
13717                    if (newMountPath != null) {
13718                        setMountPath(newMountPath);
13719                    } else {
13720                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13721                    }
13722                }
13723            }
13724            return status;
13725        }
13726
13727        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13728            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13729            String newMountPath = null;
13730            if (PackageHelper.isContainerMounted(cid)) {
13731                // Unmount the container
13732                if (!PackageHelper.unMountSdDir(cid)) {
13733                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13734                    return false;
13735                }
13736            }
13737            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13738                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13739                        " which might be stale. Will try to clean up.");
13740                // Clean up the stale container and proceed to recreate.
13741                if (!PackageHelper.destroySdDir(newCacheId)) {
13742                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13743                    return false;
13744                }
13745                // Successfully cleaned up stale container. Try to rename again.
13746                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13747                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13748                            + " inspite of cleaning it up.");
13749                    return false;
13750                }
13751            }
13752            if (!PackageHelper.isContainerMounted(newCacheId)) {
13753                Slog.w(TAG, "Mounting container " + newCacheId);
13754                newMountPath = PackageHelper.mountSdDir(newCacheId,
13755                        getEncryptKey(), Process.SYSTEM_UID);
13756            } else {
13757                newMountPath = PackageHelper.getSdDir(newCacheId);
13758            }
13759            if (newMountPath == null) {
13760                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13761                return false;
13762            }
13763            Log.i(TAG, "Succesfully renamed " + cid +
13764                    " to " + newCacheId +
13765                    " at new path: " + newMountPath);
13766            cid = newCacheId;
13767
13768            final File beforeCodeFile = new File(packagePath);
13769            setMountPath(newMountPath);
13770            final File afterCodeFile = new File(packagePath);
13771
13772            // Reflect the rename in scanned details
13773            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13774            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13775                    afterCodeFile, pkg.baseCodePath));
13776            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13777                    afterCodeFile, pkg.splitCodePaths));
13778
13779            // Reflect the rename in app info
13780            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13781            pkg.setApplicationInfoCodePath(pkg.codePath);
13782            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13783            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13784            pkg.setApplicationInfoResourcePath(pkg.codePath);
13785            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13786            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13787
13788            return true;
13789        }
13790
13791        private void setMountPath(String mountPath) {
13792            final File mountFile = new File(mountPath);
13793
13794            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13795            if (monolithicFile.exists()) {
13796                packagePath = monolithicFile.getAbsolutePath();
13797                if (isFwdLocked()) {
13798                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13799                } else {
13800                    resourcePath = packagePath;
13801                }
13802            } else {
13803                packagePath = mountFile.getAbsolutePath();
13804                resourcePath = packagePath;
13805            }
13806        }
13807
13808        int doPostInstall(int status, int uid) {
13809            if (status != PackageManager.INSTALL_SUCCEEDED) {
13810                cleanUp();
13811            } else {
13812                final int groupOwner;
13813                final String protectedFile;
13814                if (isFwdLocked()) {
13815                    groupOwner = UserHandle.getSharedAppGid(uid);
13816                    protectedFile = RES_FILE_NAME;
13817                } else {
13818                    groupOwner = -1;
13819                    protectedFile = null;
13820                }
13821
13822                if (uid < Process.FIRST_APPLICATION_UID
13823                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13824                    Slog.e(TAG, "Failed to finalize " + cid);
13825                    PackageHelper.destroySdDir(cid);
13826                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13827                }
13828
13829                boolean mounted = PackageHelper.isContainerMounted(cid);
13830                if (!mounted) {
13831                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13832                }
13833            }
13834            return status;
13835        }
13836
13837        private void cleanUp() {
13838            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13839
13840            // Destroy secure container
13841            PackageHelper.destroySdDir(cid);
13842        }
13843
13844        private List<String> getAllCodePaths() {
13845            final File codeFile = new File(getCodePath());
13846            if (codeFile != null && codeFile.exists()) {
13847                try {
13848                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13849                    return pkg.getAllCodePaths();
13850                } catch (PackageParserException e) {
13851                    // Ignored; we tried our best
13852                }
13853            }
13854            return Collections.EMPTY_LIST;
13855        }
13856
13857        void cleanUpResourcesLI() {
13858            // Enumerate all code paths before deleting
13859            cleanUpResourcesLI(getAllCodePaths());
13860        }
13861
13862        private void cleanUpResourcesLI(List<String> allCodePaths) {
13863            cleanUp();
13864            removeDexFiles(allCodePaths, instructionSets);
13865        }
13866
13867        String getPackageName() {
13868            return getAsecPackageName(cid);
13869        }
13870
13871        boolean doPostDeleteLI(boolean delete) {
13872            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13873            final List<String> allCodePaths = getAllCodePaths();
13874            boolean mounted = PackageHelper.isContainerMounted(cid);
13875            if (mounted) {
13876                // Unmount first
13877                if (PackageHelper.unMountSdDir(cid)) {
13878                    mounted = false;
13879                }
13880            }
13881            if (!mounted && delete) {
13882                cleanUpResourcesLI(allCodePaths);
13883            }
13884            return !mounted;
13885        }
13886
13887        @Override
13888        int doPreCopy() {
13889            if (isFwdLocked()) {
13890                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13891                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13892                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13893                }
13894            }
13895
13896            return PackageManager.INSTALL_SUCCEEDED;
13897        }
13898
13899        @Override
13900        int doPostCopy(int uid) {
13901            if (isFwdLocked()) {
13902                if (uid < Process.FIRST_APPLICATION_UID
13903                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13904                                RES_FILE_NAME)) {
13905                    Slog.e(TAG, "Failed to finalize " + cid);
13906                    PackageHelper.destroySdDir(cid);
13907                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13908                }
13909            }
13910
13911            return PackageManager.INSTALL_SUCCEEDED;
13912        }
13913    }
13914
13915    /**
13916     * Logic to handle movement of existing installed applications.
13917     */
13918    class MoveInstallArgs extends InstallArgs {
13919        private File codeFile;
13920        private File resourceFile;
13921
13922        /** New install */
13923        MoveInstallArgs(InstallParams params) {
13924            super(params.origin, params.move, params.observer, params.installFlags,
13925                    params.installerPackageName, params.volumeUuid,
13926                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13927                    params.grantedRuntimePermissions,
13928                    params.traceMethod, params.traceCookie, params.certificates);
13929        }
13930
13931        int copyApk(IMediaContainerService imcs, boolean temp) {
13932            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13933                    + move.fromUuid + " to " + move.toUuid);
13934            synchronized (mInstaller) {
13935                try {
13936                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13937                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13938                } catch (InstallerException e) {
13939                    Slog.w(TAG, "Failed to move app", e);
13940                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13941                }
13942            }
13943
13944            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13945            resourceFile = codeFile;
13946            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13947
13948            return PackageManager.INSTALL_SUCCEEDED;
13949        }
13950
13951        int doPreInstall(int status) {
13952            if (status != PackageManager.INSTALL_SUCCEEDED) {
13953                cleanUp(move.toUuid);
13954            }
13955            return status;
13956        }
13957
13958        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13959            if (status != PackageManager.INSTALL_SUCCEEDED) {
13960                cleanUp(move.toUuid);
13961                return false;
13962            }
13963
13964            // Reflect the move in app info
13965            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13966            pkg.setApplicationInfoCodePath(pkg.codePath);
13967            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13968            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13969            pkg.setApplicationInfoResourcePath(pkg.codePath);
13970            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13971            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13972
13973            return true;
13974        }
13975
13976        int doPostInstall(int status, int uid) {
13977            if (status == PackageManager.INSTALL_SUCCEEDED) {
13978                cleanUp(move.fromUuid);
13979            } else {
13980                cleanUp(move.toUuid);
13981            }
13982            return status;
13983        }
13984
13985        @Override
13986        String getCodePath() {
13987            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13988        }
13989
13990        @Override
13991        String getResourcePath() {
13992            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13993        }
13994
13995        private boolean cleanUp(String volumeUuid) {
13996            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13997                    move.dataAppName);
13998            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13999            final int[] userIds = sUserManager.getUserIds();
14000            synchronized (mInstallLock) {
14001                // Clean up both app data and code
14002                // All package moves are frozen until finished
14003                for (int userId : userIds) {
14004                    try {
14005                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14006                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14007                    } catch (InstallerException e) {
14008                        Slog.w(TAG, String.valueOf(e));
14009                    }
14010                }
14011                removeCodePathLI(codeFile);
14012            }
14013            return true;
14014        }
14015
14016        void cleanUpResourcesLI() {
14017            throw new UnsupportedOperationException();
14018        }
14019
14020        boolean doPostDeleteLI(boolean delete) {
14021            throw new UnsupportedOperationException();
14022        }
14023    }
14024
14025    static String getAsecPackageName(String packageCid) {
14026        int idx = packageCid.lastIndexOf("-");
14027        if (idx == -1) {
14028            return packageCid;
14029        }
14030        return packageCid.substring(0, idx);
14031    }
14032
14033    // Utility method used to create code paths based on package name and available index.
14034    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14035        String idxStr = "";
14036        int idx = 1;
14037        // Fall back to default value of idx=1 if prefix is not
14038        // part of oldCodePath
14039        if (oldCodePath != null) {
14040            String subStr = oldCodePath;
14041            // Drop the suffix right away
14042            if (suffix != null && subStr.endsWith(suffix)) {
14043                subStr = subStr.substring(0, subStr.length() - suffix.length());
14044            }
14045            // If oldCodePath already contains prefix find out the
14046            // ending index to either increment or decrement.
14047            int sidx = subStr.lastIndexOf(prefix);
14048            if (sidx != -1) {
14049                subStr = subStr.substring(sidx + prefix.length());
14050                if (subStr != null) {
14051                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14052                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14053                    }
14054                    try {
14055                        idx = Integer.parseInt(subStr);
14056                        if (idx <= 1) {
14057                            idx++;
14058                        } else {
14059                            idx--;
14060                        }
14061                    } catch(NumberFormatException e) {
14062                    }
14063                }
14064            }
14065        }
14066        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14067        return prefix + idxStr;
14068    }
14069
14070    private File getNextCodePath(File targetDir, String packageName) {
14071        int suffix = 1;
14072        File result;
14073        do {
14074            result = new File(targetDir, packageName + "-" + suffix);
14075            suffix++;
14076        } while (result.exists());
14077        return result;
14078    }
14079
14080    // Utility method that returns the relative package path with respect
14081    // to the installation directory. Like say for /data/data/com.test-1.apk
14082    // string com.test-1 is returned.
14083    static String deriveCodePathName(String codePath) {
14084        if (codePath == null) {
14085            return null;
14086        }
14087        final File codeFile = new File(codePath);
14088        final String name = codeFile.getName();
14089        if (codeFile.isDirectory()) {
14090            return name;
14091        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14092            final int lastDot = name.lastIndexOf('.');
14093            return name.substring(0, lastDot);
14094        } else {
14095            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14096            return null;
14097        }
14098    }
14099
14100    static class PackageInstalledInfo {
14101        String name;
14102        int uid;
14103        // The set of users that originally had this package installed.
14104        int[] origUsers;
14105        // The set of users that now have this package installed.
14106        int[] newUsers;
14107        PackageParser.Package pkg;
14108        int returnCode;
14109        String returnMsg;
14110        PackageRemovedInfo removedInfo;
14111        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14112
14113        public void setError(int code, String msg) {
14114            setReturnCode(code);
14115            setReturnMessage(msg);
14116            Slog.w(TAG, msg);
14117        }
14118
14119        public void setError(String msg, PackageParserException e) {
14120            setReturnCode(e.error);
14121            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14122            Slog.w(TAG, msg, e);
14123        }
14124
14125        public void setError(String msg, PackageManagerException e) {
14126            returnCode = e.error;
14127            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14128            Slog.w(TAG, msg, e);
14129        }
14130
14131        public void setReturnCode(int returnCode) {
14132            this.returnCode = returnCode;
14133            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14134            for (int i = 0; i < childCount; i++) {
14135                addedChildPackages.valueAt(i).returnCode = returnCode;
14136            }
14137        }
14138
14139        private void setReturnMessage(String returnMsg) {
14140            this.returnMsg = returnMsg;
14141            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14142            for (int i = 0; i < childCount; i++) {
14143                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14144            }
14145        }
14146
14147        // In some error cases we want to convey more info back to the observer
14148        String origPackage;
14149        String origPermission;
14150    }
14151
14152    /*
14153     * Install a non-existing package.
14154     */
14155    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14156            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14157            PackageInstalledInfo res) {
14158        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14159
14160        // Remember this for later, in case we need to rollback this install
14161        String pkgName = pkg.packageName;
14162
14163        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14164
14165        synchronized(mPackages) {
14166            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14167                // A package with the same name is already installed, though
14168                // it has been renamed to an older name.  The package we
14169                // are trying to install should be installed as an update to
14170                // the existing one, but that has not been requested, so bail.
14171                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14172                        + " without first uninstalling package running as "
14173                        + mSettings.mRenamedPackages.get(pkgName));
14174                return;
14175            }
14176            if (mPackages.containsKey(pkgName)) {
14177                // Don't allow installation over an existing package with the same name.
14178                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14179                        + " without first uninstalling.");
14180                return;
14181            }
14182        }
14183
14184        try {
14185            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14186                    System.currentTimeMillis(), user);
14187
14188            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14189
14190            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14191                prepareAppDataAfterInstallLIF(newPackage);
14192
14193            } else {
14194                // Remove package from internal structures, but keep around any
14195                // data that might have already existed
14196                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14197                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14198            }
14199        } catch (PackageManagerException e) {
14200            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14201        }
14202
14203        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14204    }
14205
14206    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14207        // Can't rotate keys during boot or if sharedUser.
14208        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14209                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14210            return false;
14211        }
14212        // app is using upgradeKeySets; make sure all are valid
14213        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14214        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14215        for (int i = 0; i < upgradeKeySets.length; i++) {
14216            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14217                Slog.wtf(TAG, "Package "
14218                         + (oldPs.name != null ? oldPs.name : "<null>")
14219                         + " contains upgrade-key-set reference to unknown key-set: "
14220                         + upgradeKeySets[i]
14221                         + " reverting to signatures check.");
14222                return false;
14223            }
14224        }
14225        return true;
14226    }
14227
14228    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14229        // Upgrade keysets are being used.  Determine if new package has a superset of the
14230        // required keys.
14231        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14232        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14233        for (int i = 0; i < upgradeKeySets.length; i++) {
14234            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14235            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14236                return true;
14237            }
14238        }
14239        return false;
14240    }
14241
14242    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14243        try (DigestInputStream digestStream =
14244                new DigestInputStream(new FileInputStream(file), digest)) {
14245            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14246        }
14247    }
14248
14249    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14250            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14251        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14252
14253        final PackageParser.Package oldPackage;
14254        final String pkgName = pkg.packageName;
14255        final int[] allUsers;
14256        final int[] installedUsers;
14257
14258        synchronized(mPackages) {
14259            oldPackage = mPackages.get(pkgName);
14260            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14261
14262            // don't allow upgrade to target a release SDK from a pre-release SDK
14263            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14264                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14265            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14266                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14267            if (oldTargetsPreRelease
14268                    && !newTargetsPreRelease
14269                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14270                Slog.w(TAG, "Can't install package targeting released sdk");
14271                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14272                return;
14273            }
14274
14275            // don't allow an upgrade from full to ephemeral
14276            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14277            if (isEphemeral && !oldIsEphemeral) {
14278                // can't downgrade from full to ephemeral
14279                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14280                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14281                return;
14282            }
14283
14284            // verify signatures are valid
14285            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14286            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14287                if (!checkUpgradeKeySetLP(ps, pkg)) {
14288                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14289                            "New package not signed by keys specified by upgrade-keysets: "
14290                                    + pkgName);
14291                    return;
14292                }
14293            } else {
14294                // default to original signature matching
14295                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14296                        != PackageManager.SIGNATURE_MATCH) {
14297                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14298                            "New package has a different signature: " + pkgName);
14299                    return;
14300                }
14301            }
14302
14303            // don't allow a system upgrade unless the upgrade hash matches
14304            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14305                byte[] digestBytes = null;
14306                try {
14307                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14308                    updateDigest(digest, new File(pkg.baseCodePath));
14309                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14310                        for (String path : pkg.splitCodePaths) {
14311                            updateDigest(digest, new File(path));
14312                        }
14313                    }
14314                    digestBytes = digest.digest();
14315                } catch (NoSuchAlgorithmException | IOException e) {
14316                    res.setError(INSTALL_FAILED_INVALID_APK,
14317                            "Could not compute hash: " + pkgName);
14318                    return;
14319                }
14320                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14321                    res.setError(INSTALL_FAILED_INVALID_APK,
14322                            "New package fails restrict-update check: " + pkgName);
14323                    return;
14324                }
14325                // retain upgrade restriction
14326                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14327            }
14328
14329            // Check for shared user id changes
14330            String invalidPackageName =
14331                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14332            if (invalidPackageName != null) {
14333                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14334                        "Package " + invalidPackageName + " tried to change user "
14335                                + oldPackage.mSharedUserId);
14336                return;
14337            }
14338
14339            // In case of rollback, remember per-user/profile install state
14340            allUsers = sUserManager.getUserIds();
14341            installedUsers = ps.queryInstalledUsers(allUsers, true);
14342        }
14343
14344        // Update what is removed
14345        res.removedInfo = new PackageRemovedInfo();
14346        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14347        res.removedInfo.removedPackage = oldPackage.packageName;
14348        res.removedInfo.isUpdate = true;
14349        res.removedInfo.origUsers = installedUsers;
14350        final int childCount = (oldPackage.childPackages != null)
14351                ? oldPackage.childPackages.size() : 0;
14352        for (int i = 0; i < childCount; i++) {
14353            boolean childPackageUpdated = false;
14354            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14355            if (res.addedChildPackages != null) {
14356                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14357                if (childRes != null) {
14358                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14359                    childRes.removedInfo.removedPackage = childPkg.packageName;
14360                    childRes.removedInfo.isUpdate = true;
14361                    childPackageUpdated = true;
14362                }
14363            }
14364            if (!childPackageUpdated) {
14365                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14366                childRemovedRes.removedPackage = childPkg.packageName;
14367                childRemovedRes.isUpdate = false;
14368                childRemovedRes.dataRemoved = true;
14369                synchronized (mPackages) {
14370                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14371                    if (childPs != null) {
14372                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14373                    }
14374                }
14375                if (res.removedInfo.removedChildPackages == null) {
14376                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14377                }
14378                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14379            }
14380        }
14381
14382        boolean sysPkg = (isSystemApp(oldPackage));
14383        if (sysPkg) {
14384            // Set the system/privileged flags as needed
14385            final boolean privileged =
14386                    (oldPackage.applicationInfo.privateFlags
14387                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14388            final int systemPolicyFlags = policyFlags
14389                    | PackageParser.PARSE_IS_SYSTEM
14390                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14391
14392            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14393                    user, allUsers, installerPackageName, res);
14394        } else {
14395            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14396                    user, allUsers, installerPackageName, res);
14397        }
14398    }
14399
14400    public List<String> getPreviousCodePaths(String packageName) {
14401        final PackageSetting ps = mSettings.mPackages.get(packageName);
14402        final List<String> result = new ArrayList<String>();
14403        if (ps != null && ps.oldCodePaths != null) {
14404            result.addAll(ps.oldCodePaths);
14405        }
14406        return result;
14407    }
14408
14409    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14410            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14411            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14412        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14413                + deletedPackage);
14414
14415        String pkgName = deletedPackage.packageName;
14416        boolean deletedPkg = true;
14417        boolean addedPkg = false;
14418        boolean updatedSettings = false;
14419        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14420        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14421                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14422
14423        final long origUpdateTime = (pkg.mExtras != null)
14424                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14425
14426        // First delete the existing package while retaining the data directory
14427        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14428                res.removedInfo, true, pkg)) {
14429            // If the existing package wasn't successfully deleted
14430            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14431            deletedPkg = false;
14432        } else {
14433            // Successfully deleted the old package; proceed with replace.
14434
14435            // If deleted package lived in a container, give users a chance to
14436            // relinquish resources before killing.
14437            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14438                if (DEBUG_INSTALL) {
14439                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14440                }
14441                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14442                final ArrayList<String> pkgList = new ArrayList<String>(1);
14443                pkgList.add(deletedPackage.applicationInfo.packageName);
14444                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14445            }
14446
14447            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14448                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14449            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14450
14451            try {
14452                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14453                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14454                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14455
14456                // Update the in-memory copy of the previous code paths.
14457                PackageSetting ps = mSettings.mPackages.get(pkgName);
14458                if (!killApp) {
14459                    if (ps.oldCodePaths == null) {
14460                        ps.oldCodePaths = new ArraySet<>();
14461                    }
14462                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14463                    if (deletedPackage.splitCodePaths != null) {
14464                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14465                    }
14466                } else {
14467                    ps.oldCodePaths = null;
14468                }
14469                if (ps.childPackageNames != null) {
14470                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14471                        final String childPkgName = ps.childPackageNames.get(i);
14472                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14473                        childPs.oldCodePaths = ps.oldCodePaths;
14474                    }
14475                }
14476                prepareAppDataAfterInstallLIF(newPackage);
14477                addedPkg = true;
14478            } catch (PackageManagerException e) {
14479                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14480            }
14481        }
14482
14483        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14484            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14485
14486            // Revert all internal state mutations and added folders for the failed install
14487            if (addedPkg) {
14488                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14489                        res.removedInfo, true, null);
14490            }
14491
14492            // Restore the old package
14493            if (deletedPkg) {
14494                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14495                File restoreFile = new File(deletedPackage.codePath);
14496                // Parse old package
14497                boolean oldExternal = isExternal(deletedPackage);
14498                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14499                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14500                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14501                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14502                try {
14503                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14504                            null);
14505                } catch (PackageManagerException e) {
14506                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14507                            + e.getMessage());
14508                    return;
14509                }
14510
14511                synchronized (mPackages) {
14512                    // Ensure the installer package name up to date
14513                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14514
14515                    // Update permissions for restored package
14516                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14517
14518                    mSettings.writeLPr();
14519                }
14520
14521                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14522            }
14523        } else {
14524            synchronized (mPackages) {
14525                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14526                if (ps != null) {
14527                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14528                    if (res.removedInfo.removedChildPackages != null) {
14529                        final int childCount = res.removedInfo.removedChildPackages.size();
14530                        // Iterate in reverse as we may modify the collection
14531                        for (int i = childCount - 1; i >= 0; i--) {
14532                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14533                            if (res.addedChildPackages.containsKey(childPackageName)) {
14534                                res.removedInfo.removedChildPackages.removeAt(i);
14535                            } else {
14536                                PackageRemovedInfo childInfo = res.removedInfo
14537                                        .removedChildPackages.valueAt(i);
14538                                childInfo.removedForAllUsers = mPackages.get(
14539                                        childInfo.removedPackage) == null;
14540                            }
14541                        }
14542                    }
14543                }
14544            }
14545        }
14546    }
14547
14548    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14549            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14550            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14551        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14552                + ", old=" + deletedPackage);
14553
14554        final boolean disabledSystem;
14555
14556        // Remove existing system package
14557        removePackageLI(deletedPackage, true);
14558
14559        synchronized (mPackages) {
14560            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14561        }
14562        if (!disabledSystem) {
14563            // We didn't need to disable the .apk as a current system package,
14564            // which means we are replacing another update that is already
14565            // installed.  We need to make sure to delete the older one's .apk.
14566            res.removedInfo.args = createInstallArgsForExisting(0,
14567                    deletedPackage.applicationInfo.getCodePath(),
14568                    deletedPackage.applicationInfo.getResourcePath(),
14569                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14570        } else {
14571            res.removedInfo.args = null;
14572        }
14573
14574        // Successfully disabled the old package. Now proceed with re-installation
14575        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14576                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14577        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14578
14579        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14580        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14581                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14582
14583        PackageParser.Package newPackage = null;
14584        try {
14585            // Add the package to the internal data structures
14586            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14587
14588            // Set the update and install times
14589            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14590            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14591                    System.currentTimeMillis());
14592
14593            // Update the package dynamic state if succeeded
14594            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14595                // Now that the install succeeded make sure we remove data
14596                // directories for any child package the update removed.
14597                final int deletedChildCount = (deletedPackage.childPackages != null)
14598                        ? deletedPackage.childPackages.size() : 0;
14599                final int newChildCount = (newPackage.childPackages != null)
14600                        ? newPackage.childPackages.size() : 0;
14601                for (int i = 0; i < deletedChildCount; i++) {
14602                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14603                    boolean childPackageDeleted = true;
14604                    for (int j = 0; j < newChildCount; j++) {
14605                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14606                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14607                            childPackageDeleted = false;
14608                            break;
14609                        }
14610                    }
14611                    if (childPackageDeleted) {
14612                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14613                                deletedChildPkg.packageName);
14614                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14615                            PackageRemovedInfo removedChildRes = res.removedInfo
14616                                    .removedChildPackages.get(deletedChildPkg.packageName);
14617                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14618                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14619                        }
14620                    }
14621                }
14622
14623                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14624                prepareAppDataAfterInstallLIF(newPackage);
14625            }
14626        } catch (PackageManagerException e) {
14627            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14628            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14629        }
14630
14631        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14632            // Re installation failed. Restore old information
14633            // Remove new pkg information
14634            if (newPackage != null) {
14635                removeInstalledPackageLI(newPackage, true);
14636            }
14637            // Add back the old system package
14638            try {
14639                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14640            } catch (PackageManagerException e) {
14641                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14642            }
14643
14644            synchronized (mPackages) {
14645                if (disabledSystem) {
14646                    enableSystemPackageLPw(deletedPackage);
14647                }
14648
14649                // Ensure the installer package name up to date
14650                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14651
14652                // Update permissions for restored package
14653                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14654
14655                mSettings.writeLPr();
14656            }
14657
14658            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14659                    + " after failed upgrade");
14660        }
14661    }
14662
14663    /**
14664     * Checks whether the parent or any of the child packages have a change shared
14665     * user. For a package to be a valid update the shred users of the parent and
14666     * the children should match. We may later support changing child shared users.
14667     * @param oldPkg The updated package.
14668     * @param newPkg The update package.
14669     * @return The shared user that change between the versions.
14670     */
14671    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14672            PackageParser.Package newPkg) {
14673        // Check parent shared user
14674        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14675            return newPkg.packageName;
14676        }
14677        // Check child shared users
14678        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14679        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14680        for (int i = 0; i < newChildCount; i++) {
14681            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14682            // If this child was present, did it have the same shared user?
14683            for (int j = 0; j < oldChildCount; j++) {
14684                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14685                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14686                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14687                    return newChildPkg.packageName;
14688                }
14689            }
14690        }
14691        return null;
14692    }
14693
14694    private void removeNativeBinariesLI(PackageSetting ps) {
14695        // Remove the lib path for the parent package
14696        if (ps != null) {
14697            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14698            // Remove the lib path for the child packages
14699            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14700            for (int i = 0; i < childCount; i++) {
14701                PackageSetting childPs = null;
14702                synchronized (mPackages) {
14703                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14704                }
14705                if (childPs != null) {
14706                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14707                            .legacyNativeLibraryPathString);
14708                }
14709            }
14710        }
14711    }
14712
14713    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14714        // Enable the parent package
14715        mSettings.enableSystemPackageLPw(pkg.packageName);
14716        // Enable the child packages
14717        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14718        for (int i = 0; i < childCount; i++) {
14719            PackageParser.Package childPkg = pkg.childPackages.get(i);
14720            mSettings.enableSystemPackageLPw(childPkg.packageName);
14721        }
14722    }
14723
14724    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14725            PackageParser.Package newPkg) {
14726        // Disable the parent package (parent always replaced)
14727        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14728        // Disable the child packages
14729        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14730        for (int i = 0; i < childCount; i++) {
14731            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14732            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14733            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14734        }
14735        return disabled;
14736    }
14737
14738    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14739            String installerPackageName) {
14740        // Enable the parent package
14741        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14742        // Enable the child packages
14743        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14744        for (int i = 0; i < childCount; i++) {
14745            PackageParser.Package childPkg = pkg.childPackages.get(i);
14746            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14747        }
14748    }
14749
14750    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14751        // Collect all used permissions in the UID
14752        ArraySet<String> usedPermissions = new ArraySet<>();
14753        final int packageCount = su.packages.size();
14754        for (int i = 0; i < packageCount; i++) {
14755            PackageSetting ps = su.packages.valueAt(i);
14756            if (ps.pkg == null) {
14757                continue;
14758            }
14759            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14760            for (int j = 0; j < requestedPermCount; j++) {
14761                String permission = ps.pkg.requestedPermissions.get(j);
14762                BasePermission bp = mSettings.mPermissions.get(permission);
14763                if (bp != null) {
14764                    usedPermissions.add(permission);
14765                }
14766            }
14767        }
14768
14769        PermissionsState permissionsState = su.getPermissionsState();
14770        // Prune install permissions
14771        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14772        final int installPermCount = installPermStates.size();
14773        for (int i = installPermCount - 1; i >= 0;  i--) {
14774            PermissionState permissionState = installPermStates.get(i);
14775            if (!usedPermissions.contains(permissionState.getName())) {
14776                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14777                if (bp != null) {
14778                    permissionsState.revokeInstallPermission(bp);
14779                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14780                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14781                }
14782            }
14783        }
14784
14785        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14786
14787        // Prune runtime permissions
14788        for (int userId : allUserIds) {
14789            List<PermissionState> runtimePermStates = permissionsState
14790                    .getRuntimePermissionStates(userId);
14791            final int runtimePermCount = runtimePermStates.size();
14792            for (int i = runtimePermCount - 1; i >= 0; i--) {
14793                PermissionState permissionState = runtimePermStates.get(i);
14794                if (!usedPermissions.contains(permissionState.getName())) {
14795                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14796                    if (bp != null) {
14797                        permissionsState.revokeRuntimePermission(bp, userId);
14798                        permissionsState.updatePermissionFlags(bp, userId,
14799                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14800                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14801                                runtimePermissionChangedUserIds, userId);
14802                    }
14803                }
14804            }
14805        }
14806
14807        return runtimePermissionChangedUserIds;
14808    }
14809
14810    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14811            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14812        // Update the parent package setting
14813        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14814                res, user);
14815        // Update the child packages setting
14816        final int childCount = (newPackage.childPackages != null)
14817                ? newPackage.childPackages.size() : 0;
14818        for (int i = 0; i < childCount; i++) {
14819            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14820            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14821            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14822                    childRes.origUsers, childRes, user);
14823        }
14824    }
14825
14826    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14827            String installerPackageName, int[] allUsers, int[] installedForUsers,
14828            PackageInstalledInfo res, UserHandle user) {
14829        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14830
14831        String pkgName = newPackage.packageName;
14832        synchronized (mPackages) {
14833            //write settings. the installStatus will be incomplete at this stage.
14834            //note that the new package setting would have already been
14835            //added to mPackages. It hasn't been persisted yet.
14836            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14837            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14838            mSettings.writeLPr();
14839            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14840        }
14841
14842        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14843        synchronized (mPackages) {
14844            updatePermissionsLPw(newPackage.packageName, newPackage,
14845                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14846                            ? UPDATE_PERMISSIONS_ALL : 0));
14847            // For system-bundled packages, we assume that installing an upgraded version
14848            // of the package implies that the user actually wants to run that new code,
14849            // so we enable the package.
14850            PackageSetting ps = mSettings.mPackages.get(pkgName);
14851            final int userId = user.getIdentifier();
14852            if (ps != null) {
14853                if (isSystemApp(newPackage)) {
14854                    if (DEBUG_INSTALL) {
14855                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14856                    }
14857                    // Enable system package for requested users
14858                    if (res.origUsers != null) {
14859                        for (int origUserId : res.origUsers) {
14860                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14861                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14862                                        origUserId, installerPackageName);
14863                            }
14864                        }
14865                    }
14866                    // Also convey the prior install/uninstall state
14867                    if (allUsers != null && installedForUsers != null) {
14868                        for (int currentUserId : allUsers) {
14869                            final boolean installed = ArrayUtils.contains(
14870                                    installedForUsers, currentUserId);
14871                            if (DEBUG_INSTALL) {
14872                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14873                            }
14874                            ps.setInstalled(installed, currentUserId);
14875                        }
14876                        // these install state changes will be persisted in the
14877                        // upcoming call to mSettings.writeLPr().
14878                    }
14879                }
14880                // It's implied that when a user requests installation, they want the app to be
14881                // installed and enabled.
14882                if (userId != UserHandle.USER_ALL) {
14883                    ps.setInstalled(true, userId);
14884                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14885                }
14886            }
14887            res.name = pkgName;
14888            res.uid = newPackage.applicationInfo.uid;
14889            res.pkg = newPackage;
14890            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14891            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14892            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14893            //to update install status
14894            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14895            mSettings.writeLPr();
14896            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14897        }
14898
14899        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14900    }
14901
14902    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14903        try {
14904            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14905            installPackageLI(args, res);
14906        } finally {
14907            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14908        }
14909    }
14910
14911    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14912        final int installFlags = args.installFlags;
14913        final String installerPackageName = args.installerPackageName;
14914        final String volumeUuid = args.volumeUuid;
14915        final File tmpPackageFile = new File(args.getCodePath());
14916        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14917        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14918                || (args.volumeUuid != null));
14919        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14920        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14921        boolean replace = false;
14922        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14923        if (args.move != null) {
14924            // moving a complete application; perform an initial scan on the new install location
14925            scanFlags |= SCAN_INITIAL;
14926        }
14927        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14928            scanFlags |= SCAN_DONT_KILL_APP;
14929        }
14930
14931        // Result object to be returned
14932        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14933
14934        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14935
14936        // Sanity check
14937        if (ephemeral && (forwardLocked || onExternal)) {
14938            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14939                    + " external=" + onExternal);
14940            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14941            return;
14942        }
14943
14944        // Retrieve PackageSettings and parse package
14945        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14946                | PackageParser.PARSE_ENFORCE_CODE
14947                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14948                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14949                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14950                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14951        PackageParser pp = new PackageParser();
14952        pp.setSeparateProcesses(mSeparateProcesses);
14953        pp.setDisplayMetrics(mMetrics);
14954
14955        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14956        final PackageParser.Package pkg;
14957        try {
14958            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14959        } catch (PackageParserException e) {
14960            res.setError("Failed parse during installPackageLI", e);
14961            return;
14962        } finally {
14963            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14964        }
14965
14966        // If we are installing a clustered package add results for the children
14967        if (pkg.childPackages != null) {
14968            synchronized (mPackages) {
14969                final int childCount = pkg.childPackages.size();
14970                for (int i = 0; i < childCount; i++) {
14971                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14972                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14973                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14974                    childRes.pkg = childPkg;
14975                    childRes.name = childPkg.packageName;
14976                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14977                    if (childPs != null) {
14978                        childRes.origUsers = childPs.queryInstalledUsers(
14979                                sUserManager.getUserIds(), true);
14980                    }
14981                    if ((mPackages.containsKey(childPkg.packageName))) {
14982                        childRes.removedInfo = new PackageRemovedInfo();
14983                        childRes.removedInfo.removedPackage = childPkg.packageName;
14984                    }
14985                    if (res.addedChildPackages == null) {
14986                        res.addedChildPackages = new ArrayMap<>();
14987                    }
14988                    res.addedChildPackages.put(childPkg.packageName, childRes);
14989                }
14990            }
14991        }
14992
14993        // If package doesn't declare API override, mark that we have an install
14994        // time CPU ABI override.
14995        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14996            pkg.cpuAbiOverride = args.abiOverride;
14997        }
14998
14999        String pkgName = res.name = pkg.packageName;
15000        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15001            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15002                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15003                return;
15004            }
15005        }
15006
15007        try {
15008            // either use what we've been given or parse directly from the APK
15009            if (args.certificates != null) {
15010                try {
15011                    PackageParser.populateCertificates(pkg, args.certificates);
15012                } catch (PackageParserException e) {
15013                    // there was something wrong with the certificates we were given;
15014                    // try to pull them from the APK
15015                    PackageParser.collectCertificates(pkg, parseFlags);
15016                }
15017            } else {
15018                PackageParser.collectCertificates(pkg, parseFlags);
15019            }
15020        } catch (PackageParserException e) {
15021            res.setError("Failed collect during installPackageLI", e);
15022            return;
15023        }
15024
15025        // Get rid of all references to package scan path via parser.
15026        pp = null;
15027        String oldCodePath = null;
15028        boolean systemApp = false;
15029        synchronized (mPackages) {
15030            // Check if installing already existing package
15031            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15032                String oldName = mSettings.mRenamedPackages.get(pkgName);
15033                if (pkg.mOriginalPackages != null
15034                        && pkg.mOriginalPackages.contains(oldName)
15035                        && mPackages.containsKey(oldName)) {
15036                    // This package is derived from an original package,
15037                    // and this device has been updating from that original
15038                    // name.  We must continue using the original name, so
15039                    // rename the new package here.
15040                    pkg.setPackageName(oldName);
15041                    pkgName = pkg.packageName;
15042                    replace = true;
15043                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15044                            + oldName + " pkgName=" + pkgName);
15045                } else if (mPackages.containsKey(pkgName)) {
15046                    // This package, under its official name, already exists
15047                    // on the device; we should replace it.
15048                    replace = true;
15049                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15050                }
15051
15052                // Child packages are installed through the parent package
15053                if (pkg.parentPackage != null) {
15054                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15055                            "Package " + pkg.packageName + " is child of package "
15056                                    + pkg.parentPackage.parentPackage + ". Child packages "
15057                                    + "can be updated only through the parent package.");
15058                    return;
15059                }
15060
15061                if (replace) {
15062                    // Prevent apps opting out from runtime permissions
15063                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15064                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15065                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15066                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15067                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15068                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15069                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15070                                        + " doesn't support runtime permissions but the old"
15071                                        + " target SDK " + oldTargetSdk + " does.");
15072                        return;
15073                    }
15074
15075                    // Prevent installing of child packages
15076                    if (oldPackage.parentPackage != null) {
15077                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15078                                "Package " + pkg.packageName + " is child of package "
15079                                        + oldPackage.parentPackage + ". Child packages "
15080                                        + "can be updated only through the parent package.");
15081                        return;
15082                    }
15083                }
15084            }
15085
15086            PackageSetting ps = mSettings.mPackages.get(pkgName);
15087            if (ps != null) {
15088                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15089
15090                // Quick sanity check that we're signed correctly if updating;
15091                // we'll check this again later when scanning, but we want to
15092                // bail early here before tripping over redefined permissions.
15093                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15094                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15095                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15096                                + pkg.packageName + " upgrade keys do not match the "
15097                                + "previously installed version");
15098                        return;
15099                    }
15100                } else {
15101                    try {
15102                        verifySignaturesLP(ps, pkg);
15103                    } catch (PackageManagerException e) {
15104                        res.setError(e.error, e.getMessage());
15105                        return;
15106                    }
15107                }
15108
15109                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15110                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15111                    systemApp = (ps.pkg.applicationInfo.flags &
15112                            ApplicationInfo.FLAG_SYSTEM) != 0;
15113                }
15114                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15115            }
15116
15117            // Check whether the newly-scanned package wants to define an already-defined perm
15118            int N = pkg.permissions.size();
15119            for (int i = N-1; i >= 0; i--) {
15120                PackageParser.Permission perm = pkg.permissions.get(i);
15121                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15122                if (bp != null) {
15123                    // If the defining package is signed with our cert, it's okay.  This
15124                    // also includes the "updating the same package" case, of course.
15125                    // "updating same package" could also involve key-rotation.
15126                    final boolean sigsOk;
15127                    if (bp.sourcePackage.equals(pkg.packageName)
15128                            && (bp.packageSetting instanceof PackageSetting)
15129                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15130                                    scanFlags))) {
15131                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15132                    } else {
15133                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15134                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15135                    }
15136                    if (!sigsOk) {
15137                        // If the owning package is the system itself, we log but allow
15138                        // install to proceed; we fail the install on all other permission
15139                        // redefinitions.
15140                        if (!bp.sourcePackage.equals("android")) {
15141                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15142                                    + pkg.packageName + " attempting to redeclare permission "
15143                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15144                            res.origPermission = perm.info.name;
15145                            res.origPackage = bp.sourcePackage;
15146                            return;
15147                        } else {
15148                            Slog.w(TAG, "Package " + pkg.packageName
15149                                    + " attempting to redeclare system permission "
15150                                    + perm.info.name + "; ignoring new declaration");
15151                            pkg.permissions.remove(i);
15152                        }
15153                    }
15154                }
15155            }
15156        }
15157
15158        if (systemApp) {
15159            if (onExternal) {
15160                // Abort update; system app can't be replaced with app on sdcard
15161                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15162                        "Cannot install updates to system apps on sdcard");
15163                return;
15164            } else if (ephemeral) {
15165                // Abort update; system app can't be replaced with an ephemeral app
15166                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15167                        "Cannot update a system app with an ephemeral app");
15168                return;
15169            }
15170        }
15171
15172        if (args.move != null) {
15173            // We did an in-place move, so dex is ready to roll
15174            scanFlags |= SCAN_NO_DEX;
15175            scanFlags |= SCAN_MOVE;
15176
15177            synchronized (mPackages) {
15178                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15179                if (ps == null) {
15180                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15181                            "Missing settings for moved package " + pkgName);
15182                }
15183
15184                // We moved the entire application as-is, so bring over the
15185                // previously derived ABI information.
15186                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15187                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15188            }
15189
15190        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15191            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15192            scanFlags |= SCAN_NO_DEX;
15193
15194            try {
15195                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15196                    args.abiOverride : pkg.cpuAbiOverride);
15197                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15198                        true /* extract libs */);
15199            } catch (PackageManagerException pme) {
15200                Slog.e(TAG, "Error deriving application ABI", pme);
15201                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15202                return;
15203            }
15204
15205            // Shared libraries for the package need to be updated.
15206            synchronized (mPackages) {
15207                try {
15208                    updateSharedLibrariesLPw(pkg, null);
15209                } catch (PackageManagerException e) {
15210                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15211                }
15212            }
15213            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15214            // Do not run PackageDexOptimizer through the local performDexOpt
15215            // method because `pkg` may not be in `mPackages` yet.
15216            //
15217            // Also, don't fail application installs if the dexopt step fails.
15218            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15219                    null /* instructionSets */, false /* checkProfiles */,
15220                    getCompilerFilterForReason(REASON_INSTALL));
15221            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15222
15223            // Notify BackgroundDexOptService that the package has been changed.
15224            // If this is an update of a package which used to fail to compile,
15225            // BDOS will remove it from its blacklist.
15226            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15227        }
15228
15229        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15230            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15231            return;
15232        }
15233
15234        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15235
15236        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15237                "installPackageLI")) {
15238            if (replace) {
15239                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15240                        installerPackageName, res);
15241            } else {
15242                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15243                        args.user, installerPackageName, volumeUuid, res);
15244            }
15245        }
15246        synchronized (mPackages) {
15247            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15248            if (ps != null) {
15249                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15250            }
15251
15252            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15253            for (int i = 0; i < childCount; i++) {
15254                PackageParser.Package childPkg = pkg.childPackages.get(i);
15255                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15256                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15257                if (childPs != null) {
15258                    childRes.newUsers = childPs.queryInstalledUsers(
15259                            sUserManager.getUserIds(), true);
15260                }
15261            }
15262        }
15263    }
15264
15265    private void startIntentFilterVerifications(int userId, boolean replacing,
15266            PackageParser.Package pkg) {
15267        if (mIntentFilterVerifierComponent == null) {
15268            Slog.w(TAG, "No IntentFilter verification will not be done as "
15269                    + "there is no IntentFilterVerifier available!");
15270            return;
15271        }
15272
15273        final int verifierUid = getPackageUid(
15274                mIntentFilterVerifierComponent.getPackageName(),
15275                MATCH_DEBUG_TRIAGED_MISSING,
15276                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15277
15278        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15279        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15280        mHandler.sendMessage(msg);
15281
15282        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15283        for (int i = 0; i < childCount; i++) {
15284            PackageParser.Package childPkg = pkg.childPackages.get(i);
15285            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15286            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15287            mHandler.sendMessage(msg);
15288        }
15289    }
15290
15291    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15292            PackageParser.Package pkg) {
15293        int size = pkg.activities.size();
15294        if (size == 0) {
15295            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15296                    "No activity, so no need to verify any IntentFilter!");
15297            return;
15298        }
15299
15300        final boolean hasDomainURLs = hasDomainURLs(pkg);
15301        if (!hasDomainURLs) {
15302            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15303                    "No domain URLs, so no need to verify any IntentFilter!");
15304            return;
15305        }
15306
15307        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15308                + " if any IntentFilter from the " + size
15309                + " Activities needs verification ...");
15310
15311        int count = 0;
15312        final String packageName = pkg.packageName;
15313
15314        synchronized (mPackages) {
15315            // If this is a new install and we see that we've already run verification for this
15316            // package, we have nothing to do: it means the state was restored from backup.
15317            if (!replacing) {
15318                IntentFilterVerificationInfo ivi =
15319                        mSettings.getIntentFilterVerificationLPr(packageName);
15320                if (ivi != null) {
15321                    if (DEBUG_DOMAIN_VERIFICATION) {
15322                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15323                                + ivi.getStatusString());
15324                    }
15325                    return;
15326                }
15327            }
15328
15329            // If any filters need to be verified, then all need to be.
15330            boolean needToVerify = false;
15331            for (PackageParser.Activity a : pkg.activities) {
15332                for (ActivityIntentInfo filter : a.intents) {
15333                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15334                        if (DEBUG_DOMAIN_VERIFICATION) {
15335                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15336                        }
15337                        needToVerify = true;
15338                        break;
15339                    }
15340                }
15341            }
15342
15343            if (needToVerify) {
15344                final int verificationId = mIntentFilterVerificationToken++;
15345                for (PackageParser.Activity a : pkg.activities) {
15346                    for (ActivityIntentInfo filter : a.intents) {
15347                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15348                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15349                                    "Verification needed for IntentFilter:" + filter.toString());
15350                            mIntentFilterVerifier.addOneIntentFilterVerification(
15351                                    verifierUid, userId, verificationId, filter, packageName);
15352                            count++;
15353                        }
15354                    }
15355                }
15356            }
15357        }
15358
15359        if (count > 0) {
15360            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15361                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15362                    +  " for userId:" + userId);
15363            mIntentFilterVerifier.startVerifications(userId);
15364        } else {
15365            if (DEBUG_DOMAIN_VERIFICATION) {
15366                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15367            }
15368        }
15369    }
15370
15371    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15372        final ComponentName cn  = filter.activity.getComponentName();
15373        final String packageName = cn.getPackageName();
15374
15375        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15376                packageName);
15377        if (ivi == null) {
15378            return true;
15379        }
15380        int status = ivi.getStatus();
15381        switch (status) {
15382            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15383            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15384                return true;
15385
15386            default:
15387                // Nothing to do
15388                return false;
15389        }
15390    }
15391
15392    private static boolean isMultiArch(ApplicationInfo info) {
15393        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15394    }
15395
15396    private static boolean isExternal(PackageParser.Package pkg) {
15397        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15398    }
15399
15400    private static boolean isExternal(PackageSetting ps) {
15401        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15402    }
15403
15404    private static boolean isEphemeral(PackageParser.Package pkg) {
15405        return pkg.applicationInfo.isEphemeralApp();
15406    }
15407
15408    private static boolean isEphemeral(PackageSetting ps) {
15409        return ps.pkg != null && isEphemeral(ps.pkg);
15410    }
15411
15412    private static boolean isSystemApp(PackageParser.Package pkg) {
15413        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15414    }
15415
15416    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15417        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15418    }
15419
15420    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15421        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15422    }
15423
15424    private static boolean isSystemApp(PackageSetting ps) {
15425        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15426    }
15427
15428    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15429        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15430    }
15431
15432    private int packageFlagsToInstallFlags(PackageSetting ps) {
15433        int installFlags = 0;
15434        if (isEphemeral(ps)) {
15435            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15436        }
15437        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15438            // This existing package was an external ASEC install when we have
15439            // the external flag without a UUID
15440            installFlags |= PackageManager.INSTALL_EXTERNAL;
15441        }
15442        if (ps.isForwardLocked()) {
15443            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15444        }
15445        return installFlags;
15446    }
15447
15448    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15449        if (isExternal(pkg)) {
15450            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15451                return StorageManager.UUID_PRIMARY_PHYSICAL;
15452            } else {
15453                return pkg.volumeUuid;
15454            }
15455        } else {
15456            return StorageManager.UUID_PRIVATE_INTERNAL;
15457        }
15458    }
15459
15460    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15461        if (isExternal(pkg)) {
15462            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15463                return mSettings.getExternalVersion();
15464            } else {
15465                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15466            }
15467        } else {
15468            return mSettings.getInternalVersion();
15469        }
15470    }
15471
15472    private void deleteTempPackageFiles() {
15473        final FilenameFilter filter = new FilenameFilter() {
15474            public boolean accept(File dir, String name) {
15475                return name.startsWith("vmdl") && name.endsWith(".tmp");
15476            }
15477        };
15478        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15479            file.delete();
15480        }
15481    }
15482
15483    @Override
15484    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15485            int flags) {
15486        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15487                flags);
15488    }
15489
15490    @Override
15491    public void deletePackage(final String packageName,
15492            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15493        mContext.enforceCallingOrSelfPermission(
15494                android.Manifest.permission.DELETE_PACKAGES, null);
15495        Preconditions.checkNotNull(packageName);
15496        Preconditions.checkNotNull(observer);
15497        final int uid = Binder.getCallingUid();
15498        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15499        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15500        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15501            mContext.enforceCallingOrSelfPermission(
15502                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15503                    "deletePackage for user " + userId);
15504        }
15505
15506        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15507            try {
15508                observer.onPackageDeleted(packageName,
15509                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15510            } catch (RemoteException re) {
15511            }
15512            return;
15513        }
15514
15515        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15516            try {
15517                observer.onPackageDeleted(packageName,
15518                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15519            } catch (RemoteException re) {
15520            }
15521            return;
15522        }
15523
15524        if (DEBUG_REMOVE) {
15525            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15526                    + " deleteAllUsers: " + deleteAllUsers );
15527        }
15528        // Queue up an async operation since the package deletion may take a little while.
15529        mHandler.post(new Runnable() {
15530            public void run() {
15531                mHandler.removeCallbacks(this);
15532                int returnCode;
15533                if (!deleteAllUsers) {
15534                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15535                } else {
15536                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15537                    // If nobody is blocking uninstall, proceed with delete for all users
15538                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15539                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15540                    } else {
15541                        // Otherwise uninstall individually for users with blockUninstalls=false
15542                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15543                        for (int userId : users) {
15544                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15545                                returnCode = deletePackageX(packageName, userId, userFlags);
15546                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15547                                    Slog.w(TAG, "Package delete failed for user " + userId
15548                                            + ", returnCode " + returnCode);
15549                                }
15550                            }
15551                        }
15552                        // The app has only been marked uninstalled for certain users.
15553                        // We still need to report that delete was blocked
15554                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15555                    }
15556                }
15557                try {
15558                    observer.onPackageDeleted(packageName, returnCode, null);
15559                } catch (RemoteException e) {
15560                    Log.i(TAG, "Observer no longer exists.");
15561                } //end catch
15562            } //end run
15563        });
15564    }
15565
15566    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15567        int[] result = EMPTY_INT_ARRAY;
15568        for (int userId : userIds) {
15569            if (getBlockUninstallForUser(packageName, userId)) {
15570                result = ArrayUtils.appendInt(result, userId);
15571            }
15572        }
15573        return result;
15574    }
15575
15576    @Override
15577    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15578        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15579    }
15580
15581    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15582        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15583                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15584        try {
15585            if (dpm != null) {
15586                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15587                        /* callingUserOnly =*/ false);
15588                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15589                        : deviceOwnerComponentName.getPackageName();
15590                // Does the package contains the device owner?
15591                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15592                // this check is probably not needed, since DO should be registered as a device
15593                // admin on some user too. (Original bug for this: b/17657954)
15594                if (packageName.equals(deviceOwnerPackageName)) {
15595                    return true;
15596                }
15597                // Does it contain a device admin for any user?
15598                int[] users;
15599                if (userId == UserHandle.USER_ALL) {
15600                    users = sUserManager.getUserIds();
15601                } else {
15602                    users = new int[]{userId};
15603                }
15604                for (int i = 0; i < users.length; ++i) {
15605                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15606                        return true;
15607                    }
15608                }
15609            }
15610        } catch (RemoteException e) {
15611        }
15612        return false;
15613    }
15614
15615    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15616        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15617    }
15618
15619    /**
15620     *  This method is an internal method that could be get invoked either
15621     *  to delete an installed package or to clean up a failed installation.
15622     *  After deleting an installed package, a broadcast is sent to notify any
15623     *  listeners that the package has been removed. For cleaning up a failed
15624     *  installation, the broadcast is not necessary since the package's
15625     *  installation wouldn't have sent the initial broadcast either
15626     *  The key steps in deleting a package are
15627     *  deleting the package information in internal structures like mPackages,
15628     *  deleting the packages base directories through installd
15629     *  updating mSettings to reflect current status
15630     *  persisting settings for later use
15631     *  sending a broadcast if necessary
15632     */
15633    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15634        final PackageRemovedInfo info = new PackageRemovedInfo();
15635        final boolean res;
15636
15637        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15638                ? UserHandle.USER_ALL : userId;
15639
15640        if (isPackageDeviceAdmin(packageName, removeUser)) {
15641            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15642            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15643        }
15644
15645        PackageSetting uninstalledPs = null;
15646
15647        // for the uninstall-updates case and restricted profiles, remember the per-
15648        // user handle installed state
15649        int[] allUsers;
15650        synchronized (mPackages) {
15651            uninstalledPs = mSettings.mPackages.get(packageName);
15652            if (uninstalledPs == null) {
15653                Slog.w(TAG, "Not removing non-existent package " + packageName);
15654                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15655            }
15656            allUsers = sUserManager.getUserIds();
15657            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15658        }
15659
15660        final int freezeUser;
15661        if (isUpdatedSystemApp(uninstalledPs)
15662                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15663            // We're downgrading a system app, which will apply to all users, so
15664            // freeze them all during the downgrade
15665            freezeUser = UserHandle.USER_ALL;
15666        } else {
15667            freezeUser = removeUser;
15668        }
15669
15670        synchronized (mInstallLock) {
15671            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15672            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15673                    deleteFlags, "deletePackageX")) {
15674                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15675                        deleteFlags | REMOVE_CHATTY, info, true, null);
15676            }
15677            synchronized (mPackages) {
15678                if (res) {
15679                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15680                }
15681            }
15682        }
15683
15684        if (res) {
15685            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15686            info.sendPackageRemovedBroadcasts(killApp);
15687            info.sendSystemPackageUpdatedBroadcasts();
15688            info.sendSystemPackageAppearedBroadcasts();
15689        }
15690        // Force a gc here.
15691        Runtime.getRuntime().gc();
15692        // Delete the resources here after sending the broadcast to let
15693        // other processes clean up before deleting resources.
15694        if (info.args != null) {
15695            synchronized (mInstallLock) {
15696                info.args.doPostDeleteLI(true);
15697            }
15698        }
15699
15700        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15701    }
15702
15703    class PackageRemovedInfo {
15704        String removedPackage;
15705        int uid = -1;
15706        int removedAppId = -1;
15707        int[] origUsers;
15708        int[] removedUsers = null;
15709        boolean isRemovedPackageSystemUpdate = false;
15710        boolean isUpdate;
15711        boolean dataRemoved;
15712        boolean removedForAllUsers;
15713        // Clean up resources deleted packages.
15714        InstallArgs args = null;
15715        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15716        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15717
15718        void sendPackageRemovedBroadcasts(boolean killApp) {
15719            sendPackageRemovedBroadcastInternal(killApp);
15720            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15721            for (int i = 0; i < childCount; i++) {
15722                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15723                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15724            }
15725        }
15726
15727        void sendSystemPackageUpdatedBroadcasts() {
15728            if (isRemovedPackageSystemUpdate) {
15729                sendSystemPackageUpdatedBroadcastsInternal();
15730                final int childCount = (removedChildPackages != null)
15731                        ? removedChildPackages.size() : 0;
15732                for (int i = 0; i < childCount; i++) {
15733                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15734                    if (childInfo.isRemovedPackageSystemUpdate) {
15735                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15736                    }
15737                }
15738            }
15739        }
15740
15741        void sendSystemPackageAppearedBroadcasts() {
15742            final int packageCount = (appearedChildPackages != null)
15743                    ? appearedChildPackages.size() : 0;
15744            for (int i = 0; i < packageCount; i++) {
15745                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15746                for (int userId : installedInfo.newUsers) {
15747                    sendPackageAddedForUser(installedInfo.name, true,
15748                            UserHandle.getAppId(installedInfo.uid), userId);
15749                }
15750            }
15751        }
15752
15753        private void sendSystemPackageUpdatedBroadcastsInternal() {
15754            Bundle extras = new Bundle(2);
15755            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15756            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15757            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15758                    extras, 0, null, null, null);
15759            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15760                    extras, 0, null, null, null);
15761            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15762                    null, 0, removedPackage, null, null);
15763        }
15764
15765        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15766            Bundle extras = new Bundle(2);
15767            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15768            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15769            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15770            if (isUpdate || isRemovedPackageSystemUpdate) {
15771                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15772            }
15773            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15774            if (removedPackage != null) {
15775                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15776                        extras, 0, null, null, removedUsers);
15777                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15778                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15779                            removedPackage, extras, 0, null, null, removedUsers);
15780                }
15781            }
15782            if (removedAppId >= 0) {
15783                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15784                        removedUsers);
15785            }
15786        }
15787    }
15788
15789    /*
15790     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15791     * flag is not set, the data directory is removed as well.
15792     * make sure this flag is set for partially installed apps. If not its meaningless to
15793     * delete a partially installed application.
15794     */
15795    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15796            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15797        String packageName = ps.name;
15798        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15799        // Retrieve object to delete permissions for shared user later on
15800        final PackageParser.Package deletedPkg;
15801        final PackageSetting deletedPs;
15802        // reader
15803        synchronized (mPackages) {
15804            deletedPkg = mPackages.get(packageName);
15805            deletedPs = mSettings.mPackages.get(packageName);
15806            if (outInfo != null) {
15807                outInfo.removedPackage = packageName;
15808                outInfo.removedUsers = deletedPs != null
15809                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15810                        : null;
15811            }
15812        }
15813
15814        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15815
15816        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15817            final PackageParser.Package resolvedPkg;
15818            if (deletedPkg != null) {
15819                resolvedPkg = deletedPkg;
15820            } else {
15821                // We don't have a parsed package when it lives on an ejected
15822                // adopted storage device, so fake something together
15823                resolvedPkg = new PackageParser.Package(ps.name);
15824                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15825            }
15826            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15827                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15828            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15829            if (outInfo != null) {
15830                outInfo.dataRemoved = true;
15831            }
15832            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15833        }
15834
15835        // writer
15836        synchronized (mPackages) {
15837            if (deletedPs != null) {
15838                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15839                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15840                    clearDefaultBrowserIfNeeded(packageName);
15841                    if (outInfo != null) {
15842                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15843                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15844                    }
15845                    updatePermissionsLPw(deletedPs.name, null, 0);
15846                    if (deletedPs.sharedUser != null) {
15847                        // Remove permissions associated with package. Since runtime
15848                        // permissions are per user we have to kill the removed package
15849                        // or packages running under the shared user of the removed
15850                        // package if revoking the permissions requested only by the removed
15851                        // package is successful and this causes a change in gids.
15852                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15853                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15854                                    userId);
15855                            if (userIdToKill == UserHandle.USER_ALL
15856                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15857                                // If gids changed for this user, kill all affected packages.
15858                                mHandler.post(new Runnable() {
15859                                    @Override
15860                                    public void run() {
15861                                        // This has to happen with no lock held.
15862                                        killApplication(deletedPs.name, deletedPs.appId,
15863                                                KILL_APP_REASON_GIDS_CHANGED);
15864                                    }
15865                                });
15866                                break;
15867                            }
15868                        }
15869                    }
15870                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15871                }
15872                // make sure to preserve per-user disabled state if this removal was just
15873                // a downgrade of a system app to the factory package
15874                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15875                    if (DEBUG_REMOVE) {
15876                        Slog.d(TAG, "Propagating install state across downgrade");
15877                    }
15878                    for (int userId : allUserHandles) {
15879                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15880                        if (DEBUG_REMOVE) {
15881                            Slog.d(TAG, "    user " + userId + " => " + installed);
15882                        }
15883                        ps.setInstalled(installed, userId);
15884                    }
15885                }
15886            }
15887            // can downgrade to reader
15888            if (writeSettings) {
15889                // Save settings now
15890                mSettings.writeLPr();
15891            }
15892        }
15893        if (outInfo != null) {
15894            // A user ID was deleted here. Go through all users and remove it
15895            // from KeyStore.
15896            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15897        }
15898    }
15899
15900    static boolean locationIsPrivileged(File path) {
15901        try {
15902            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15903                    .getCanonicalPath();
15904            return path.getCanonicalPath().startsWith(privilegedAppDir);
15905        } catch (IOException e) {
15906            Slog.e(TAG, "Unable to access code path " + path);
15907        }
15908        return false;
15909    }
15910
15911    /*
15912     * Tries to delete system package.
15913     */
15914    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15915            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15916            boolean writeSettings) {
15917        if (deletedPs.parentPackageName != null) {
15918            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15919            return false;
15920        }
15921
15922        final boolean applyUserRestrictions
15923                = (allUserHandles != null) && (outInfo.origUsers != null);
15924        final PackageSetting disabledPs;
15925        // Confirm if the system package has been updated
15926        // An updated system app can be deleted. This will also have to restore
15927        // the system pkg from system partition
15928        // reader
15929        synchronized (mPackages) {
15930            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15931        }
15932
15933        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15934                + " disabledPs=" + disabledPs);
15935
15936        if (disabledPs == null) {
15937            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15938            return false;
15939        } else if (DEBUG_REMOVE) {
15940            Slog.d(TAG, "Deleting system pkg from data partition");
15941        }
15942
15943        if (DEBUG_REMOVE) {
15944            if (applyUserRestrictions) {
15945                Slog.d(TAG, "Remembering install states:");
15946                for (int userId : allUserHandles) {
15947                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15948                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15949                }
15950            }
15951        }
15952
15953        // Delete the updated package
15954        outInfo.isRemovedPackageSystemUpdate = true;
15955        if (outInfo.removedChildPackages != null) {
15956            final int childCount = (deletedPs.childPackageNames != null)
15957                    ? deletedPs.childPackageNames.size() : 0;
15958            for (int i = 0; i < childCount; i++) {
15959                String childPackageName = deletedPs.childPackageNames.get(i);
15960                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15961                        .contains(childPackageName)) {
15962                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15963                            childPackageName);
15964                    if (childInfo != null) {
15965                        childInfo.isRemovedPackageSystemUpdate = true;
15966                    }
15967                }
15968            }
15969        }
15970
15971        if (disabledPs.versionCode < deletedPs.versionCode) {
15972            // Delete data for downgrades
15973            flags &= ~PackageManager.DELETE_KEEP_DATA;
15974        } else {
15975            // Preserve data by setting flag
15976            flags |= PackageManager.DELETE_KEEP_DATA;
15977        }
15978
15979        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15980                outInfo, writeSettings, disabledPs.pkg);
15981        if (!ret) {
15982            return false;
15983        }
15984
15985        // writer
15986        synchronized (mPackages) {
15987            // Reinstate the old system package
15988            enableSystemPackageLPw(disabledPs.pkg);
15989            // Remove any native libraries from the upgraded package.
15990            removeNativeBinariesLI(deletedPs);
15991        }
15992
15993        // Install the system package
15994        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15995        int parseFlags = mDefParseFlags
15996                | PackageParser.PARSE_MUST_BE_APK
15997                | PackageParser.PARSE_IS_SYSTEM
15998                | PackageParser.PARSE_IS_SYSTEM_DIR;
15999        if (locationIsPrivileged(disabledPs.codePath)) {
16000            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16001        }
16002
16003        final PackageParser.Package newPkg;
16004        try {
16005            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16006        } catch (PackageManagerException e) {
16007            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16008                    + e.getMessage());
16009            return false;
16010        }
16011
16012        prepareAppDataAfterInstallLIF(newPkg);
16013
16014        // writer
16015        synchronized (mPackages) {
16016            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16017
16018            // Propagate the permissions state as we do not want to drop on the floor
16019            // runtime permissions. The update permissions method below will take
16020            // care of removing obsolete permissions and grant install permissions.
16021            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16022            updatePermissionsLPw(newPkg.packageName, newPkg,
16023                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16024
16025            if (applyUserRestrictions) {
16026                if (DEBUG_REMOVE) {
16027                    Slog.d(TAG, "Propagating install state across reinstall");
16028                }
16029                for (int userId : allUserHandles) {
16030                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16031                    if (DEBUG_REMOVE) {
16032                        Slog.d(TAG, "    user " + userId + " => " + installed);
16033                    }
16034                    ps.setInstalled(installed, userId);
16035
16036                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16037                }
16038                // Regardless of writeSettings we need to ensure that this restriction
16039                // state propagation is persisted
16040                mSettings.writeAllUsersPackageRestrictionsLPr();
16041            }
16042            // can downgrade to reader here
16043            if (writeSettings) {
16044                mSettings.writeLPr();
16045            }
16046        }
16047        return true;
16048    }
16049
16050    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16051            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16052            PackageRemovedInfo outInfo, boolean writeSettings,
16053            PackageParser.Package replacingPackage) {
16054        synchronized (mPackages) {
16055            if (outInfo != null) {
16056                outInfo.uid = ps.appId;
16057            }
16058
16059            if (outInfo != null && outInfo.removedChildPackages != null) {
16060                final int childCount = (ps.childPackageNames != null)
16061                        ? ps.childPackageNames.size() : 0;
16062                for (int i = 0; i < childCount; i++) {
16063                    String childPackageName = ps.childPackageNames.get(i);
16064                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16065                    if (childPs == null) {
16066                        return false;
16067                    }
16068                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16069                            childPackageName);
16070                    if (childInfo != null) {
16071                        childInfo.uid = childPs.appId;
16072                    }
16073                }
16074            }
16075        }
16076
16077        // Delete package data from internal structures and also remove data if flag is set
16078        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16079
16080        // Delete the child packages data
16081        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16082        for (int i = 0; i < childCount; i++) {
16083            PackageSetting childPs;
16084            synchronized (mPackages) {
16085                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16086            }
16087            if (childPs != null) {
16088                PackageRemovedInfo childOutInfo = (outInfo != null
16089                        && outInfo.removedChildPackages != null)
16090                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16091                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16092                        && (replacingPackage != null
16093                        && !replacingPackage.hasChildPackage(childPs.name))
16094                        ? flags & ~DELETE_KEEP_DATA : flags;
16095                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16096                        deleteFlags, writeSettings);
16097            }
16098        }
16099
16100        // Delete application code and resources only for parent packages
16101        if (ps.parentPackageName == null) {
16102            if (deleteCodeAndResources && (outInfo != null)) {
16103                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16104                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16105                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16106            }
16107        }
16108
16109        return true;
16110    }
16111
16112    @Override
16113    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16114            int userId) {
16115        mContext.enforceCallingOrSelfPermission(
16116                android.Manifest.permission.DELETE_PACKAGES, null);
16117        synchronized (mPackages) {
16118            PackageSetting ps = mSettings.mPackages.get(packageName);
16119            if (ps == null) {
16120                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16121                return false;
16122            }
16123            if (!ps.getInstalled(userId)) {
16124                // Can't block uninstall for an app that is not installed or enabled.
16125                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16126                return false;
16127            }
16128            ps.setBlockUninstall(blockUninstall, userId);
16129            mSettings.writePackageRestrictionsLPr(userId);
16130        }
16131        return true;
16132    }
16133
16134    @Override
16135    public boolean getBlockUninstallForUser(String packageName, int userId) {
16136        synchronized (mPackages) {
16137            PackageSetting ps = mSettings.mPackages.get(packageName);
16138            if (ps == null) {
16139                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16140                return false;
16141            }
16142            return ps.getBlockUninstall(userId);
16143        }
16144    }
16145
16146    @Override
16147    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16148        int callingUid = Binder.getCallingUid();
16149        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16150            throw new SecurityException(
16151                    "setRequiredForSystemUser can only be run by the system or root");
16152        }
16153        synchronized (mPackages) {
16154            PackageSetting ps = mSettings.mPackages.get(packageName);
16155            if (ps == null) {
16156                Log.w(TAG, "Package doesn't exist: " + packageName);
16157                return false;
16158            }
16159            if (systemUserApp) {
16160                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16161            } else {
16162                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16163            }
16164            mSettings.writeLPr();
16165        }
16166        return true;
16167    }
16168
16169    /*
16170     * This method handles package deletion in general
16171     */
16172    private boolean deletePackageLIF(String packageName, UserHandle user,
16173            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16174            PackageRemovedInfo outInfo, boolean writeSettings,
16175            PackageParser.Package replacingPackage) {
16176        if (packageName == null) {
16177            Slog.w(TAG, "Attempt to delete null packageName.");
16178            return false;
16179        }
16180
16181        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16182
16183        PackageSetting ps;
16184
16185        synchronized (mPackages) {
16186            ps = mSettings.mPackages.get(packageName);
16187            if (ps == null) {
16188                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16189                return false;
16190            }
16191
16192            if (ps.parentPackageName != null && (!isSystemApp(ps)
16193                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16194                if (DEBUG_REMOVE) {
16195                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16196                            + ((user == null) ? UserHandle.USER_ALL : user));
16197                }
16198                final int removedUserId = (user != null) ? user.getIdentifier()
16199                        : UserHandle.USER_ALL;
16200                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16201                    return false;
16202                }
16203                markPackageUninstalledForUserLPw(ps, user);
16204                scheduleWritePackageRestrictionsLocked(user);
16205                return true;
16206            }
16207        }
16208
16209        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16210                && user.getIdentifier() != UserHandle.USER_ALL)) {
16211            // The caller is asking that the package only be deleted for a single
16212            // user.  To do this, we just mark its uninstalled state and delete
16213            // its data. If this is a system app, we only allow this to happen if
16214            // they have set the special DELETE_SYSTEM_APP which requests different
16215            // semantics than normal for uninstalling system apps.
16216            markPackageUninstalledForUserLPw(ps, user);
16217
16218            if (!isSystemApp(ps)) {
16219                // Do not uninstall the APK if an app should be cached
16220                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16221                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16222                    // Other user still have this package installed, so all
16223                    // we need to do is clear this user's data and save that
16224                    // it is uninstalled.
16225                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16226                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16227                        return false;
16228                    }
16229                    scheduleWritePackageRestrictionsLocked(user);
16230                    return true;
16231                } else {
16232                    // We need to set it back to 'installed' so the uninstall
16233                    // broadcasts will be sent correctly.
16234                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16235                    ps.setInstalled(true, user.getIdentifier());
16236                }
16237            } else {
16238                // This is a system app, so we assume that the
16239                // other users still have this package installed, so all
16240                // we need to do is clear this user's data and save that
16241                // it is uninstalled.
16242                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16243                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16244                    return false;
16245                }
16246                scheduleWritePackageRestrictionsLocked(user);
16247                return true;
16248            }
16249        }
16250
16251        // If we are deleting a composite package for all users, keep track
16252        // of result for each child.
16253        if (ps.childPackageNames != null && outInfo != null) {
16254            synchronized (mPackages) {
16255                final int childCount = ps.childPackageNames.size();
16256                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16257                for (int i = 0; i < childCount; i++) {
16258                    String childPackageName = ps.childPackageNames.get(i);
16259                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16260                    childInfo.removedPackage = childPackageName;
16261                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16262                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16263                    if (childPs != null) {
16264                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16265                    }
16266                }
16267            }
16268        }
16269
16270        boolean ret = false;
16271        if (isSystemApp(ps)) {
16272            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16273            // When an updated system application is deleted we delete the existing resources
16274            // as well and fall back to existing code in system partition
16275            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16276        } else {
16277            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16278            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16279                    outInfo, writeSettings, replacingPackage);
16280        }
16281
16282        // Take a note whether we deleted the package for all users
16283        if (outInfo != null) {
16284            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16285            if (outInfo.removedChildPackages != null) {
16286                synchronized (mPackages) {
16287                    final int childCount = outInfo.removedChildPackages.size();
16288                    for (int i = 0; i < childCount; i++) {
16289                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16290                        if (childInfo != null) {
16291                            childInfo.removedForAllUsers = mPackages.get(
16292                                    childInfo.removedPackage) == null;
16293                        }
16294                    }
16295                }
16296            }
16297            // If we uninstalled an update to a system app there may be some
16298            // child packages that appeared as they are declared in the system
16299            // app but were not declared in the update.
16300            if (isSystemApp(ps)) {
16301                synchronized (mPackages) {
16302                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16303                    final int childCount = (updatedPs.childPackageNames != null)
16304                            ? updatedPs.childPackageNames.size() : 0;
16305                    for (int i = 0; i < childCount; i++) {
16306                        String childPackageName = updatedPs.childPackageNames.get(i);
16307                        if (outInfo.removedChildPackages == null
16308                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16309                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16310                            if (childPs == null) {
16311                                continue;
16312                            }
16313                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16314                            installRes.name = childPackageName;
16315                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16316                            installRes.pkg = mPackages.get(childPackageName);
16317                            installRes.uid = childPs.pkg.applicationInfo.uid;
16318                            if (outInfo.appearedChildPackages == null) {
16319                                outInfo.appearedChildPackages = new ArrayMap<>();
16320                            }
16321                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16322                        }
16323                    }
16324                }
16325            }
16326        }
16327
16328        return ret;
16329    }
16330
16331    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16332        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16333                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16334        for (int nextUserId : userIds) {
16335            if (DEBUG_REMOVE) {
16336                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16337            }
16338            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16339                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16340                    false /*hidden*/, false /*suspended*/, null, null, null,
16341                    false /*blockUninstall*/,
16342                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16343        }
16344    }
16345
16346    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16347            PackageRemovedInfo outInfo) {
16348        final PackageParser.Package pkg;
16349        synchronized (mPackages) {
16350            pkg = mPackages.get(ps.name);
16351        }
16352
16353        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16354                : new int[] {userId};
16355        for (int nextUserId : userIds) {
16356            if (DEBUG_REMOVE) {
16357                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16358                        + nextUserId);
16359            }
16360
16361            destroyAppDataLIF(pkg, userId,
16362                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16363            destroyAppProfilesLIF(pkg, userId);
16364            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16365            schedulePackageCleaning(ps.name, nextUserId, false);
16366            synchronized (mPackages) {
16367                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16368                    scheduleWritePackageRestrictionsLocked(nextUserId);
16369                }
16370                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16371            }
16372        }
16373
16374        if (outInfo != null) {
16375            outInfo.removedPackage = ps.name;
16376            outInfo.removedAppId = ps.appId;
16377            outInfo.removedUsers = userIds;
16378        }
16379
16380        return true;
16381    }
16382
16383    private final class ClearStorageConnection implements ServiceConnection {
16384        IMediaContainerService mContainerService;
16385
16386        @Override
16387        public void onServiceConnected(ComponentName name, IBinder service) {
16388            synchronized (this) {
16389                mContainerService = IMediaContainerService.Stub.asInterface(service);
16390                notifyAll();
16391            }
16392        }
16393
16394        @Override
16395        public void onServiceDisconnected(ComponentName name) {
16396        }
16397    }
16398
16399    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16400        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16401
16402        final boolean mounted;
16403        if (Environment.isExternalStorageEmulated()) {
16404            mounted = true;
16405        } else {
16406            final String status = Environment.getExternalStorageState();
16407
16408            mounted = status.equals(Environment.MEDIA_MOUNTED)
16409                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16410        }
16411
16412        if (!mounted) {
16413            return;
16414        }
16415
16416        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16417        int[] users;
16418        if (userId == UserHandle.USER_ALL) {
16419            users = sUserManager.getUserIds();
16420        } else {
16421            users = new int[] { userId };
16422        }
16423        final ClearStorageConnection conn = new ClearStorageConnection();
16424        if (mContext.bindServiceAsUser(
16425                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16426            try {
16427                for (int curUser : users) {
16428                    long timeout = SystemClock.uptimeMillis() + 5000;
16429                    synchronized (conn) {
16430                        long now;
16431                        while (conn.mContainerService == null &&
16432                                (now = SystemClock.uptimeMillis()) < timeout) {
16433                            try {
16434                                conn.wait(timeout - now);
16435                            } catch (InterruptedException e) {
16436                            }
16437                        }
16438                    }
16439                    if (conn.mContainerService == null) {
16440                        return;
16441                    }
16442
16443                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16444                    clearDirectory(conn.mContainerService,
16445                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16446                    if (allData) {
16447                        clearDirectory(conn.mContainerService,
16448                                userEnv.buildExternalStorageAppDataDirs(packageName));
16449                        clearDirectory(conn.mContainerService,
16450                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16451                    }
16452                }
16453            } finally {
16454                mContext.unbindService(conn);
16455            }
16456        }
16457    }
16458
16459    @Override
16460    public void clearApplicationProfileData(String packageName) {
16461        enforceSystemOrRoot("Only the system can clear all profile data");
16462
16463        final PackageParser.Package pkg;
16464        synchronized (mPackages) {
16465            pkg = mPackages.get(packageName);
16466        }
16467
16468        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16469            synchronized (mInstallLock) {
16470                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16471                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16472                        true /* removeBaseMarker */);
16473            }
16474        }
16475    }
16476
16477    @Override
16478    public void clearApplicationUserData(final String packageName,
16479            final IPackageDataObserver observer, final int userId) {
16480        mContext.enforceCallingOrSelfPermission(
16481                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16482
16483        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16484                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16485
16486        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16487            throw new SecurityException("Cannot clear data for a protected package: "
16488                    + packageName);
16489        }
16490        // Queue up an async operation since the package deletion may take a little while.
16491        mHandler.post(new Runnable() {
16492            public void run() {
16493                mHandler.removeCallbacks(this);
16494                final boolean succeeded;
16495                try (PackageFreezer freezer = freezePackage(packageName,
16496                        "clearApplicationUserData")) {
16497                    synchronized (mInstallLock) {
16498                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16499                    }
16500                    clearExternalStorageDataSync(packageName, userId, true);
16501                }
16502                if (succeeded) {
16503                    // invoke DeviceStorageMonitor's update method to clear any notifications
16504                    DeviceStorageMonitorInternal dsm = LocalServices
16505                            .getService(DeviceStorageMonitorInternal.class);
16506                    if (dsm != null) {
16507                        dsm.checkMemory();
16508                    }
16509                }
16510                if(observer != null) {
16511                    try {
16512                        observer.onRemoveCompleted(packageName, succeeded);
16513                    } catch (RemoteException e) {
16514                        Log.i(TAG, "Observer no longer exists.");
16515                    }
16516                } //end if observer
16517            } //end run
16518        });
16519    }
16520
16521    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16522        if (packageName == null) {
16523            Slog.w(TAG, "Attempt to delete null packageName.");
16524            return false;
16525        }
16526
16527        // Try finding details about the requested package
16528        PackageParser.Package pkg;
16529        synchronized (mPackages) {
16530            pkg = mPackages.get(packageName);
16531            if (pkg == null) {
16532                final PackageSetting ps = mSettings.mPackages.get(packageName);
16533                if (ps != null) {
16534                    pkg = ps.pkg;
16535                }
16536            }
16537
16538            if (pkg == null) {
16539                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16540                return false;
16541            }
16542
16543            PackageSetting ps = (PackageSetting) pkg.mExtras;
16544            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16545        }
16546
16547        clearAppDataLIF(pkg, userId,
16548                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16549
16550        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16551        removeKeystoreDataIfNeeded(userId, appId);
16552
16553        UserManagerInternal umInternal = getUserManagerInternal();
16554        final int flags;
16555        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16556            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16557        } else if (umInternal.isUserRunning(userId)) {
16558            flags = StorageManager.FLAG_STORAGE_DE;
16559        } else {
16560            flags = 0;
16561        }
16562        prepareAppDataContentsLIF(pkg, userId, flags);
16563
16564        return true;
16565    }
16566
16567    /**
16568     * Reverts user permission state changes (permissions and flags) in
16569     * all packages for a given user.
16570     *
16571     * @param userId The device user for which to do a reset.
16572     */
16573    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16574        final int packageCount = mPackages.size();
16575        for (int i = 0; i < packageCount; i++) {
16576            PackageParser.Package pkg = mPackages.valueAt(i);
16577            PackageSetting ps = (PackageSetting) pkg.mExtras;
16578            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16579        }
16580    }
16581
16582    private void resetNetworkPolicies(int userId) {
16583        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16584    }
16585
16586    /**
16587     * Reverts user permission state changes (permissions and flags).
16588     *
16589     * @param ps The package for which to reset.
16590     * @param userId The device user for which to do a reset.
16591     */
16592    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16593            final PackageSetting ps, final int userId) {
16594        if (ps.pkg == null) {
16595            return;
16596        }
16597
16598        // These are flags that can change base on user actions.
16599        final int userSettableMask = FLAG_PERMISSION_USER_SET
16600                | FLAG_PERMISSION_USER_FIXED
16601                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16602                | FLAG_PERMISSION_REVIEW_REQUIRED;
16603
16604        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16605                | FLAG_PERMISSION_POLICY_FIXED;
16606
16607        boolean writeInstallPermissions = false;
16608        boolean writeRuntimePermissions = false;
16609
16610        final int permissionCount = ps.pkg.requestedPermissions.size();
16611        for (int i = 0; i < permissionCount; i++) {
16612            String permission = ps.pkg.requestedPermissions.get(i);
16613
16614            BasePermission bp = mSettings.mPermissions.get(permission);
16615            if (bp == null) {
16616                continue;
16617            }
16618
16619            // If shared user we just reset the state to which only this app contributed.
16620            if (ps.sharedUser != null) {
16621                boolean used = false;
16622                final int packageCount = ps.sharedUser.packages.size();
16623                for (int j = 0; j < packageCount; j++) {
16624                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16625                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16626                            && pkg.pkg.requestedPermissions.contains(permission)) {
16627                        used = true;
16628                        break;
16629                    }
16630                }
16631                if (used) {
16632                    continue;
16633                }
16634            }
16635
16636            PermissionsState permissionsState = ps.getPermissionsState();
16637
16638            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16639
16640            // Always clear the user settable flags.
16641            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16642                    bp.name) != null;
16643            // If permission review is enabled and this is a legacy app, mark the
16644            // permission as requiring a review as this is the initial state.
16645            int flags = 0;
16646            if (Build.PERMISSIONS_REVIEW_REQUIRED
16647                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16648                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16649            }
16650            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16651                if (hasInstallState) {
16652                    writeInstallPermissions = true;
16653                } else {
16654                    writeRuntimePermissions = true;
16655                }
16656            }
16657
16658            // Below is only runtime permission handling.
16659            if (!bp.isRuntime()) {
16660                continue;
16661            }
16662
16663            // Never clobber system or policy.
16664            if ((oldFlags & policyOrSystemFlags) != 0) {
16665                continue;
16666            }
16667
16668            // If this permission was granted by default, make sure it is.
16669            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16670                if (permissionsState.grantRuntimePermission(bp, userId)
16671                        != PERMISSION_OPERATION_FAILURE) {
16672                    writeRuntimePermissions = true;
16673                }
16674            // If permission review is enabled the permissions for a legacy apps
16675            // are represented as constantly granted runtime ones, so don't revoke.
16676            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16677                // Otherwise, reset the permission.
16678                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16679                switch (revokeResult) {
16680                    case PERMISSION_OPERATION_SUCCESS:
16681                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16682                        writeRuntimePermissions = true;
16683                        final int appId = ps.appId;
16684                        mHandler.post(new Runnable() {
16685                            @Override
16686                            public void run() {
16687                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16688                            }
16689                        });
16690                    } break;
16691                }
16692            }
16693        }
16694
16695        // Synchronously write as we are taking permissions away.
16696        if (writeRuntimePermissions) {
16697            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16698        }
16699
16700        // Synchronously write as we are taking permissions away.
16701        if (writeInstallPermissions) {
16702            mSettings.writeLPr();
16703        }
16704    }
16705
16706    /**
16707     * Remove entries from the keystore daemon. Will only remove it if the
16708     * {@code appId} is valid.
16709     */
16710    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16711        if (appId < 0) {
16712            return;
16713        }
16714
16715        final KeyStore keyStore = KeyStore.getInstance();
16716        if (keyStore != null) {
16717            if (userId == UserHandle.USER_ALL) {
16718                for (final int individual : sUserManager.getUserIds()) {
16719                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16720                }
16721            } else {
16722                keyStore.clearUid(UserHandle.getUid(userId, appId));
16723            }
16724        } else {
16725            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16726        }
16727    }
16728
16729    @Override
16730    public void deleteApplicationCacheFiles(final String packageName,
16731            final IPackageDataObserver observer) {
16732        final int userId = UserHandle.getCallingUserId();
16733        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16734    }
16735
16736    @Override
16737    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16738            final IPackageDataObserver observer) {
16739        mContext.enforceCallingOrSelfPermission(
16740                android.Manifest.permission.DELETE_CACHE_FILES, null);
16741        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16742                /* requireFullPermission= */ true, /* checkShell= */ false,
16743                "delete application cache files");
16744
16745        final PackageParser.Package pkg;
16746        synchronized (mPackages) {
16747            pkg = mPackages.get(packageName);
16748        }
16749
16750        // Queue up an async operation since the package deletion may take a little while.
16751        mHandler.post(new Runnable() {
16752            public void run() {
16753                synchronized (mInstallLock) {
16754                    final int flags = StorageManager.FLAG_STORAGE_DE
16755                            | StorageManager.FLAG_STORAGE_CE;
16756                    // We're only clearing cache files, so we don't care if the
16757                    // app is unfrozen and still able to run
16758                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16759                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16760                }
16761                clearExternalStorageDataSync(packageName, userId, false);
16762                if (observer != null) {
16763                    try {
16764                        observer.onRemoveCompleted(packageName, true);
16765                    } catch (RemoteException e) {
16766                        Log.i(TAG, "Observer no longer exists.");
16767                    }
16768                }
16769            }
16770        });
16771    }
16772
16773    @Override
16774    public void getPackageSizeInfo(final String packageName, int userHandle,
16775            final IPackageStatsObserver observer) {
16776        mContext.enforceCallingOrSelfPermission(
16777                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16778        if (packageName == null) {
16779            throw new IllegalArgumentException("Attempt to get size of null packageName");
16780        }
16781
16782        PackageStats stats = new PackageStats(packageName, userHandle);
16783
16784        /*
16785         * Queue up an async operation since the package measurement may take a
16786         * little while.
16787         */
16788        Message msg = mHandler.obtainMessage(INIT_COPY);
16789        msg.obj = new MeasureParams(stats, observer);
16790        mHandler.sendMessage(msg);
16791    }
16792
16793    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16794        final PackageSetting ps;
16795        synchronized (mPackages) {
16796            ps = mSettings.mPackages.get(packageName);
16797            if (ps == null) {
16798                Slog.w(TAG, "Failed to find settings for " + packageName);
16799                return false;
16800            }
16801        }
16802        try {
16803            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16804                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16805                    ps.getCeDataInode(userId), ps.codePathString, stats);
16806        } catch (InstallerException e) {
16807            Slog.w(TAG, String.valueOf(e));
16808            return false;
16809        }
16810
16811        // For now, ignore code size of packages on system partition
16812        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16813            stats.codeSize = 0;
16814        }
16815
16816        return true;
16817    }
16818
16819    private int getUidTargetSdkVersionLockedLPr(int uid) {
16820        Object obj = mSettings.getUserIdLPr(uid);
16821        if (obj instanceof SharedUserSetting) {
16822            final SharedUserSetting sus = (SharedUserSetting) obj;
16823            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16824            final Iterator<PackageSetting> it = sus.packages.iterator();
16825            while (it.hasNext()) {
16826                final PackageSetting ps = it.next();
16827                if (ps.pkg != null) {
16828                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16829                    if (v < vers) vers = v;
16830                }
16831            }
16832            return vers;
16833        } else if (obj instanceof PackageSetting) {
16834            final PackageSetting ps = (PackageSetting) obj;
16835            if (ps.pkg != null) {
16836                return ps.pkg.applicationInfo.targetSdkVersion;
16837            }
16838        }
16839        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16840    }
16841
16842    @Override
16843    public void addPreferredActivity(IntentFilter filter, int match,
16844            ComponentName[] set, ComponentName activity, int userId) {
16845        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16846                "Adding preferred");
16847    }
16848
16849    private void addPreferredActivityInternal(IntentFilter filter, int match,
16850            ComponentName[] set, ComponentName activity, boolean always, int userId,
16851            String opname) {
16852        // writer
16853        int callingUid = Binder.getCallingUid();
16854        enforceCrossUserPermission(callingUid, userId,
16855                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16856        if (filter.countActions() == 0) {
16857            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16858            return;
16859        }
16860        synchronized (mPackages) {
16861            if (mContext.checkCallingOrSelfPermission(
16862                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16863                    != PackageManager.PERMISSION_GRANTED) {
16864                if (getUidTargetSdkVersionLockedLPr(callingUid)
16865                        < Build.VERSION_CODES.FROYO) {
16866                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16867                            + callingUid);
16868                    return;
16869                }
16870                mContext.enforceCallingOrSelfPermission(
16871                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16872            }
16873
16874            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16875            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16876                    + userId + ":");
16877            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16878            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16879            scheduleWritePackageRestrictionsLocked(userId);
16880        }
16881    }
16882
16883    @Override
16884    public void replacePreferredActivity(IntentFilter filter, int match,
16885            ComponentName[] set, ComponentName activity, int userId) {
16886        if (filter.countActions() != 1) {
16887            throw new IllegalArgumentException(
16888                    "replacePreferredActivity expects filter to have only 1 action.");
16889        }
16890        if (filter.countDataAuthorities() != 0
16891                || filter.countDataPaths() != 0
16892                || filter.countDataSchemes() > 1
16893                || filter.countDataTypes() != 0) {
16894            throw new IllegalArgumentException(
16895                    "replacePreferredActivity expects filter to have no data authorities, " +
16896                    "paths, or types; and at most one scheme.");
16897        }
16898
16899        final int callingUid = Binder.getCallingUid();
16900        enforceCrossUserPermission(callingUid, userId,
16901                true /* requireFullPermission */, false /* checkShell */,
16902                "replace preferred activity");
16903        synchronized (mPackages) {
16904            if (mContext.checkCallingOrSelfPermission(
16905                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16906                    != PackageManager.PERMISSION_GRANTED) {
16907                if (getUidTargetSdkVersionLockedLPr(callingUid)
16908                        < Build.VERSION_CODES.FROYO) {
16909                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16910                            + Binder.getCallingUid());
16911                    return;
16912                }
16913                mContext.enforceCallingOrSelfPermission(
16914                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16915            }
16916
16917            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16918            if (pir != null) {
16919                // Get all of the existing entries that exactly match this filter.
16920                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16921                if (existing != null && existing.size() == 1) {
16922                    PreferredActivity cur = existing.get(0);
16923                    if (DEBUG_PREFERRED) {
16924                        Slog.i(TAG, "Checking replace of preferred:");
16925                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16926                        if (!cur.mPref.mAlways) {
16927                            Slog.i(TAG, "  -- CUR; not mAlways!");
16928                        } else {
16929                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16930                            Slog.i(TAG, "  -- CUR: mSet="
16931                                    + Arrays.toString(cur.mPref.mSetComponents));
16932                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16933                            Slog.i(TAG, "  -- NEW: mMatch="
16934                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16935                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16936                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16937                        }
16938                    }
16939                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16940                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16941                            && cur.mPref.sameSet(set)) {
16942                        // Setting the preferred activity to what it happens to be already
16943                        if (DEBUG_PREFERRED) {
16944                            Slog.i(TAG, "Replacing with same preferred activity "
16945                                    + cur.mPref.mShortComponent + " for user "
16946                                    + userId + ":");
16947                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16948                        }
16949                        return;
16950                    }
16951                }
16952
16953                if (existing != null) {
16954                    if (DEBUG_PREFERRED) {
16955                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16956                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16957                    }
16958                    for (int i = 0; i < existing.size(); i++) {
16959                        PreferredActivity pa = existing.get(i);
16960                        if (DEBUG_PREFERRED) {
16961                            Slog.i(TAG, "Removing existing preferred activity "
16962                                    + pa.mPref.mComponent + ":");
16963                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16964                        }
16965                        pir.removeFilter(pa);
16966                    }
16967                }
16968            }
16969            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16970                    "Replacing preferred");
16971        }
16972    }
16973
16974    @Override
16975    public void clearPackagePreferredActivities(String packageName) {
16976        final int uid = Binder.getCallingUid();
16977        // writer
16978        synchronized (mPackages) {
16979            PackageParser.Package pkg = mPackages.get(packageName);
16980            if (pkg == null || pkg.applicationInfo.uid != uid) {
16981                if (mContext.checkCallingOrSelfPermission(
16982                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16983                        != PackageManager.PERMISSION_GRANTED) {
16984                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16985                            < Build.VERSION_CODES.FROYO) {
16986                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16987                                + Binder.getCallingUid());
16988                        return;
16989                    }
16990                    mContext.enforceCallingOrSelfPermission(
16991                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16992                }
16993            }
16994
16995            int user = UserHandle.getCallingUserId();
16996            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16997                scheduleWritePackageRestrictionsLocked(user);
16998            }
16999        }
17000    }
17001
17002    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17003    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17004        ArrayList<PreferredActivity> removed = null;
17005        boolean changed = false;
17006        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17007            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17008            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17009            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17010                continue;
17011            }
17012            Iterator<PreferredActivity> it = pir.filterIterator();
17013            while (it.hasNext()) {
17014                PreferredActivity pa = it.next();
17015                // Mark entry for removal only if it matches the package name
17016                // and the entry is of type "always".
17017                if (packageName == null ||
17018                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17019                                && pa.mPref.mAlways)) {
17020                    if (removed == null) {
17021                        removed = new ArrayList<PreferredActivity>();
17022                    }
17023                    removed.add(pa);
17024                }
17025            }
17026            if (removed != null) {
17027                for (int j=0; j<removed.size(); j++) {
17028                    PreferredActivity pa = removed.get(j);
17029                    pir.removeFilter(pa);
17030                }
17031                changed = true;
17032            }
17033        }
17034        return changed;
17035    }
17036
17037    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17038    private void clearIntentFilterVerificationsLPw(int userId) {
17039        final int packageCount = mPackages.size();
17040        for (int i = 0; i < packageCount; i++) {
17041            PackageParser.Package pkg = mPackages.valueAt(i);
17042            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17043        }
17044    }
17045
17046    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17047    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17048        if (userId == UserHandle.USER_ALL) {
17049            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17050                    sUserManager.getUserIds())) {
17051                for (int oneUserId : sUserManager.getUserIds()) {
17052                    scheduleWritePackageRestrictionsLocked(oneUserId);
17053                }
17054            }
17055        } else {
17056            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17057                scheduleWritePackageRestrictionsLocked(userId);
17058            }
17059        }
17060    }
17061
17062    void clearDefaultBrowserIfNeeded(String packageName) {
17063        for (int oneUserId : sUserManager.getUserIds()) {
17064            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17065            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17066            if (packageName.equals(defaultBrowserPackageName)) {
17067                setDefaultBrowserPackageName(null, oneUserId);
17068            }
17069        }
17070    }
17071
17072    @Override
17073    public void resetApplicationPreferences(int userId) {
17074        mContext.enforceCallingOrSelfPermission(
17075                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17076        final long identity = Binder.clearCallingIdentity();
17077        // writer
17078        try {
17079            synchronized (mPackages) {
17080                clearPackagePreferredActivitiesLPw(null, userId);
17081                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17082                // TODO: We have to reset the default SMS and Phone. This requires
17083                // significant refactoring to keep all default apps in the package
17084                // manager (cleaner but more work) or have the services provide
17085                // callbacks to the package manager to request a default app reset.
17086                applyFactoryDefaultBrowserLPw(userId);
17087                clearIntentFilterVerificationsLPw(userId);
17088                primeDomainVerificationsLPw(userId);
17089                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17090                scheduleWritePackageRestrictionsLocked(userId);
17091            }
17092            resetNetworkPolicies(userId);
17093        } finally {
17094            Binder.restoreCallingIdentity(identity);
17095        }
17096    }
17097
17098    @Override
17099    public int getPreferredActivities(List<IntentFilter> outFilters,
17100            List<ComponentName> outActivities, String packageName) {
17101
17102        int num = 0;
17103        final int userId = UserHandle.getCallingUserId();
17104        // reader
17105        synchronized (mPackages) {
17106            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17107            if (pir != null) {
17108                final Iterator<PreferredActivity> it = pir.filterIterator();
17109                while (it.hasNext()) {
17110                    final PreferredActivity pa = it.next();
17111                    if (packageName == null
17112                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17113                                    && pa.mPref.mAlways)) {
17114                        if (outFilters != null) {
17115                            outFilters.add(new IntentFilter(pa));
17116                        }
17117                        if (outActivities != null) {
17118                            outActivities.add(pa.mPref.mComponent);
17119                        }
17120                    }
17121                }
17122            }
17123        }
17124
17125        return num;
17126    }
17127
17128    @Override
17129    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17130            int userId) {
17131        int callingUid = Binder.getCallingUid();
17132        if (callingUid != Process.SYSTEM_UID) {
17133            throw new SecurityException(
17134                    "addPersistentPreferredActivity can only be run by the system");
17135        }
17136        if (filter.countActions() == 0) {
17137            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17138            return;
17139        }
17140        synchronized (mPackages) {
17141            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17142                    ":");
17143            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17144            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17145                    new PersistentPreferredActivity(filter, activity));
17146            scheduleWritePackageRestrictionsLocked(userId);
17147        }
17148    }
17149
17150    @Override
17151    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17152        int callingUid = Binder.getCallingUid();
17153        if (callingUid != Process.SYSTEM_UID) {
17154            throw new SecurityException(
17155                    "clearPackagePersistentPreferredActivities can only be run by the system");
17156        }
17157        ArrayList<PersistentPreferredActivity> removed = null;
17158        boolean changed = false;
17159        synchronized (mPackages) {
17160            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17161                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17162                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17163                        .valueAt(i);
17164                if (userId != thisUserId) {
17165                    continue;
17166                }
17167                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17168                while (it.hasNext()) {
17169                    PersistentPreferredActivity ppa = it.next();
17170                    // Mark entry for removal only if it matches the package name.
17171                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17172                        if (removed == null) {
17173                            removed = new ArrayList<PersistentPreferredActivity>();
17174                        }
17175                        removed.add(ppa);
17176                    }
17177                }
17178                if (removed != null) {
17179                    for (int j=0; j<removed.size(); j++) {
17180                        PersistentPreferredActivity ppa = removed.get(j);
17181                        ppir.removeFilter(ppa);
17182                    }
17183                    changed = true;
17184                }
17185            }
17186
17187            if (changed) {
17188                scheduleWritePackageRestrictionsLocked(userId);
17189            }
17190        }
17191    }
17192
17193    /**
17194     * Common machinery for picking apart a restored XML blob and passing
17195     * it to a caller-supplied functor to be applied to the running system.
17196     */
17197    private void restoreFromXml(XmlPullParser parser, int userId,
17198            String expectedStartTag, BlobXmlRestorer functor)
17199            throws IOException, XmlPullParserException {
17200        int type;
17201        while ((type = parser.next()) != XmlPullParser.START_TAG
17202                && type != XmlPullParser.END_DOCUMENT) {
17203        }
17204        if (type != XmlPullParser.START_TAG) {
17205            // oops didn't find a start tag?!
17206            if (DEBUG_BACKUP) {
17207                Slog.e(TAG, "Didn't find start tag during restore");
17208            }
17209            return;
17210        }
17211Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17212        // this is supposed to be TAG_PREFERRED_BACKUP
17213        if (!expectedStartTag.equals(parser.getName())) {
17214            if (DEBUG_BACKUP) {
17215                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17216            }
17217            return;
17218        }
17219
17220        // skip interfering stuff, then we're aligned with the backing implementation
17221        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17222Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17223        functor.apply(parser, userId);
17224    }
17225
17226    private interface BlobXmlRestorer {
17227        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17228    }
17229
17230    /**
17231     * Non-Binder method, support for the backup/restore mechanism: write the
17232     * full set of preferred activities in its canonical XML format.  Returns the
17233     * XML output as a byte array, or null if there is none.
17234     */
17235    @Override
17236    public byte[] getPreferredActivityBackup(int userId) {
17237        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17238            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17239        }
17240
17241        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17242        try {
17243            final XmlSerializer serializer = new FastXmlSerializer();
17244            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17245            serializer.startDocument(null, true);
17246            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17247
17248            synchronized (mPackages) {
17249                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17250            }
17251
17252            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17253            serializer.endDocument();
17254            serializer.flush();
17255        } catch (Exception e) {
17256            if (DEBUG_BACKUP) {
17257                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17258            }
17259            return null;
17260        }
17261
17262        return dataStream.toByteArray();
17263    }
17264
17265    @Override
17266    public void restorePreferredActivities(byte[] backup, int userId) {
17267        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17268            throw new SecurityException("Only the system may call restorePreferredActivities()");
17269        }
17270
17271        try {
17272            final XmlPullParser parser = Xml.newPullParser();
17273            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17274            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17275                    new BlobXmlRestorer() {
17276                        @Override
17277                        public void apply(XmlPullParser parser, int userId)
17278                                throws XmlPullParserException, IOException {
17279                            synchronized (mPackages) {
17280                                mSettings.readPreferredActivitiesLPw(parser, userId);
17281                            }
17282                        }
17283                    } );
17284        } catch (Exception e) {
17285            if (DEBUG_BACKUP) {
17286                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17287            }
17288        }
17289    }
17290
17291    /**
17292     * Non-Binder method, support for the backup/restore mechanism: write the
17293     * default browser (etc) settings in its canonical XML format.  Returns the default
17294     * browser XML representation as a byte array, or null if there is none.
17295     */
17296    @Override
17297    public byte[] getDefaultAppsBackup(int userId) {
17298        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17299            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17300        }
17301
17302        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17303        try {
17304            final XmlSerializer serializer = new FastXmlSerializer();
17305            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17306            serializer.startDocument(null, true);
17307            serializer.startTag(null, TAG_DEFAULT_APPS);
17308
17309            synchronized (mPackages) {
17310                mSettings.writeDefaultAppsLPr(serializer, userId);
17311            }
17312
17313            serializer.endTag(null, TAG_DEFAULT_APPS);
17314            serializer.endDocument();
17315            serializer.flush();
17316        } catch (Exception e) {
17317            if (DEBUG_BACKUP) {
17318                Slog.e(TAG, "Unable to write default apps for backup", e);
17319            }
17320            return null;
17321        }
17322
17323        return dataStream.toByteArray();
17324    }
17325
17326    @Override
17327    public void restoreDefaultApps(byte[] backup, int userId) {
17328        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17329            throw new SecurityException("Only the system may call restoreDefaultApps()");
17330        }
17331
17332        try {
17333            final XmlPullParser parser = Xml.newPullParser();
17334            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17335            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17336                    new BlobXmlRestorer() {
17337                        @Override
17338                        public void apply(XmlPullParser parser, int userId)
17339                                throws XmlPullParserException, IOException {
17340                            synchronized (mPackages) {
17341                                mSettings.readDefaultAppsLPw(parser, userId);
17342                            }
17343                        }
17344                    } );
17345        } catch (Exception e) {
17346            if (DEBUG_BACKUP) {
17347                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17348            }
17349        }
17350    }
17351
17352    @Override
17353    public byte[] getIntentFilterVerificationBackup(int userId) {
17354        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17355            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17356        }
17357
17358        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17359        try {
17360            final XmlSerializer serializer = new FastXmlSerializer();
17361            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17362            serializer.startDocument(null, true);
17363            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17364
17365            synchronized (mPackages) {
17366                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17367            }
17368
17369            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17370            serializer.endDocument();
17371            serializer.flush();
17372        } catch (Exception e) {
17373            if (DEBUG_BACKUP) {
17374                Slog.e(TAG, "Unable to write default apps for backup", e);
17375            }
17376            return null;
17377        }
17378
17379        return dataStream.toByteArray();
17380    }
17381
17382    @Override
17383    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17384        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17385            throw new SecurityException("Only the system may call restorePreferredActivities()");
17386        }
17387
17388        try {
17389            final XmlPullParser parser = Xml.newPullParser();
17390            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17391            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17392                    new BlobXmlRestorer() {
17393                        @Override
17394                        public void apply(XmlPullParser parser, int userId)
17395                                throws XmlPullParserException, IOException {
17396                            synchronized (mPackages) {
17397                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17398                                mSettings.writeLPr();
17399                            }
17400                        }
17401                    } );
17402        } catch (Exception e) {
17403            if (DEBUG_BACKUP) {
17404                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17405            }
17406        }
17407    }
17408
17409    @Override
17410    public byte[] getPermissionGrantBackup(int userId) {
17411        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17412            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17413        }
17414
17415        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17416        try {
17417            final XmlSerializer serializer = new FastXmlSerializer();
17418            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17419            serializer.startDocument(null, true);
17420            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17421
17422            synchronized (mPackages) {
17423                serializeRuntimePermissionGrantsLPr(serializer, userId);
17424            }
17425
17426            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17427            serializer.endDocument();
17428            serializer.flush();
17429        } catch (Exception e) {
17430            if (DEBUG_BACKUP) {
17431                Slog.e(TAG, "Unable to write default apps for backup", e);
17432            }
17433            return null;
17434        }
17435
17436        return dataStream.toByteArray();
17437    }
17438
17439    @Override
17440    public void restorePermissionGrants(byte[] backup, int userId) {
17441        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17442            throw new SecurityException("Only the system may call restorePermissionGrants()");
17443        }
17444
17445        try {
17446            final XmlPullParser parser = Xml.newPullParser();
17447            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17448            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17449                    new BlobXmlRestorer() {
17450                        @Override
17451                        public void apply(XmlPullParser parser, int userId)
17452                                throws XmlPullParserException, IOException {
17453                            synchronized (mPackages) {
17454                                processRestoredPermissionGrantsLPr(parser, userId);
17455                            }
17456                        }
17457                    } );
17458        } catch (Exception e) {
17459            if (DEBUG_BACKUP) {
17460                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17461            }
17462        }
17463    }
17464
17465    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17466            throws IOException {
17467        serializer.startTag(null, TAG_ALL_GRANTS);
17468
17469        final int N = mSettings.mPackages.size();
17470        for (int i = 0; i < N; i++) {
17471            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17472            boolean pkgGrantsKnown = false;
17473
17474            PermissionsState packagePerms = ps.getPermissionsState();
17475
17476            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17477                final int grantFlags = state.getFlags();
17478                // only look at grants that are not system/policy fixed
17479                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17480                    final boolean isGranted = state.isGranted();
17481                    // And only back up the user-twiddled state bits
17482                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17483                        final String packageName = mSettings.mPackages.keyAt(i);
17484                        if (!pkgGrantsKnown) {
17485                            serializer.startTag(null, TAG_GRANT);
17486                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17487                            pkgGrantsKnown = true;
17488                        }
17489
17490                        final boolean userSet =
17491                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17492                        final boolean userFixed =
17493                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17494                        final boolean revoke =
17495                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17496
17497                        serializer.startTag(null, TAG_PERMISSION);
17498                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17499                        if (isGranted) {
17500                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17501                        }
17502                        if (userSet) {
17503                            serializer.attribute(null, ATTR_USER_SET, "true");
17504                        }
17505                        if (userFixed) {
17506                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17507                        }
17508                        if (revoke) {
17509                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17510                        }
17511                        serializer.endTag(null, TAG_PERMISSION);
17512                    }
17513                }
17514            }
17515
17516            if (pkgGrantsKnown) {
17517                serializer.endTag(null, TAG_GRANT);
17518            }
17519        }
17520
17521        serializer.endTag(null, TAG_ALL_GRANTS);
17522    }
17523
17524    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17525            throws XmlPullParserException, IOException {
17526        String pkgName = null;
17527        int outerDepth = parser.getDepth();
17528        int type;
17529        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17530                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17531            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17532                continue;
17533            }
17534
17535            final String tagName = parser.getName();
17536            if (tagName.equals(TAG_GRANT)) {
17537                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17538                if (DEBUG_BACKUP) {
17539                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17540                }
17541            } else if (tagName.equals(TAG_PERMISSION)) {
17542
17543                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17544                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17545
17546                int newFlagSet = 0;
17547                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17548                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17549                }
17550                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17551                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17552                }
17553                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17554                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17555                }
17556                if (DEBUG_BACKUP) {
17557                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17558                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17559                }
17560                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17561                if (ps != null) {
17562                    // Already installed so we apply the grant immediately
17563                    if (DEBUG_BACKUP) {
17564                        Slog.v(TAG, "        + already installed; applying");
17565                    }
17566                    PermissionsState perms = ps.getPermissionsState();
17567                    BasePermission bp = mSettings.mPermissions.get(permName);
17568                    if (bp != null) {
17569                        if (isGranted) {
17570                            perms.grantRuntimePermission(bp, userId);
17571                        }
17572                        if (newFlagSet != 0) {
17573                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17574                        }
17575                    }
17576                } else {
17577                    // Need to wait for post-restore install to apply the grant
17578                    if (DEBUG_BACKUP) {
17579                        Slog.v(TAG, "        - not yet installed; saving for later");
17580                    }
17581                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17582                            isGranted, newFlagSet, userId);
17583                }
17584            } else {
17585                PackageManagerService.reportSettingsProblem(Log.WARN,
17586                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17587                XmlUtils.skipCurrentTag(parser);
17588            }
17589        }
17590
17591        scheduleWriteSettingsLocked();
17592        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17593    }
17594
17595    @Override
17596    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17597            int sourceUserId, int targetUserId, int flags) {
17598        mContext.enforceCallingOrSelfPermission(
17599                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17600        int callingUid = Binder.getCallingUid();
17601        enforceOwnerRights(ownerPackage, callingUid);
17602        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17603        if (intentFilter.countActions() == 0) {
17604            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17605            return;
17606        }
17607        synchronized (mPackages) {
17608            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17609                    ownerPackage, targetUserId, flags);
17610            CrossProfileIntentResolver resolver =
17611                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17612            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17613            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17614            if (existing != null) {
17615                int size = existing.size();
17616                for (int i = 0; i < size; i++) {
17617                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17618                        return;
17619                    }
17620                }
17621            }
17622            resolver.addFilter(newFilter);
17623            scheduleWritePackageRestrictionsLocked(sourceUserId);
17624        }
17625    }
17626
17627    @Override
17628    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17629        mContext.enforceCallingOrSelfPermission(
17630                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17631        int callingUid = Binder.getCallingUid();
17632        enforceOwnerRights(ownerPackage, callingUid);
17633        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17634        synchronized (mPackages) {
17635            CrossProfileIntentResolver resolver =
17636                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17637            ArraySet<CrossProfileIntentFilter> set =
17638                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17639            for (CrossProfileIntentFilter filter : set) {
17640                if (filter.getOwnerPackage().equals(ownerPackage)) {
17641                    resolver.removeFilter(filter);
17642                }
17643            }
17644            scheduleWritePackageRestrictionsLocked(sourceUserId);
17645        }
17646    }
17647
17648    // Enforcing that callingUid is owning pkg on userId
17649    private void enforceOwnerRights(String pkg, int callingUid) {
17650        // The system owns everything.
17651        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17652            return;
17653        }
17654        int callingUserId = UserHandle.getUserId(callingUid);
17655        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17656        if (pi == null) {
17657            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17658                    + callingUserId);
17659        }
17660        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17661            throw new SecurityException("Calling uid " + callingUid
17662                    + " does not own package " + pkg);
17663        }
17664    }
17665
17666    @Override
17667    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17668        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17669    }
17670
17671    private Intent getHomeIntent() {
17672        Intent intent = new Intent(Intent.ACTION_MAIN);
17673        intent.addCategory(Intent.CATEGORY_HOME);
17674        intent.addCategory(Intent.CATEGORY_DEFAULT);
17675        return intent;
17676    }
17677
17678    private IntentFilter getHomeFilter() {
17679        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17680        filter.addCategory(Intent.CATEGORY_HOME);
17681        filter.addCategory(Intent.CATEGORY_DEFAULT);
17682        return filter;
17683    }
17684
17685    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17686            int userId) {
17687        Intent intent  = getHomeIntent();
17688        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17689                PackageManager.GET_META_DATA, userId);
17690        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17691                true, false, false, userId);
17692
17693        allHomeCandidates.clear();
17694        if (list != null) {
17695            for (ResolveInfo ri : list) {
17696                allHomeCandidates.add(ri);
17697            }
17698        }
17699        return (preferred == null || preferred.activityInfo == null)
17700                ? null
17701                : new ComponentName(preferred.activityInfo.packageName,
17702                        preferred.activityInfo.name);
17703    }
17704
17705    @Override
17706    public void setHomeActivity(ComponentName comp, int userId) {
17707        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17708        getHomeActivitiesAsUser(homeActivities, userId);
17709
17710        boolean found = false;
17711
17712        final int size = homeActivities.size();
17713        final ComponentName[] set = new ComponentName[size];
17714        for (int i = 0; i < size; i++) {
17715            final ResolveInfo candidate = homeActivities.get(i);
17716            final ActivityInfo info = candidate.activityInfo;
17717            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17718            set[i] = activityName;
17719            if (!found && activityName.equals(comp)) {
17720                found = true;
17721            }
17722        }
17723        if (!found) {
17724            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17725                    + userId);
17726        }
17727        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17728                set, comp, userId);
17729    }
17730
17731    private @Nullable String getSetupWizardPackageName() {
17732        final Intent intent = new Intent(Intent.ACTION_MAIN);
17733        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17734
17735        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17736                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17737                        | MATCH_DISABLED_COMPONENTS,
17738                UserHandle.myUserId());
17739        if (matches.size() == 1) {
17740            return matches.get(0).getComponentInfo().packageName;
17741        } else {
17742            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17743                    + ": matches=" + matches);
17744            return null;
17745        }
17746    }
17747
17748    @Override
17749    public void setApplicationEnabledSetting(String appPackageName,
17750            int newState, int flags, int userId, String callingPackage) {
17751        if (!sUserManager.exists(userId)) return;
17752        if (callingPackage == null) {
17753            callingPackage = Integer.toString(Binder.getCallingUid());
17754        }
17755        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17756    }
17757
17758    @Override
17759    public void setComponentEnabledSetting(ComponentName componentName,
17760            int newState, int flags, int userId) {
17761        if (!sUserManager.exists(userId)) return;
17762        setEnabledSetting(componentName.getPackageName(),
17763                componentName.getClassName(), newState, flags, userId, null);
17764    }
17765
17766    private void setEnabledSetting(final String packageName, String className, int newState,
17767            final int flags, int userId, String callingPackage) {
17768        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17769              || newState == COMPONENT_ENABLED_STATE_ENABLED
17770              || newState == COMPONENT_ENABLED_STATE_DISABLED
17771              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17772              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17773            throw new IllegalArgumentException("Invalid new component state: "
17774                    + newState);
17775        }
17776        PackageSetting pkgSetting;
17777        final int uid = Binder.getCallingUid();
17778        final int permission;
17779        if (uid == Process.SYSTEM_UID) {
17780            permission = PackageManager.PERMISSION_GRANTED;
17781        } else {
17782            permission = mContext.checkCallingOrSelfPermission(
17783                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17784        }
17785        enforceCrossUserPermission(uid, userId,
17786                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17787        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17788        boolean sendNow = false;
17789        boolean isApp = (className == null);
17790        String componentName = isApp ? packageName : className;
17791        int packageUid = -1;
17792        ArrayList<String> components;
17793
17794        // writer
17795        synchronized (mPackages) {
17796            pkgSetting = mSettings.mPackages.get(packageName);
17797            if (pkgSetting == null) {
17798                if (className == null) {
17799                    throw new IllegalArgumentException("Unknown package: " + packageName);
17800                }
17801                throw new IllegalArgumentException(
17802                        "Unknown component: " + packageName + "/" + className);
17803            }
17804        }
17805
17806        // Limit who can change which apps
17807        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17808            // Don't allow apps that don't have permission to modify other apps
17809            if (!allowedByPermission) {
17810                throw new SecurityException(
17811                        "Permission Denial: attempt to change component state from pid="
17812                        + Binder.getCallingPid()
17813                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17814            }
17815            // Don't allow changing protected packages.
17816            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17817                throw new SecurityException("Cannot disable a protected package: " + packageName);
17818            }
17819        }
17820
17821        synchronized (mPackages) {
17822            if (uid == Process.SHELL_UID) {
17823                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17824                int oldState = pkgSetting.getEnabled(userId);
17825                if (className == null
17826                    &&
17827                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17828                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17829                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17830                    &&
17831                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17832                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17833                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17834                    // ok
17835                } else {
17836                    throw new SecurityException(
17837                            "Shell cannot change component state for " + packageName + "/"
17838                            + className + " to " + newState);
17839                }
17840            }
17841            if (className == null) {
17842                // We're dealing with an application/package level state change
17843                if (pkgSetting.getEnabled(userId) == newState) {
17844                    // Nothing to do
17845                    return;
17846                }
17847                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17848                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17849                    // Don't care about who enables an app.
17850                    callingPackage = null;
17851                }
17852                pkgSetting.setEnabled(newState, userId, callingPackage);
17853                // pkgSetting.pkg.mSetEnabled = newState;
17854            } else {
17855                // We're dealing with a component level state change
17856                // First, verify that this is a valid class name.
17857                PackageParser.Package pkg = pkgSetting.pkg;
17858                if (pkg == null || !pkg.hasComponentClassName(className)) {
17859                    if (pkg != null &&
17860                            pkg.applicationInfo.targetSdkVersion >=
17861                                    Build.VERSION_CODES.JELLY_BEAN) {
17862                        throw new IllegalArgumentException("Component class " + className
17863                                + " does not exist in " + packageName);
17864                    } else {
17865                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17866                                + className + " does not exist in " + packageName);
17867                    }
17868                }
17869                switch (newState) {
17870                case COMPONENT_ENABLED_STATE_ENABLED:
17871                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17872                        return;
17873                    }
17874                    break;
17875                case COMPONENT_ENABLED_STATE_DISABLED:
17876                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17877                        return;
17878                    }
17879                    break;
17880                case COMPONENT_ENABLED_STATE_DEFAULT:
17881                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17882                        return;
17883                    }
17884                    break;
17885                default:
17886                    Slog.e(TAG, "Invalid new component state: " + newState);
17887                    return;
17888                }
17889            }
17890            scheduleWritePackageRestrictionsLocked(userId);
17891            components = mPendingBroadcasts.get(userId, packageName);
17892            final boolean newPackage = components == null;
17893            if (newPackage) {
17894                components = new ArrayList<String>();
17895            }
17896            if (!components.contains(componentName)) {
17897                components.add(componentName);
17898            }
17899            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17900                sendNow = true;
17901                // Purge entry from pending broadcast list if another one exists already
17902                // since we are sending one right away.
17903                mPendingBroadcasts.remove(userId, packageName);
17904            } else {
17905                if (newPackage) {
17906                    mPendingBroadcasts.put(userId, packageName, components);
17907                }
17908                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17909                    // Schedule a message
17910                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17911                }
17912            }
17913        }
17914
17915        long callingId = Binder.clearCallingIdentity();
17916        try {
17917            if (sendNow) {
17918                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17919                sendPackageChangedBroadcast(packageName,
17920                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17921            }
17922        } finally {
17923            Binder.restoreCallingIdentity(callingId);
17924        }
17925    }
17926
17927    @Override
17928    public void flushPackageRestrictionsAsUser(int userId) {
17929        if (!sUserManager.exists(userId)) {
17930            return;
17931        }
17932        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17933                false /* checkShell */, "flushPackageRestrictions");
17934        synchronized (mPackages) {
17935            mSettings.writePackageRestrictionsLPr(userId);
17936            mDirtyUsers.remove(userId);
17937            if (mDirtyUsers.isEmpty()) {
17938                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17939            }
17940        }
17941    }
17942
17943    private void sendPackageChangedBroadcast(String packageName,
17944            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17945        if (DEBUG_INSTALL)
17946            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17947                    + componentNames);
17948        Bundle extras = new Bundle(4);
17949        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17950        String nameList[] = new String[componentNames.size()];
17951        componentNames.toArray(nameList);
17952        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17953        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17954        extras.putInt(Intent.EXTRA_UID, packageUid);
17955        // If this is not reporting a change of the overall package, then only send it
17956        // to registered receivers.  We don't want to launch a swath of apps for every
17957        // little component state change.
17958        final int flags = !componentNames.contains(packageName)
17959                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17960        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17961                new int[] {UserHandle.getUserId(packageUid)});
17962    }
17963
17964    @Override
17965    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17966        if (!sUserManager.exists(userId)) return;
17967        final int uid = Binder.getCallingUid();
17968        final int permission = mContext.checkCallingOrSelfPermission(
17969                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17970        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17971        enforceCrossUserPermission(uid, userId,
17972                true /* requireFullPermission */, true /* checkShell */, "stop package");
17973        // writer
17974        synchronized (mPackages) {
17975            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17976                    allowedByPermission, uid, userId)) {
17977                scheduleWritePackageRestrictionsLocked(userId);
17978            }
17979        }
17980    }
17981
17982    @Override
17983    public String getInstallerPackageName(String packageName) {
17984        // reader
17985        synchronized (mPackages) {
17986            return mSettings.getInstallerPackageNameLPr(packageName);
17987        }
17988    }
17989
17990    public boolean isOrphaned(String packageName) {
17991        // reader
17992        synchronized (mPackages) {
17993            return mSettings.isOrphaned(packageName);
17994        }
17995    }
17996
17997    @Override
17998    public int getApplicationEnabledSetting(String packageName, int userId) {
17999        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18000        int uid = Binder.getCallingUid();
18001        enforceCrossUserPermission(uid, userId,
18002                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18003        // reader
18004        synchronized (mPackages) {
18005            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18006        }
18007    }
18008
18009    @Override
18010    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18011        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18012        int uid = Binder.getCallingUid();
18013        enforceCrossUserPermission(uid, userId,
18014                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18015        // reader
18016        synchronized (mPackages) {
18017            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18018        }
18019    }
18020
18021    @Override
18022    public void enterSafeMode() {
18023        enforceSystemOrRoot("Only the system can request entering safe mode");
18024
18025        if (!mSystemReady) {
18026            mSafeMode = true;
18027        }
18028    }
18029
18030    @Override
18031    public void systemReady() {
18032        mSystemReady = true;
18033
18034        // Read the compatibilty setting when the system is ready.
18035        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18036                mContext.getContentResolver(),
18037                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18038        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18039        if (DEBUG_SETTINGS) {
18040            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18041        }
18042
18043        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18044
18045        synchronized (mPackages) {
18046            // Verify that all of the preferred activity components actually
18047            // exist.  It is possible for applications to be updated and at
18048            // that point remove a previously declared activity component that
18049            // had been set as a preferred activity.  We try to clean this up
18050            // the next time we encounter that preferred activity, but it is
18051            // possible for the user flow to never be able to return to that
18052            // situation so here we do a sanity check to make sure we haven't
18053            // left any junk around.
18054            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18055            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18056                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18057                removed.clear();
18058                for (PreferredActivity pa : pir.filterSet()) {
18059                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18060                        removed.add(pa);
18061                    }
18062                }
18063                if (removed.size() > 0) {
18064                    for (int r=0; r<removed.size(); r++) {
18065                        PreferredActivity pa = removed.get(r);
18066                        Slog.w(TAG, "Removing dangling preferred activity: "
18067                                + pa.mPref.mComponent);
18068                        pir.removeFilter(pa);
18069                    }
18070                    mSettings.writePackageRestrictionsLPr(
18071                            mSettings.mPreferredActivities.keyAt(i));
18072                }
18073            }
18074
18075            for (int userId : UserManagerService.getInstance().getUserIds()) {
18076                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18077                    grantPermissionsUserIds = ArrayUtils.appendInt(
18078                            grantPermissionsUserIds, userId);
18079                }
18080            }
18081        }
18082        sUserManager.systemReady();
18083
18084        // If we upgraded grant all default permissions before kicking off.
18085        for (int userId : grantPermissionsUserIds) {
18086            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18087        }
18088
18089        // Kick off any messages waiting for system ready
18090        if (mPostSystemReadyMessages != null) {
18091            for (Message msg : mPostSystemReadyMessages) {
18092                msg.sendToTarget();
18093            }
18094            mPostSystemReadyMessages = null;
18095        }
18096
18097        // Watch for external volumes that come and go over time
18098        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18099        storage.registerListener(mStorageListener);
18100
18101        mInstallerService.systemReady();
18102        mPackageDexOptimizer.systemReady();
18103
18104        MountServiceInternal mountServiceInternal = LocalServices.getService(
18105                MountServiceInternal.class);
18106        mountServiceInternal.addExternalStoragePolicy(
18107                new MountServiceInternal.ExternalStorageMountPolicy() {
18108            @Override
18109            public int getMountMode(int uid, String packageName) {
18110                if (Process.isIsolated(uid)) {
18111                    return Zygote.MOUNT_EXTERNAL_NONE;
18112                }
18113                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18114                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18115                }
18116                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18117                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18118                }
18119                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18120                    return Zygote.MOUNT_EXTERNAL_READ;
18121                }
18122                return Zygote.MOUNT_EXTERNAL_WRITE;
18123            }
18124
18125            @Override
18126            public boolean hasExternalStorage(int uid, String packageName) {
18127                return true;
18128            }
18129        });
18130
18131        // Now that we're mostly running, clean up stale users and apps
18132        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18133        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18134    }
18135
18136    @Override
18137    public boolean isSafeMode() {
18138        return mSafeMode;
18139    }
18140
18141    @Override
18142    public boolean hasSystemUidErrors() {
18143        return mHasSystemUidErrors;
18144    }
18145
18146    static String arrayToString(int[] array) {
18147        StringBuffer buf = new StringBuffer(128);
18148        buf.append('[');
18149        if (array != null) {
18150            for (int i=0; i<array.length; i++) {
18151                if (i > 0) buf.append(", ");
18152                buf.append(array[i]);
18153            }
18154        }
18155        buf.append(']');
18156        return buf.toString();
18157    }
18158
18159    static class DumpState {
18160        public static final int DUMP_LIBS = 1 << 0;
18161        public static final int DUMP_FEATURES = 1 << 1;
18162        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18163        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18164        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18165        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18166        public static final int DUMP_PERMISSIONS = 1 << 6;
18167        public static final int DUMP_PACKAGES = 1 << 7;
18168        public static final int DUMP_SHARED_USERS = 1 << 8;
18169        public static final int DUMP_MESSAGES = 1 << 9;
18170        public static final int DUMP_PROVIDERS = 1 << 10;
18171        public static final int DUMP_VERIFIERS = 1 << 11;
18172        public static final int DUMP_PREFERRED = 1 << 12;
18173        public static final int DUMP_PREFERRED_XML = 1 << 13;
18174        public static final int DUMP_KEYSETS = 1 << 14;
18175        public static final int DUMP_VERSION = 1 << 15;
18176        public static final int DUMP_INSTALLS = 1 << 16;
18177        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18178        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18179        public static final int DUMP_FROZEN = 1 << 19;
18180        public static final int DUMP_DEXOPT = 1 << 20;
18181
18182        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18183
18184        private int mTypes;
18185
18186        private int mOptions;
18187
18188        private boolean mTitlePrinted;
18189
18190        private SharedUserSetting mSharedUser;
18191
18192        public boolean isDumping(int type) {
18193            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18194                return true;
18195            }
18196
18197            return (mTypes & type) != 0;
18198        }
18199
18200        public void setDump(int type) {
18201            mTypes |= type;
18202        }
18203
18204        public boolean isOptionEnabled(int option) {
18205            return (mOptions & option) != 0;
18206        }
18207
18208        public void setOptionEnabled(int option) {
18209            mOptions |= option;
18210        }
18211
18212        public boolean onTitlePrinted() {
18213            final boolean printed = mTitlePrinted;
18214            mTitlePrinted = true;
18215            return printed;
18216        }
18217
18218        public boolean getTitlePrinted() {
18219            return mTitlePrinted;
18220        }
18221
18222        public void setTitlePrinted(boolean enabled) {
18223            mTitlePrinted = enabled;
18224        }
18225
18226        public SharedUserSetting getSharedUser() {
18227            return mSharedUser;
18228        }
18229
18230        public void setSharedUser(SharedUserSetting user) {
18231            mSharedUser = user;
18232        }
18233    }
18234
18235    @Override
18236    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18237            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18238        (new PackageManagerShellCommand(this)).exec(
18239                this, in, out, err, args, resultReceiver);
18240    }
18241
18242    @Override
18243    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18244        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18245                != PackageManager.PERMISSION_GRANTED) {
18246            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18247                    + Binder.getCallingPid()
18248                    + ", uid=" + Binder.getCallingUid()
18249                    + " without permission "
18250                    + android.Manifest.permission.DUMP);
18251            return;
18252        }
18253
18254        DumpState dumpState = new DumpState();
18255        boolean fullPreferred = false;
18256        boolean checkin = false;
18257
18258        String packageName = null;
18259        ArraySet<String> permissionNames = null;
18260
18261        int opti = 0;
18262        while (opti < args.length) {
18263            String opt = args[opti];
18264            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18265                break;
18266            }
18267            opti++;
18268
18269            if ("-a".equals(opt)) {
18270                // Right now we only know how to print all.
18271            } else if ("-h".equals(opt)) {
18272                pw.println("Package manager dump options:");
18273                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18274                pw.println("    --checkin: dump for a checkin");
18275                pw.println("    -f: print details of intent filters");
18276                pw.println("    -h: print this help");
18277                pw.println("  cmd may be one of:");
18278                pw.println("    l[ibraries]: list known shared libraries");
18279                pw.println("    f[eatures]: list device features");
18280                pw.println("    k[eysets]: print known keysets");
18281                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18282                pw.println("    perm[issions]: dump permissions");
18283                pw.println("    permission [name ...]: dump declaration and use of given permission");
18284                pw.println("    pref[erred]: print preferred package settings");
18285                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18286                pw.println("    prov[iders]: dump content providers");
18287                pw.println("    p[ackages]: dump installed packages");
18288                pw.println("    s[hared-users]: dump shared user IDs");
18289                pw.println("    m[essages]: print collected runtime messages");
18290                pw.println("    v[erifiers]: print package verifier info");
18291                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18292                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18293                pw.println("    version: print database version info");
18294                pw.println("    write: write current settings now");
18295                pw.println("    installs: details about install sessions");
18296                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18297                pw.println("    dexopt: dump dexopt state");
18298                pw.println("    <package.name>: info about given package");
18299                return;
18300            } else if ("--checkin".equals(opt)) {
18301                checkin = true;
18302            } else if ("-f".equals(opt)) {
18303                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18304            } else {
18305                pw.println("Unknown argument: " + opt + "; use -h for help");
18306            }
18307        }
18308
18309        // Is the caller requesting to dump a particular piece of data?
18310        if (opti < args.length) {
18311            String cmd = args[opti];
18312            opti++;
18313            // Is this a package name?
18314            if ("android".equals(cmd) || cmd.contains(".")) {
18315                packageName = cmd;
18316                // When dumping a single package, we always dump all of its
18317                // filter information since the amount of data will be reasonable.
18318                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18319            } else if ("check-permission".equals(cmd)) {
18320                if (opti >= args.length) {
18321                    pw.println("Error: check-permission missing permission argument");
18322                    return;
18323                }
18324                String perm = args[opti];
18325                opti++;
18326                if (opti >= args.length) {
18327                    pw.println("Error: check-permission missing package argument");
18328                    return;
18329                }
18330                String pkg = args[opti];
18331                opti++;
18332                int user = UserHandle.getUserId(Binder.getCallingUid());
18333                if (opti < args.length) {
18334                    try {
18335                        user = Integer.parseInt(args[opti]);
18336                    } catch (NumberFormatException e) {
18337                        pw.println("Error: check-permission user argument is not a number: "
18338                                + args[opti]);
18339                        return;
18340                    }
18341                }
18342                pw.println(checkPermission(perm, pkg, user));
18343                return;
18344            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18345                dumpState.setDump(DumpState.DUMP_LIBS);
18346            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18347                dumpState.setDump(DumpState.DUMP_FEATURES);
18348            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18349                if (opti >= args.length) {
18350                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18351                            | DumpState.DUMP_SERVICE_RESOLVERS
18352                            | DumpState.DUMP_RECEIVER_RESOLVERS
18353                            | DumpState.DUMP_CONTENT_RESOLVERS);
18354                } else {
18355                    while (opti < args.length) {
18356                        String name = args[opti];
18357                        if ("a".equals(name) || "activity".equals(name)) {
18358                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18359                        } else if ("s".equals(name) || "service".equals(name)) {
18360                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18361                        } else if ("r".equals(name) || "receiver".equals(name)) {
18362                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18363                        } else if ("c".equals(name) || "content".equals(name)) {
18364                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18365                        } else {
18366                            pw.println("Error: unknown resolver table type: " + name);
18367                            return;
18368                        }
18369                        opti++;
18370                    }
18371                }
18372            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18373                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18374            } else if ("permission".equals(cmd)) {
18375                if (opti >= args.length) {
18376                    pw.println("Error: permission requires permission name");
18377                    return;
18378                }
18379                permissionNames = new ArraySet<>();
18380                while (opti < args.length) {
18381                    permissionNames.add(args[opti]);
18382                    opti++;
18383                }
18384                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18385                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18386            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18387                dumpState.setDump(DumpState.DUMP_PREFERRED);
18388            } else if ("preferred-xml".equals(cmd)) {
18389                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18390                if (opti < args.length && "--full".equals(args[opti])) {
18391                    fullPreferred = true;
18392                    opti++;
18393                }
18394            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18395                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18396            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18397                dumpState.setDump(DumpState.DUMP_PACKAGES);
18398            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18399                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18400            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18401                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18402            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18403                dumpState.setDump(DumpState.DUMP_MESSAGES);
18404            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18405                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18406            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18407                    || "intent-filter-verifiers".equals(cmd)) {
18408                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18409            } else if ("version".equals(cmd)) {
18410                dumpState.setDump(DumpState.DUMP_VERSION);
18411            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18412                dumpState.setDump(DumpState.DUMP_KEYSETS);
18413            } else if ("installs".equals(cmd)) {
18414                dumpState.setDump(DumpState.DUMP_INSTALLS);
18415            } else if ("frozen".equals(cmd)) {
18416                dumpState.setDump(DumpState.DUMP_FROZEN);
18417            } else if ("dexopt".equals(cmd)) {
18418                dumpState.setDump(DumpState.DUMP_DEXOPT);
18419            } else if ("write".equals(cmd)) {
18420                synchronized (mPackages) {
18421                    mSettings.writeLPr();
18422                    pw.println("Settings written.");
18423                    return;
18424                }
18425            }
18426        }
18427
18428        if (checkin) {
18429            pw.println("vers,1");
18430        }
18431
18432        // reader
18433        synchronized (mPackages) {
18434            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18435                if (!checkin) {
18436                    if (dumpState.onTitlePrinted())
18437                        pw.println();
18438                    pw.println("Database versions:");
18439                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18440                }
18441            }
18442
18443            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18444                if (!checkin) {
18445                    if (dumpState.onTitlePrinted())
18446                        pw.println();
18447                    pw.println("Verifiers:");
18448                    pw.print("  Required: ");
18449                    pw.print(mRequiredVerifierPackage);
18450                    pw.print(" (uid=");
18451                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18452                            UserHandle.USER_SYSTEM));
18453                    pw.println(")");
18454                } else if (mRequiredVerifierPackage != null) {
18455                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18456                    pw.print(",");
18457                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18458                            UserHandle.USER_SYSTEM));
18459                }
18460            }
18461
18462            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18463                    packageName == null) {
18464                if (mIntentFilterVerifierComponent != null) {
18465                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18466                    if (!checkin) {
18467                        if (dumpState.onTitlePrinted())
18468                            pw.println();
18469                        pw.println("Intent Filter Verifier:");
18470                        pw.print("  Using: ");
18471                        pw.print(verifierPackageName);
18472                        pw.print(" (uid=");
18473                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18474                                UserHandle.USER_SYSTEM));
18475                        pw.println(")");
18476                    } else if (verifierPackageName != null) {
18477                        pw.print("ifv,"); pw.print(verifierPackageName);
18478                        pw.print(",");
18479                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18480                                UserHandle.USER_SYSTEM));
18481                    }
18482                } else {
18483                    pw.println();
18484                    pw.println("No Intent Filter Verifier available!");
18485                }
18486            }
18487
18488            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18489                boolean printedHeader = false;
18490                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18491                while (it.hasNext()) {
18492                    String name = it.next();
18493                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18494                    if (!checkin) {
18495                        if (!printedHeader) {
18496                            if (dumpState.onTitlePrinted())
18497                                pw.println();
18498                            pw.println("Libraries:");
18499                            printedHeader = true;
18500                        }
18501                        pw.print("  ");
18502                    } else {
18503                        pw.print("lib,");
18504                    }
18505                    pw.print(name);
18506                    if (!checkin) {
18507                        pw.print(" -> ");
18508                    }
18509                    if (ent.path != null) {
18510                        if (!checkin) {
18511                            pw.print("(jar) ");
18512                            pw.print(ent.path);
18513                        } else {
18514                            pw.print(",jar,");
18515                            pw.print(ent.path);
18516                        }
18517                    } else {
18518                        if (!checkin) {
18519                            pw.print("(apk) ");
18520                            pw.print(ent.apk);
18521                        } else {
18522                            pw.print(",apk,");
18523                            pw.print(ent.apk);
18524                        }
18525                    }
18526                    pw.println();
18527                }
18528            }
18529
18530            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18531                if (dumpState.onTitlePrinted())
18532                    pw.println();
18533                if (!checkin) {
18534                    pw.println("Features:");
18535                }
18536
18537                for (FeatureInfo feat : mAvailableFeatures.values()) {
18538                    if (checkin) {
18539                        pw.print("feat,");
18540                        pw.print(feat.name);
18541                        pw.print(",");
18542                        pw.println(feat.version);
18543                    } else {
18544                        pw.print("  ");
18545                        pw.print(feat.name);
18546                        if (feat.version > 0) {
18547                            pw.print(" version=");
18548                            pw.print(feat.version);
18549                        }
18550                        pw.println();
18551                    }
18552                }
18553            }
18554
18555            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18556                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18557                        : "Activity Resolver Table:", "  ", packageName,
18558                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18559                    dumpState.setTitlePrinted(true);
18560                }
18561            }
18562            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18563                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18564                        : "Receiver Resolver Table:", "  ", packageName,
18565                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18566                    dumpState.setTitlePrinted(true);
18567                }
18568            }
18569            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18570                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18571                        : "Service Resolver Table:", "  ", packageName,
18572                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18573                    dumpState.setTitlePrinted(true);
18574                }
18575            }
18576            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18577                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18578                        : "Provider Resolver Table:", "  ", packageName,
18579                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18580                    dumpState.setTitlePrinted(true);
18581                }
18582            }
18583
18584            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18585                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18586                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18587                    int user = mSettings.mPreferredActivities.keyAt(i);
18588                    if (pir.dump(pw,
18589                            dumpState.getTitlePrinted()
18590                                ? "\nPreferred Activities User " + user + ":"
18591                                : "Preferred Activities User " + user + ":", "  ",
18592                            packageName, true, false)) {
18593                        dumpState.setTitlePrinted(true);
18594                    }
18595                }
18596            }
18597
18598            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18599                pw.flush();
18600                FileOutputStream fout = new FileOutputStream(fd);
18601                BufferedOutputStream str = new BufferedOutputStream(fout);
18602                XmlSerializer serializer = new FastXmlSerializer();
18603                try {
18604                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18605                    serializer.startDocument(null, true);
18606                    serializer.setFeature(
18607                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18608                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18609                    serializer.endDocument();
18610                    serializer.flush();
18611                } catch (IllegalArgumentException e) {
18612                    pw.println("Failed writing: " + e);
18613                } catch (IllegalStateException e) {
18614                    pw.println("Failed writing: " + e);
18615                } catch (IOException e) {
18616                    pw.println("Failed writing: " + e);
18617                }
18618            }
18619
18620            if (!checkin
18621                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18622                    && packageName == null) {
18623                pw.println();
18624                int count = mSettings.mPackages.size();
18625                if (count == 0) {
18626                    pw.println("No applications!");
18627                    pw.println();
18628                } else {
18629                    final String prefix = "  ";
18630                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18631                    if (allPackageSettings.size() == 0) {
18632                        pw.println("No domain preferred apps!");
18633                        pw.println();
18634                    } else {
18635                        pw.println("App verification status:");
18636                        pw.println();
18637                        count = 0;
18638                        for (PackageSetting ps : allPackageSettings) {
18639                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18640                            if (ivi == null || ivi.getPackageName() == null) continue;
18641                            pw.println(prefix + "Package: " + ivi.getPackageName());
18642                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18643                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18644                            pw.println();
18645                            count++;
18646                        }
18647                        if (count == 0) {
18648                            pw.println(prefix + "No app verification established.");
18649                            pw.println();
18650                        }
18651                        for (int userId : sUserManager.getUserIds()) {
18652                            pw.println("App linkages for user " + userId + ":");
18653                            pw.println();
18654                            count = 0;
18655                            for (PackageSetting ps : allPackageSettings) {
18656                                final long status = ps.getDomainVerificationStatusForUser(userId);
18657                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18658                                    continue;
18659                                }
18660                                pw.println(prefix + "Package: " + ps.name);
18661                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18662                                String statusStr = IntentFilterVerificationInfo.
18663                                        getStatusStringFromValue(status);
18664                                pw.println(prefix + "Status:  " + statusStr);
18665                                pw.println();
18666                                count++;
18667                            }
18668                            if (count == 0) {
18669                                pw.println(prefix + "No configured app linkages.");
18670                                pw.println();
18671                            }
18672                        }
18673                    }
18674                }
18675            }
18676
18677            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18678                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18679                if (packageName == null && permissionNames == null) {
18680                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18681                        if (iperm == 0) {
18682                            if (dumpState.onTitlePrinted())
18683                                pw.println();
18684                            pw.println("AppOp Permissions:");
18685                        }
18686                        pw.print("  AppOp Permission ");
18687                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18688                        pw.println(":");
18689                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18690                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18691                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18692                        }
18693                    }
18694                }
18695            }
18696
18697            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18698                boolean printedSomething = false;
18699                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18700                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18701                        continue;
18702                    }
18703                    if (!printedSomething) {
18704                        if (dumpState.onTitlePrinted())
18705                            pw.println();
18706                        pw.println("Registered ContentProviders:");
18707                        printedSomething = true;
18708                    }
18709                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18710                    pw.print("    "); pw.println(p.toString());
18711                }
18712                printedSomething = false;
18713                for (Map.Entry<String, PackageParser.Provider> entry :
18714                        mProvidersByAuthority.entrySet()) {
18715                    PackageParser.Provider p = entry.getValue();
18716                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18717                        continue;
18718                    }
18719                    if (!printedSomething) {
18720                        if (dumpState.onTitlePrinted())
18721                            pw.println();
18722                        pw.println("ContentProvider Authorities:");
18723                        printedSomething = true;
18724                    }
18725                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18726                    pw.print("    "); pw.println(p.toString());
18727                    if (p.info != null && p.info.applicationInfo != null) {
18728                        final String appInfo = p.info.applicationInfo.toString();
18729                        pw.print("      applicationInfo="); pw.println(appInfo);
18730                    }
18731                }
18732            }
18733
18734            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18735                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18736            }
18737
18738            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18739                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18740            }
18741
18742            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18743                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18744            }
18745
18746            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18747                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18748            }
18749
18750            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18751                // XXX should handle packageName != null by dumping only install data that
18752                // the given package is involved with.
18753                if (dumpState.onTitlePrinted()) pw.println();
18754                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18755            }
18756
18757            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18758                // XXX should handle packageName != null by dumping only install data that
18759                // the given package is involved with.
18760                if (dumpState.onTitlePrinted()) pw.println();
18761
18762                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18763                ipw.println();
18764                ipw.println("Frozen packages:");
18765                ipw.increaseIndent();
18766                if (mFrozenPackages.size() == 0) {
18767                    ipw.println("(none)");
18768                } else {
18769                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18770                        ipw.println(mFrozenPackages.valueAt(i));
18771                    }
18772                }
18773                ipw.decreaseIndent();
18774            }
18775
18776            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18777                if (dumpState.onTitlePrinted()) pw.println();
18778                dumpDexoptStateLPr(pw, packageName);
18779            }
18780
18781            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18782                if (dumpState.onTitlePrinted()) pw.println();
18783                mSettings.dumpReadMessagesLPr(pw, dumpState);
18784
18785                pw.println();
18786                pw.println("Package warning messages:");
18787                BufferedReader in = null;
18788                String line = null;
18789                try {
18790                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18791                    while ((line = in.readLine()) != null) {
18792                        if (line.contains("ignored: updated version")) continue;
18793                        pw.println(line);
18794                    }
18795                } catch (IOException ignored) {
18796                } finally {
18797                    IoUtils.closeQuietly(in);
18798                }
18799            }
18800
18801            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18802                BufferedReader in = null;
18803                String line = null;
18804                try {
18805                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18806                    while ((line = in.readLine()) != null) {
18807                        if (line.contains("ignored: updated version")) continue;
18808                        pw.print("msg,");
18809                        pw.println(line);
18810                    }
18811                } catch (IOException ignored) {
18812                } finally {
18813                    IoUtils.closeQuietly(in);
18814                }
18815            }
18816        }
18817    }
18818
18819    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18820        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18821        ipw.println();
18822        ipw.println("Dexopt state:");
18823        ipw.increaseIndent();
18824        Collection<PackageParser.Package> packages = null;
18825        if (packageName != null) {
18826            PackageParser.Package targetPackage = mPackages.get(packageName);
18827            if (targetPackage != null) {
18828                packages = Collections.singletonList(targetPackage);
18829            } else {
18830                ipw.println("Unable to find package: " + packageName);
18831                return;
18832            }
18833        } else {
18834            packages = mPackages.values();
18835        }
18836
18837        for (PackageParser.Package pkg : packages) {
18838            ipw.println("[" + pkg.packageName + "]");
18839            ipw.increaseIndent();
18840            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18841            ipw.decreaseIndent();
18842        }
18843    }
18844
18845    private String dumpDomainString(String packageName) {
18846        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18847                .getList();
18848        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18849
18850        ArraySet<String> result = new ArraySet<>();
18851        if (iviList.size() > 0) {
18852            for (IntentFilterVerificationInfo ivi : iviList) {
18853                for (String host : ivi.getDomains()) {
18854                    result.add(host);
18855                }
18856            }
18857        }
18858        if (filters != null && filters.size() > 0) {
18859            for (IntentFilter filter : filters) {
18860                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18861                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18862                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18863                    result.addAll(filter.getHostsList());
18864                }
18865            }
18866        }
18867
18868        StringBuilder sb = new StringBuilder(result.size() * 16);
18869        for (String domain : result) {
18870            if (sb.length() > 0) sb.append(" ");
18871            sb.append(domain);
18872        }
18873        return sb.toString();
18874    }
18875
18876    // ------- apps on sdcard specific code -------
18877    static final boolean DEBUG_SD_INSTALL = false;
18878
18879    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18880
18881    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18882
18883    private boolean mMediaMounted = false;
18884
18885    static String getEncryptKey() {
18886        try {
18887            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18888                    SD_ENCRYPTION_KEYSTORE_NAME);
18889            if (sdEncKey == null) {
18890                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18891                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18892                if (sdEncKey == null) {
18893                    Slog.e(TAG, "Failed to create encryption keys");
18894                    return null;
18895                }
18896            }
18897            return sdEncKey;
18898        } catch (NoSuchAlgorithmException nsae) {
18899            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18900            return null;
18901        } catch (IOException ioe) {
18902            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18903            return null;
18904        }
18905    }
18906
18907    /*
18908     * Update media status on PackageManager.
18909     */
18910    @Override
18911    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18912        int callingUid = Binder.getCallingUid();
18913        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18914            throw new SecurityException("Media status can only be updated by the system");
18915        }
18916        // reader; this apparently protects mMediaMounted, but should probably
18917        // be a different lock in that case.
18918        synchronized (mPackages) {
18919            Log.i(TAG, "Updating external media status from "
18920                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18921                    + (mediaStatus ? "mounted" : "unmounted"));
18922            if (DEBUG_SD_INSTALL)
18923                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18924                        + ", mMediaMounted=" + mMediaMounted);
18925            if (mediaStatus == mMediaMounted) {
18926                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18927                        : 0, -1);
18928                mHandler.sendMessage(msg);
18929                return;
18930            }
18931            mMediaMounted = mediaStatus;
18932        }
18933        // Queue up an async operation since the package installation may take a
18934        // little while.
18935        mHandler.post(new Runnable() {
18936            public void run() {
18937                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18938            }
18939        });
18940    }
18941
18942    /**
18943     * Called by MountService when the initial ASECs to scan are available.
18944     * Should block until all the ASEC containers are finished being scanned.
18945     */
18946    public void scanAvailableAsecs() {
18947        updateExternalMediaStatusInner(true, false, false);
18948    }
18949
18950    /*
18951     * Collect information of applications on external media, map them against
18952     * existing containers and update information based on current mount status.
18953     * Please note that we always have to report status if reportStatus has been
18954     * set to true especially when unloading packages.
18955     */
18956    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18957            boolean externalStorage) {
18958        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18959        int[] uidArr = EmptyArray.INT;
18960
18961        final String[] list = PackageHelper.getSecureContainerList();
18962        if (ArrayUtils.isEmpty(list)) {
18963            Log.i(TAG, "No secure containers found");
18964        } else {
18965            // Process list of secure containers and categorize them
18966            // as active or stale based on their package internal state.
18967
18968            // reader
18969            synchronized (mPackages) {
18970                for (String cid : list) {
18971                    // Leave stages untouched for now; installer service owns them
18972                    if (PackageInstallerService.isStageName(cid)) continue;
18973
18974                    if (DEBUG_SD_INSTALL)
18975                        Log.i(TAG, "Processing container " + cid);
18976                    String pkgName = getAsecPackageName(cid);
18977                    if (pkgName == null) {
18978                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18979                        continue;
18980                    }
18981                    if (DEBUG_SD_INSTALL)
18982                        Log.i(TAG, "Looking for pkg : " + pkgName);
18983
18984                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18985                    if (ps == null) {
18986                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18987                        continue;
18988                    }
18989
18990                    /*
18991                     * Skip packages that are not external if we're unmounting
18992                     * external storage.
18993                     */
18994                    if (externalStorage && !isMounted && !isExternal(ps)) {
18995                        continue;
18996                    }
18997
18998                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18999                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19000                    // The package status is changed only if the code path
19001                    // matches between settings and the container id.
19002                    if (ps.codePathString != null
19003                            && ps.codePathString.startsWith(args.getCodePath())) {
19004                        if (DEBUG_SD_INSTALL) {
19005                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19006                                    + " at code path: " + ps.codePathString);
19007                        }
19008
19009                        // We do have a valid package installed on sdcard
19010                        processCids.put(args, ps.codePathString);
19011                        final int uid = ps.appId;
19012                        if (uid != -1) {
19013                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19014                        }
19015                    } else {
19016                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19017                                + ps.codePathString);
19018                    }
19019                }
19020            }
19021
19022            Arrays.sort(uidArr);
19023        }
19024
19025        // Process packages with valid entries.
19026        if (isMounted) {
19027            if (DEBUG_SD_INSTALL)
19028                Log.i(TAG, "Loading packages");
19029            loadMediaPackages(processCids, uidArr, externalStorage);
19030            startCleaningPackages();
19031            mInstallerService.onSecureContainersAvailable();
19032        } else {
19033            if (DEBUG_SD_INSTALL)
19034                Log.i(TAG, "Unloading packages");
19035            unloadMediaPackages(processCids, uidArr, reportStatus);
19036        }
19037    }
19038
19039    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19040            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19041        final int size = infos.size();
19042        final String[] packageNames = new String[size];
19043        final int[] packageUids = new int[size];
19044        for (int i = 0; i < size; i++) {
19045            final ApplicationInfo info = infos.get(i);
19046            packageNames[i] = info.packageName;
19047            packageUids[i] = info.uid;
19048        }
19049        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19050                finishedReceiver);
19051    }
19052
19053    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19054            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19055        sendResourcesChangedBroadcast(mediaStatus, replacing,
19056                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19057    }
19058
19059    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19060            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19061        int size = pkgList.length;
19062        if (size > 0) {
19063            // Send broadcasts here
19064            Bundle extras = new Bundle();
19065            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19066            if (uidArr != null) {
19067                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19068            }
19069            if (replacing) {
19070                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19071            }
19072            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19073                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19074            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19075        }
19076    }
19077
19078   /*
19079     * Look at potentially valid container ids from processCids If package
19080     * information doesn't match the one on record or package scanning fails,
19081     * the cid is added to list of removeCids. We currently don't delete stale
19082     * containers.
19083     */
19084    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19085            boolean externalStorage) {
19086        ArrayList<String> pkgList = new ArrayList<String>();
19087        Set<AsecInstallArgs> keys = processCids.keySet();
19088
19089        for (AsecInstallArgs args : keys) {
19090            String codePath = processCids.get(args);
19091            if (DEBUG_SD_INSTALL)
19092                Log.i(TAG, "Loading container : " + args.cid);
19093            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19094            try {
19095                // Make sure there are no container errors first.
19096                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19097                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19098                            + " when installing from sdcard");
19099                    continue;
19100                }
19101                // Check code path here.
19102                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19103                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19104                            + " does not match one in settings " + codePath);
19105                    continue;
19106                }
19107                // Parse package
19108                int parseFlags = mDefParseFlags;
19109                if (args.isExternalAsec()) {
19110                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19111                }
19112                if (args.isFwdLocked()) {
19113                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19114                }
19115
19116                synchronized (mInstallLock) {
19117                    PackageParser.Package pkg = null;
19118                    try {
19119                        // Sadly we don't know the package name yet to freeze it
19120                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19121                                SCAN_IGNORE_FROZEN, 0, null);
19122                    } catch (PackageManagerException e) {
19123                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19124                    }
19125                    // Scan the package
19126                    if (pkg != null) {
19127                        /*
19128                         * TODO why is the lock being held? doPostInstall is
19129                         * called in other places without the lock. This needs
19130                         * to be straightened out.
19131                         */
19132                        // writer
19133                        synchronized (mPackages) {
19134                            retCode = PackageManager.INSTALL_SUCCEEDED;
19135                            pkgList.add(pkg.packageName);
19136                            // Post process args
19137                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19138                                    pkg.applicationInfo.uid);
19139                        }
19140                    } else {
19141                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19142                    }
19143                }
19144
19145            } finally {
19146                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19147                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19148                }
19149            }
19150        }
19151        // writer
19152        synchronized (mPackages) {
19153            // If the platform SDK has changed since the last time we booted,
19154            // we need to re-grant app permission to catch any new ones that
19155            // appear. This is really a hack, and means that apps can in some
19156            // cases get permissions that the user didn't initially explicitly
19157            // allow... it would be nice to have some better way to handle
19158            // this situation.
19159            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19160                    : mSettings.getInternalVersion();
19161            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19162                    : StorageManager.UUID_PRIVATE_INTERNAL;
19163
19164            int updateFlags = UPDATE_PERMISSIONS_ALL;
19165            if (ver.sdkVersion != mSdkVersion) {
19166                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19167                        + mSdkVersion + "; regranting permissions for external");
19168                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19169            }
19170            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19171
19172            // Yay, everything is now upgraded
19173            ver.forceCurrent();
19174
19175            // can downgrade to reader
19176            // Persist settings
19177            mSettings.writeLPr();
19178        }
19179        // Send a broadcast to let everyone know we are done processing
19180        if (pkgList.size() > 0) {
19181            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19182        }
19183    }
19184
19185   /*
19186     * Utility method to unload a list of specified containers
19187     */
19188    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19189        // Just unmount all valid containers.
19190        for (AsecInstallArgs arg : cidArgs) {
19191            synchronized (mInstallLock) {
19192                arg.doPostDeleteLI(false);
19193           }
19194       }
19195   }
19196
19197    /*
19198     * Unload packages mounted on external media. This involves deleting package
19199     * data from internal structures, sending broadcasts about disabled packages,
19200     * gc'ing to free up references, unmounting all secure containers
19201     * corresponding to packages on external media, and posting a
19202     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19203     * that we always have to post this message if status has been requested no
19204     * matter what.
19205     */
19206    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19207            final boolean reportStatus) {
19208        if (DEBUG_SD_INSTALL)
19209            Log.i(TAG, "unloading media packages");
19210        ArrayList<String> pkgList = new ArrayList<String>();
19211        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19212        final Set<AsecInstallArgs> keys = processCids.keySet();
19213        for (AsecInstallArgs args : keys) {
19214            String pkgName = args.getPackageName();
19215            if (DEBUG_SD_INSTALL)
19216                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19217            // Delete package internally
19218            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19219            synchronized (mInstallLock) {
19220                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19221                final boolean res;
19222                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19223                        "unloadMediaPackages")) {
19224                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19225                            null);
19226                }
19227                if (res) {
19228                    pkgList.add(pkgName);
19229                } else {
19230                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19231                    failedList.add(args);
19232                }
19233            }
19234        }
19235
19236        // reader
19237        synchronized (mPackages) {
19238            // We didn't update the settings after removing each package;
19239            // write them now for all packages.
19240            mSettings.writeLPr();
19241        }
19242
19243        // We have to absolutely send UPDATED_MEDIA_STATUS only
19244        // after confirming that all the receivers processed the ordered
19245        // broadcast when packages get disabled, force a gc to clean things up.
19246        // and unload all the containers.
19247        if (pkgList.size() > 0) {
19248            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19249                    new IIntentReceiver.Stub() {
19250                public void performReceive(Intent intent, int resultCode, String data,
19251                        Bundle extras, boolean ordered, boolean sticky,
19252                        int sendingUser) throws RemoteException {
19253                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19254                            reportStatus ? 1 : 0, 1, keys);
19255                    mHandler.sendMessage(msg);
19256                }
19257            });
19258        } else {
19259            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19260                    keys);
19261            mHandler.sendMessage(msg);
19262        }
19263    }
19264
19265    private void loadPrivatePackages(final VolumeInfo vol) {
19266        mHandler.post(new Runnable() {
19267            @Override
19268            public void run() {
19269                loadPrivatePackagesInner(vol);
19270            }
19271        });
19272    }
19273
19274    private void loadPrivatePackagesInner(VolumeInfo vol) {
19275        final String volumeUuid = vol.fsUuid;
19276        if (TextUtils.isEmpty(volumeUuid)) {
19277            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19278            return;
19279        }
19280
19281        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19282        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19283        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19284
19285        final VersionInfo ver;
19286        final List<PackageSetting> packages;
19287        synchronized (mPackages) {
19288            ver = mSettings.findOrCreateVersion(volumeUuid);
19289            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19290        }
19291
19292        for (PackageSetting ps : packages) {
19293            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19294            synchronized (mInstallLock) {
19295                final PackageParser.Package pkg;
19296                try {
19297                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19298                    loaded.add(pkg.applicationInfo);
19299
19300                } catch (PackageManagerException e) {
19301                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19302                }
19303
19304                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19305                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19306                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19307                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19308                }
19309            }
19310        }
19311
19312        // Reconcile app data for all started/unlocked users
19313        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19314        final UserManager um = mContext.getSystemService(UserManager.class);
19315        UserManagerInternal umInternal = getUserManagerInternal();
19316        for (UserInfo user : um.getUsers()) {
19317            final int flags;
19318            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19319                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19320            } else if (umInternal.isUserRunning(user.id)) {
19321                flags = StorageManager.FLAG_STORAGE_DE;
19322            } else {
19323                continue;
19324            }
19325
19326            try {
19327                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19328                synchronized (mInstallLock) {
19329                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19330                }
19331            } catch (IllegalStateException e) {
19332                // Device was probably ejected, and we'll process that event momentarily
19333                Slog.w(TAG, "Failed to prepare storage: " + e);
19334            }
19335        }
19336
19337        synchronized (mPackages) {
19338            int updateFlags = UPDATE_PERMISSIONS_ALL;
19339            if (ver.sdkVersion != mSdkVersion) {
19340                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19341                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19342                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19343            }
19344            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19345
19346            // Yay, everything is now upgraded
19347            ver.forceCurrent();
19348
19349            mSettings.writeLPr();
19350        }
19351
19352        for (PackageFreezer freezer : freezers) {
19353            freezer.close();
19354        }
19355
19356        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19357        sendResourcesChangedBroadcast(true, false, loaded, null);
19358    }
19359
19360    private void unloadPrivatePackages(final VolumeInfo vol) {
19361        mHandler.post(new Runnable() {
19362            @Override
19363            public void run() {
19364                unloadPrivatePackagesInner(vol);
19365            }
19366        });
19367    }
19368
19369    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19370        final String volumeUuid = vol.fsUuid;
19371        if (TextUtils.isEmpty(volumeUuid)) {
19372            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19373            return;
19374        }
19375
19376        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19377        synchronized (mInstallLock) {
19378        synchronized (mPackages) {
19379            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19380            for (PackageSetting ps : packages) {
19381                if (ps.pkg == null) continue;
19382
19383                final ApplicationInfo info = ps.pkg.applicationInfo;
19384                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19385                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19386
19387                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19388                        "unloadPrivatePackagesInner")) {
19389                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19390                            false, null)) {
19391                        unloaded.add(info);
19392                    } else {
19393                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19394                    }
19395                }
19396
19397                // Try very hard to release any references to this package
19398                // so we don't risk the system server being killed due to
19399                // open FDs
19400                AttributeCache.instance().removePackage(ps.name);
19401            }
19402
19403            mSettings.writeLPr();
19404        }
19405        }
19406
19407        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19408        sendResourcesChangedBroadcast(false, false, unloaded, null);
19409
19410        // Try very hard to release any references to this path so we don't risk
19411        // the system server being killed due to open FDs
19412        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19413
19414        for (int i = 0; i < 3; i++) {
19415            System.gc();
19416            System.runFinalization();
19417        }
19418    }
19419
19420    /**
19421     * Prepare storage areas for given user on all mounted devices.
19422     */
19423    void prepareUserData(int userId, int userSerial, int flags) {
19424        synchronized (mInstallLock) {
19425            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19426            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19427                final String volumeUuid = vol.getFsUuid();
19428                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19429            }
19430        }
19431    }
19432
19433    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19434            boolean allowRecover) {
19435        // Prepare storage and verify that serial numbers are consistent; if
19436        // there's a mismatch we need to destroy to avoid leaking data
19437        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19438        try {
19439            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19440
19441            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19442                UserManagerService.enforceSerialNumber(
19443                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19444                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19445                    UserManagerService.enforceSerialNumber(
19446                            Environment.getDataSystemDeDirectory(userId), userSerial);
19447                }
19448            }
19449            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19450                UserManagerService.enforceSerialNumber(
19451                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19452                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19453                    UserManagerService.enforceSerialNumber(
19454                            Environment.getDataSystemCeDirectory(userId), userSerial);
19455                }
19456            }
19457
19458            synchronized (mInstallLock) {
19459                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19460            }
19461        } catch (Exception e) {
19462            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19463                    + " because we failed to prepare: " + e);
19464            destroyUserDataLI(volumeUuid, userId,
19465                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19466
19467            if (allowRecover) {
19468                // Try one last time; if we fail again we're really in trouble
19469                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19470            }
19471        }
19472    }
19473
19474    /**
19475     * Destroy storage areas for given user on all mounted devices.
19476     */
19477    void destroyUserData(int userId, int flags) {
19478        synchronized (mInstallLock) {
19479            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19480            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19481                final String volumeUuid = vol.getFsUuid();
19482                destroyUserDataLI(volumeUuid, userId, flags);
19483            }
19484        }
19485    }
19486
19487    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19488        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19489        try {
19490            // Clean up app data, profile data, and media data
19491            mInstaller.destroyUserData(volumeUuid, userId, flags);
19492
19493            // Clean up system data
19494            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19495                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19496                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19497                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19498                }
19499                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19500                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19501                }
19502            }
19503
19504            // Data with special labels is now gone, so finish the job
19505            storage.destroyUserStorage(volumeUuid, userId, flags);
19506
19507        } catch (Exception e) {
19508            logCriticalInfo(Log.WARN,
19509                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19510        }
19511    }
19512
19513    /**
19514     * Examine all users present on given mounted volume, and destroy data
19515     * belonging to users that are no longer valid, or whose user ID has been
19516     * recycled.
19517     */
19518    private void reconcileUsers(String volumeUuid) {
19519        final List<File> files = new ArrayList<>();
19520        Collections.addAll(files, FileUtils
19521                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19522        Collections.addAll(files, FileUtils
19523                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19524        Collections.addAll(files, FileUtils
19525                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19526        Collections.addAll(files, FileUtils
19527                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19528        for (File file : files) {
19529            if (!file.isDirectory()) continue;
19530
19531            final int userId;
19532            final UserInfo info;
19533            try {
19534                userId = Integer.parseInt(file.getName());
19535                info = sUserManager.getUserInfo(userId);
19536            } catch (NumberFormatException e) {
19537                Slog.w(TAG, "Invalid user directory " + file);
19538                continue;
19539            }
19540
19541            boolean destroyUser = false;
19542            if (info == null) {
19543                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19544                        + " because no matching user was found");
19545                destroyUser = true;
19546            } else if (!mOnlyCore) {
19547                try {
19548                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19549                } catch (IOException e) {
19550                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19551                            + " because we failed to enforce serial number: " + e);
19552                    destroyUser = true;
19553                }
19554            }
19555
19556            if (destroyUser) {
19557                synchronized (mInstallLock) {
19558                    destroyUserDataLI(volumeUuid, userId,
19559                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19560                }
19561            }
19562        }
19563    }
19564
19565    private void assertPackageKnown(String volumeUuid, String packageName)
19566            throws PackageManagerException {
19567        synchronized (mPackages) {
19568            final PackageSetting ps = mSettings.mPackages.get(packageName);
19569            if (ps == null) {
19570                throw new PackageManagerException("Package " + packageName + " is unknown");
19571            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19572                throw new PackageManagerException(
19573                        "Package " + packageName + " found on unknown volume " + volumeUuid
19574                                + "; expected volume " + ps.volumeUuid);
19575            }
19576        }
19577    }
19578
19579    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19580            throws PackageManagerException {
19581        synchronized (mPackages) {
19582            final PackageSetting ps = mSettings.mPackages.get(packageName);
19583            if (ps == null) {
19584                throw new PackageManagerException("Package " + packageName + " is unknown");
19585            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19586                throw new PackageManagerException(
19587                        "Package " + packageName + " found on unknown volume " + volumeUuid
19588                                + "; expected volume " + ps.volumeUuid);
19589            } else if (!ps.getInstalled(userId)) {
19590                throw new PackageManagerException(
19591                        "Package " + packageName + " not installed for user " + userId);
19592            }
19593        }
19594    }
19595
19596    /**
19597     * Examine all apps present on given mounted volume, and destroy apps that
19598     * aren't expected, either due to uninstallation or reinstallation on
19599     * another volume.
19600     */
19601    private void reconcileApps(String volumeUuid) {
19602        final File[] files = FileUtils
19603                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19604        for (File file : files) {
19605            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19606                    && !PackageInstallerService.isStageName(file.getName());
19607            if (!isPackage) {
19608                // Ignore entries which are not packages
19609                continue;
19610            }
19611
19612            try {
19613                final PackageLite pkg = PackageParser.parsePackageLite(file,
19614                        PackageParser.PARSE_MUST_BE_APK);
19615                assertPackageKnown(volumeUuid, pkg.packageName);
19616
19617            } catch (PackageParserException | PackageManagerException e) {
19618                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19619                synchronized (mInstallLock) {
19620                    removeCodePathLI(file);
19621                }
19622            }
19623        }
19624    }
19625
19626    /**
19627     * Reconcile all app data for the given user.
19628     * <p>
19629     * Verifies that directories exist and that ownership and labeling is
19630     * correct for all installed apps on all mounted volumes.
19631     */
19632    void reconcileAppsData(int userId, int flags) {
19633        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19634        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19635            final String volumeUuid = vol.getFsUuid();
19636            synchronized (mInstallLock) {
19637                reconcileAppsDataLI(volumeUuid, userId, flags);
19638            }
19639        }
19640    }
19641
19642    /**
19643     * Reconcile all app data on given mounted volume.
19644     * <p>
19645     * Destroys app data that isn't expected, either due to uninstallation or
19646     * reinstallation on another volume.
19647     * <p>
19648     * Verifies that directories exist and that ownership and labeling is
19649     * correct for all installed apps.
19650     */
19651    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19652        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19653                + Integer.toHexString(flags));
19654
19655        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19656        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19657
19658        boolean restoreconNeeded = false;
19659
19660        // First look for stale data that doesn't belong, and check if things
19661        // have changed since we did our last restorecon
19662        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19663            if (StorageManager.isFileEncryptedNativeOrEmulated()
19664                    && !StorageManager.isUserKeyUnlocked(userId)) {
19665                throw new RuntimeException(
19666                        "Yikes, someone asked us to reconcile CE storage while " + userId
19667                                + " was still locked; this would have caused massive data loss!");
19668            }
19669
19670            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19671
19672            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19673            for (File file : files) {
19674                final String packageName = file.getName();
19675                try {
19676                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19677                } catch (PackageManagerException e) {
19678                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19679                    try {
19680                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19681                                StorageManager.FLAG_STORAGE_CE, 0);
19682                    } catch (InstallerException e2) {
19683                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19684                    }
19685                }
19686            }
19687        }
19688        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19689            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19690
19691            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19692            for (File file : files) {
19693                final String packageName = file.getName();
19694                try {
19695                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19696                } catch (PackageManagerException e) {
19697                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19698                    try {
19699                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19700                                StorageManager.FLAG_STORAGE_DE, 0);
19701                    } catch (InstallerException e2) {
19702                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19703                    }
19704                }
19705            }
19706        }
19707
19708        // Ensure that data directories are ready to roll for all packages
19709        // installed for this volume and user
19710        final List<PackageSetting> packages;
19711        synchronized (mPackages) {
19712            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19713        }
19714        int preparedCount = 0;
19715        for (PackageSetting ps : packages) {
19716            final String packageName = ps.name;
19717            if (ps.pkg == null) {
19718                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19719                // TODO: might be due to legacy ASEC apps; we should circle back
19720                // and reconcile again once they're scanned
19721                continue;
19722            }
19723
19724            if (ps.getInstalled(userId)) {
19725                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19726
19727                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19728                    // We may have just shuffled around app data directories, so
19729                    // prepare them one more time
19730                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19731                }
19732
19733                preparedCount++;
19734            }
19735        }
19736
19737        if (restoreconNeeded) {
19738            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19739                SELinuxMMAC.setRestoreconDone(ceDir);
19740            }
19741            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19742                SELinuxMMAC.setRestoreconDone(deDir);
19743            }
19744        }
19745
19746        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19747                + " packages; restoreconNeeded was " + restoreconNeeded);
19748    }
19749
19750    /**
19751     * Prepare app data for the given app just after it was installed or
19752     * upgraded. This method carefully only touches users that it's installed
19753     * for, and it forces a restorecon to handle any seinfo changes.
19754     * <p>
19755     * Verifies that directories exist and that ownership and labeling is
19756     * correct for all installed apps. If there is an ownership mismatch, it
19757     * will try recovering system apps by wiping data; third-party app data is
19758     * left intact.
19759     * <p>
19760     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19761     */
19762    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19763        final PackageSetting ps;
19764        synchronized (mPackages) {
19765            ps = mSettings.mPackages.get(pkg.packageName);
19766            mSettings.writeKernelMappingLPr(ps);
19767        }
19768
19769        final UserManager um = mContext.getSystemService(UserManager.class);
19770        UserManagerInternal umInternal = getUserManagerInternal();
19771        for (UserInfo user : um.getUsers()) {
19772            final int flags;
19773            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19774                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19775            } else if (umInternal.isUserRunning(user.id)) {
19776                flags = StorageManager.FLAG_STORAGE_DE;
19777            } else {
19778                continue;
19779            }
19780
19781            if (ps.getInstalled(user.id)) {
19782                // Whenever an app changes, force a restorecon of its data
19783                // TODO: when user data is locked, mark that we're still dirty
19784                prepareAppDataLIF(pkg, user.id, flags, true);
19785            }
19786        }
19787    }
19788
19789    /**
19790     * Prepare app data for the given app.
19791     * <p>
19792     * Verifies that directories exist and that ownership and labeling is
19793     * correct for all installed apps. If there is an ownership mismatch, this
19794     * will try recovering system apps by wiping data; third-party app data is
19795     * left intact.
19796     */
19797    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19798            boolean restoreconNeeded) {
19799        if (pkg == null) {
19800            Slog.wtf(TAG, "Package was null!", new Throwable());
19801            return;
19802        }
19803        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19804        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19805        for (int i = 0; i < childCount; i++) {
19806            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19807        }
19808    }
19809
19810    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19811            boolean restoreconNeeded) {
19812        if (DEBUG_APP_DATA) {
19813            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19814                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19815        }
19816
19817        final String volumeUuid = pkg.volumeUuid;
19818        final String packageName = pkg.packageName;
19819        final ApplicationInfo app = pkg.applicationInfo;
19820        final int appId = UserHandle.getAppId(app.uid);
19821
19822        Preconditions.checkNotNull(app.seinfo);
19823
19824        try {
19825            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19826                    appId, app.seinfo, app.targetSdkVersion);
19827        } catch (InstallerException e) {
19828            if (app.isSystemApp()) {
19829                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19830                        + ", but trying to recover: " + e);
19831                destroyAppDataLeafLIF(pkg, userId, flags);
19832                try {
19833                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19834                            appId, app.seinfo, app.targetSdkVersion);
19835                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19836                } catch (InstallerException e2) {
19837                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19838                }
19839            } else {
19840                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19841            }
19842        }
19843
19844        if (restoreconNeeded) {
19845            try {
19846                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19847                        app.seinfo);
19848            } catch (InstallerException e) {
19849                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19850            }
19851        }
19852
19853        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19854            try {
19855                // CE storage is unlocked right now, so read out the inode and
19856                // remember for use later when it's locked
19857                // TODO: mark this structure as dirty so we persist it!
19858                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19859                        StorageManager.FLAG_STORAGE_CE);
19860                synchronized (mPackages) {
19861                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19862                    if (ps != null) {
19863                        ps.setCeDataInode(ceDataInode, userId);
19864                    }
19865                }
19866            } catch (InstallerException e) {
19867                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19868            }
19869        }
19870
19871        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19872    }
19873
19874    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19875        if (pkg == null) {
19876            Slog.wtf(TAG, "Package was null!", new Throwable());
19877            return;
19878        }
19879        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19880        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19881        for (int i = 0; i < childCount; i++) {
19882            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19883        }
19884    }
19885
19886    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19887        final String volumeUuid = pkg.volumeUuid;
19888        final String packageName = pkg.packageName;
19889        final ApplicationInfo app = pkg.applicationInfo;
19890
19891        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19892            // Create a native library symlink only if we have native libraries
19893            // and if the native libraries are 32 bit libraries. We do not provide
19894            // this symlink for 64 bit libraries.
19895            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19896                final String nativeLibPath = app.nativeLibraryDir;
19897                try {
19898                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19899                            nativeLibPath, userId);
19900                } catch (InstallerException e) {
19901                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19902                }
19903            }
19904        }
19905    }
19906
19907    /**
19908     * For system apps on non-FBE devices, this method migrates any existing
19909     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19910     * requested by the app.
19911     */
19912    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19913        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19914                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19915            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19916                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19917            try {
19918                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19919                        storageTarget);
19920            } catch (InstallerException e) {
19921                logCriticalInfo(Log.WARN,
19922                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19923            }
19924            return true;
19925        } else {
19926            return false;
19927        }
19928    }
19929
19930    public PackageFreezer freezePackage(String packageName, String killReason) {
19931        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19932    }
19933
19934    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19935        return new PackageFreezer(packageName, userId, killReason);
19936    }
19937
19938    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19939            String killReason) {
19940        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19941    }
19942
19943    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19944            String killReason) {
19945        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19946            return new PackageFreezer();
19947        } else {
19948            return freezePackage(packageName, userId, killReason);
19949        }
19950    }
19951
19952    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19953            String killReason) {
19954        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19955    }
19956
19957    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19958            String killReason) {
19959        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19960            return new PackageFreezer();
19961        } else {
19962            return freezePackage(packageName, userId, killReason);
19963        }
19964    }
19965
19966    /**
19967     * Class that freezes and kills the given package upon creation, and
19968     * unfreezes it upon closing. This is typically used when doing surgery on
19969     * app code/data to prevent the app from running while you're working.
19970     */
19971    private class PackageFreezer implements AutoCloseable {
19972        private final String mPackageName;
19973        private final PackageFreezer[] mChildren;
19974
19975        private final boolean mWeFroze;
19976
19977        private final AtomicBoolean mClosed = new AtomicBoolean();
19978        private final CloseGuard mCloseGuard = CloseGuard.get();
19979
19980        /**
19981         * Create and return a stub freezer that doesn't actually do anything,
19982         * typically used when someone requested
19983         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19984         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19985         */
19986        public PackageFreezer() {
19987            mPackageName = null;
19988            mChildren = null;
19989            mWeFroze = false;
19990            mCloseGuard.open("close");
19991        }
19992
19993        public PackageFreezer(String packageName, int userId, String killReason) {
19994            synchronized (mPackages) {
19995                mPackageName = packageName;
19996                mWeFroze = mFrozenPackages.add(mPackageName);
19997
19998                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19999                if (ps != null) {
20000                    killApplication(ps.name, ps.appId, userId, killReason);
20001                }
20002
20003                final PackageParser.Package p = mPackages.get(packageName);
20004                if (p != null && p.childPackages != null) {
20005                    final int N = p.childPackages.size();
20006                    mChildren = new PackageFreezer[N];
20007                    for (int i = 0; i < N; i++) {
20008                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20009                                userId, killReason);
20010                    }
20011                } else {
20012                    mChildren = null;
20013                }
20014            }
20015            mCloseGuard.open("close");
20016        }
20017
20018        @Override
20019        protected void finalize() throws Throwable {
20020            try {
20021                mCloseGuard.warnIfOpen();
20022                close();
20023            } finally {
20024                super.finalize();
20025            }
20026        }
20027
20028        @Override
20029        public void close() {
20030            mCloseGuard.close();
20031            if (mClosed.compareAndSet(false, true)) {
20032                synchronized (mPackages) {
20033                    if (mWeFroze) {
20034                        mFrozenPackages.remove(mPackageName);
20035                    }
20036
20037                    if (mChildren != null) {
20038                        for (PackageFreezer freezer : mChildren) {
20039                            freezer.close();
20040                        }
20041                    }
20042                }
20043            }
20044        }
20045    }
20046
20047    /**
20048     * Verify that given package is currently frozen.
20049     */
20050    private void checkPackageFrozen(String packageName) {
20051        synchronized (mPackages) {
20052            if (!mFrozenPackages.contains(packageName)) {
20053                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20054            }
20055        }
20056    }
20057
20058    @Override
20059    public int movePackage(final String packageName, final String volumeUuid) {
20060        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20061
20062        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20063        final int moveId = mNextMoveId.getAndIncrement();
20064        mHandler.post(new Runnable() {
20065            @Override
20066            public void run() {
20067                try {
20068                    movePackageInternal(packageName, volumeUuid, moveId, user);
20069                } catch (PackageManagerException e) {
20070                    Slog.w(TAG, "Failed to move " + packageName, e);
20071                    mMoveCallbacks.notifyStatusChanged(moveId,
20072                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20073                }
20074            }
20075        });
20076        return moveId;
20077    }
20078
20079    private void movePackageInternal(final String packageName, final String volumeUuid,
20080            final int moveId, UserHandle user) throws PackageManagerException {
20081        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20082        final PackageManager pm = mContext.getPackageManager();
20083
20084        final boolean currentAsec;
20085        final String currentVolumeUuid;
20086        final File codeFile;
20087        final String installerPackageName;
20088        final String packageAbiOverride;
20089        final int appId;
20090        final String seinfo;
20091        final String label;
20092        final int targetSdkVersion;
20093        final PackageFreezer freezer;
20094        final int[] installedUserIds;
20095
20096        // reader
20097        synchronized (mPackages) {
20098            final PackageParser.Package pkg = mPackages.get(packageName);
20099            final PackageSetting ps = mSettings.mPackages.get(packageName);
20100            if (pkg == null || ps == null) {
20101                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20102            }
20103
20104            if (pkg.applicationInfo.isSystemApp()) {
20105                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20106                        "Cannot move system application");
20107            }
20108
20109            if (pkg.applicationInfo.isExternalAsec()) {
20110                currentAsec = true;
20111                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20112            } else if (pkg.applicationInfo.isForwardLocked()) {
20113                currentAsec = true;
20114                currentVolumeUuid = "forward_locked";
20115            } else {
20116                currentAsec = false;
20117                currentVolumeUuid = ps.volumeUuid;
20118
20119                final File probe = new File(pkg.codePath);
20120                final File probeOat = new File(probe, "oat");
20121                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20122                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20123                            "Move only supported for modern cluster style installs");
20124                }
20125            }
20126
20127            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20128                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20129                        "Package already moved to " + volumeUuid);
20130            }
20131            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20132                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20133                        "Device admin cannot be moved");
20134            }
20135
20136            if (mFrozenPackages.contains(packageName)) {
20137                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20138                        "Failed to move already frozen package");
20139            }
20140
20141            codeFile = new File(pkg.codePath);
20142            installerPackageName = ps.installerPackageName;
20143            packageAbiOverride = ps.cpuAbiOverrideString;
20144            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20145            seinfo = pkg.applicationInfo.seinfo;
20146            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20147            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20148            freezer = freezePackage(packageName, "movePackageInternal");
20149            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20150        }
20151
20152        final Bundle extras = new Bundle();
20153        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20154        extras.putString(Intent.EXTRA_TITLE, label);
20155        mMoveCallbacks.notifyCreated(moveId, extras);
20156
20157        int installFlags;
20158        final boolean moveCompleteApp;
20159        final File measurePath;
20160
20161        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20162            installFlags = INSTALL_INTERNAL;
20163            moveCompleteApp = !currentAsec;
20164            measurePath = Environment.getDataAppDirectory(volumeUuid);
20165        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20166            installFlags = INSTALL_EXTERNAL;
20167            moveCompleteApp = false;
20168            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20169        } else {
20170            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20171            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20172                    || !volume.isMountedWritable()) {
20173                freezer.close();
20174                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20175                        "Move location not mounted private volume");
20176            }
20177
20178            Preconditions.checkState(!currentAsec);
20179
20180            installFlags = INSTALL_INTERNAL;
20181            moveCompleteApp = true;
20182            measurePath = Environment.getDataAppDirectory(volumeUuid);
20183        }
20184
20185        final PackageStats stats = new PackageStats(null, -1);
20186        synchronized (mInstaller) {
20187            for (int userId : installedUserIds) {
20188                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20189                    freezer.close();
20190                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20191                            "Failed to measure package size");
20192                }
20193            }
20194        }
20195
20196        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20197                + stats.dataSize);
20198
20199        final long startFreeBytes = measurePath.getFreeSpace();
20200        final long sizeBytes;
20201        if (moveCompleteApp) {
20202            sizeBytes = stats.codeSize + stats.dataSize;
20203        } else {
20204            sizeBytes = stats.codeSize;
20205        }
20206
20207        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20208            freezer.close();
20209            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20210                    "Not enough free space to move");
20211        }
20212
20213        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20214
20215        final CountDownLatch installedLatch = new CountDownLatch(1);
20216        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20217            @Override
20218            public void onUserActionRequired(Intent intent) throws RemoteException {
20219                throw new IllegalStateException();
20220            }
20221
20222            @Override
20223            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20224                    Bundle extras) throws RemoteException {
20225                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20226                        + PackageManager.installStatusToString(returnCode, msg));
20227
20228                installedLatch.countDown();
20229                freezer.close();
20230
20231                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20232                switch (status) {
20233                    case PackageInstaller.STATUS_SUCCESS:
20234                        mMoveCallbacks.notifyStatusChanged(moveId,
20235                                PackageManager.MOVE_SUCCEEDED);
20236                        break;
20237                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20238                        mMoveCallbacks.notifyStatusChanged(moveId,
20239                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20240                        break;
20241                    default:
20242                        mMoveCallbacks.notifyStatusChanged(moveId,
20243                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20244                        break;
20245                }
20246            }
20247        };
20248
20249        final MoveInfo move;
20250        if (moveCompleteApp) {
20251            // Kick off a thread to report progress estimates
20252            new Thread() {
20253                @Override
20254                public void run() {
20255                    while (true) {
20256                        try {
20257                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20258                                break;
20259                            }
20260                        } catch (InterruptedException ignored) {
20261                        }
20262
20263                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20264                        final int progress = 10 + (int) MathUtils.constrain(
20265                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20266                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20267                    }
20268                }
20269            }.start();
20270
20271            final String dataAppName = codeFile.getName();
20272            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20273                    dataAppName, appId, seinfo, targetSdkVersion);
20274        } else {
20275            move = null;
20276        }
20277
20278        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20279
20280        final Message msg = mHandler.obtainMessage(INIT_COPY);
20281        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20282        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20283                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20284                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20285        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20286        msg.obj = params;
20287
20288        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20289                System.identityHashCode(msg.obj));
20290        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20291                System.identityHashCode(msg.obj));
20292
20293        mHandler.sendMessage(msg);
20294    }
20295
20296    @Override
20297    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20298        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20299
20300        final int realMoveId = mNextMoveId.getAndIncrement();
20301        final Bundle extras = new Bundle();
20302        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20303        mMoveCallbacks.notifyCreated(realMoveId, extras);
20304
20305        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20306            @Override
20307            public void onCreated(int moveId, Bundle extras) {
20308                // Ignored
20309            }
20310
20311            @Override
20312            public void onStatusChanged(int moveId, int status, long estMillis) {
20313                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20314            }
20315        };
20316
20317        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20318        storage.setPrimaryStorageUuid(volumeUuid, callback);
20319        return realMoveId;
20320    }
20321
20322    @Override
20323    public int getMoveStatus(int moveId) {
20324        mContext.enforceCallingOrSelfPermission(
20325                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20326        return mMoveCallbacks.mLastStatus.get(moveId);
20327    }
20328
20329    @Override
20330    public void registerMoveCallback(IPackageMoveObserver callback) {
20331        mContext.enforceCallingOrSelfPermission(
20332                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20333        mMoveCallbacks.register(callback);
20334    }
20335
20336    @Override
20337    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20338        mContext.enforceCallingOrSelfPermission(
20339                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20340        mMoveCallbacks.unregister(callback);
20341    }
20342
20343    @Override
20344    public boolean setInstallLocation(int loc) {
20345        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20346                null);
20347        if (getInstallLocation() == loc) {
20348            return true;
20349        }
20350        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20351                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20352            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20353                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20354            return true;
20355        }
20356        return false;
20357   }
20358
20359    @Override
20360    public int getInstallLocation() {
20361        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20362                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20363                PackageHelper.APP_INSTALL_AUTO);
20364    }
20365
20366    /** Called by UserManagerService */
20367    void cleanUpUser(UserManagerService userManager, int userHandle) {
20368        synchronized (mPackages) {
20369            mDirtyUsers.remove(userHandle);
20370            mUserNeedsBadging.delete(userHandle);
20371            mSettings.removeUserLPw(userHandle);
20372            mPendingBroadcasts.remove(userHandle);
20373            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20374            removeUnusedPackagesLPw(userManager, userHandle);
20375        }
20376    }
20377
20378    /**
20379     * We're removing userHandle and would like to remove any downloaded packages
20380     * that are no longer in use by any other user.
20381     * @param userHandle the user being removed
20382     */
20383    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20384        final boolean DEBUG_CLEAN_APKS = false;
20385        int [] users = userManager.getUserIds();
20386        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20387        while (psit.hasNext()) {
20388            PackageSetting ps = psit.next();
20389            if (ps.pkg == null) {
20390                continue;
20391            }
20392            final String packageName = ps.pkg.packageName;
20393            // Skip over if system app
20394            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20395                continue;
20396            }
20397            if (DEBUG_CLEAN_APKS) {
20398                Slog.i(TAG, "Checking package " + packageName);
20399            }
20400            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20401            if (keep) {
20402                if (DEBUG_CLEAN_APKS) {
20403                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20404                }
20405            } else {
20406                for (int i = 0; i < users.length; i++) {
20407                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20408                        keep = true;
20409                        if (DEBUG_CLEAN_APKS) {
20410                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20411                                    + users[i]);
20412                        }
20413                        break;
20414                    }
20415                }
20416            }
20417            if (!keep) {
20418                if (DEBUG_CLEAN_APKS) {
20419                    Slog.i(TAG, "  Removing package " + packageName);
20420                }
20421                mHandler.post(new Runnable() {
20422                    public void run() {
20423                        deletePackageX(packageName, userHandle, 0);
20424                    } //end run
20425                });
20426            }
20427        }
20428    }
20429
20430    /** Called by UserManagerService */
20431    void createNewUser(int userId) {
20432        synchronized (mInstallLock) {
20433            mSettings.createNewUserLI(this, mInstaller, userId);
20434        }
20435        synchronized (mPackages) {
20436            scheduleWritePackageRestrictionsLocked(userId);
20437            scheduleWritePackageListLocked(userId);
20438            applyFactoryDefaultBrowserLPw(userId);
20439            primeDomainVerificationsLPw(userId);
20440        }
20441    }
20442
20443    void onBeforeUserStartUninitialized(final int userId) {
20444        synchronized (mPackages) {
20445            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20446                return;
20447            }
20448        }
20449        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20450        // If permission review for legacy apps is required, we represent
20451        // dagerous permissions for such apps as always granted runtime
20452        // permissions to keep per user flag state whether review is needed.
20453        // Hence, if a new user is added we have to propagate dangerous
20454        // permission grants for these legacy apps.
20455        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20456            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20457                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20458        }
20459    }
20460
20461    @Override
20462    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20463        mContext.enforceCallingOrSelfPermission(
20464                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20465                "Only package verification agents can read the verifier device identity");
20466
20467        synchronized (mPackages) {
20468            return mSettings.getVerifierDeviceIdentityLPw();
20469        }
20470    }
20471
20472    @Override
20473    public void setPermissionEnforced(String permission, boolean enforced) {
20474        // TODO: Now that we no longer change GID for storage, this should to away.
20475        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20476                "setPermissionEnforced");
20477        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20478            synchronized (mPackages) {
20479                if (mSettings.mReadExternalStorageEnforced == null
20480                        || mSettings.mReadExternalStorageEnforced != enforced) {
20481                    mSettings.mReadExternalStorageEnforced = enforced;
20482                    mSettings.writeLPr();
20483                }
20484            }
20485            // kill any non-foreground processes so we restart them and
20486            // grant/revoke the GID.
20487            final IActivityManager am = ActivityManagerNative.getDefault();
20488            if (am != null) {
20489                final long token = Binder.clearCallingIdentity();
20490                try {
20491                    am.killProcessesBelowForeground("setPermissionEnforcement");
20492                } catch (RemoteException e) {
20493                } finally {
20494                    Binder.restoreCallingIdentity(token);
20495                }
20496            }
20497        } else {
20498            throw new IllegalArgumentException("No selective enforcement for " + permission);
20499        }
20500    }
20501
20502    @Override
20503    @Deprecated
20504    public boolean isPermissionEnforced(String permission) {
20505        return true;
20506    }
20507
20508    @Override
20509    public boolean isStorageLow() {
20510        final long token = Binder.clearCallingIdentity();
20511        try {
20512            final DeviceStorageMonitorInternal
20513                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20514            if (dsm != null) {
20515                return dsm.isMemoryLow();
20516            } else {
20517                return false;
20518            }
20519        } finally {
20520            Binder.restoreCallingIdentity(token);
20521        }
20522    }
20523
20524    @Override
20525    public IPackageInstaller getPackageInstaller() {
20526        return mInstallerService;
20527    }
20528
20529    private boolean userNeedsBadging(int userId) {
20530        int index = mUserNeedsBadging.indexOfKey(userId);
20531        if (index < 0) {
20532            final UserInfo userInfo;
20533            final long token = Binder.clearCallingIdentity();
20534            try {
20535                userInfo = sUserManager.getUserInfo(userId);
20536            } finally {
20537                Binder.restoreCallingIdentity(token);
20538            }
20539            final boolean b;
20540            if (userInfo != null && userInfo.isManagedProfile()) {
20541                b = true;
20542            } else {
20543                b = false;
20544            }
20545            mUserNeedsBadging.put(userId, b);
20546            return b;
20547        }
20548        return mUserNeedsBadging.valueAt(index);
20549    }
20550
20551    @Override
20552    public KeySet getKeySetByAlias(String packageName, String alias) {
20553        if (packageName == null || alias == null) {
20554            return null;
20555        }
20556        synchronized(mPackages) {
20557            final PackageParser.Package pkg = mPackages.get(packageName);
20558            if (pkg == null) {
20559                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20560                throw new IllegalArgumentException("Unknown package: " + packageName);
20561            }
20562            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20563            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20564        }
20565    }
20566
20567    @Override
20568    public KeySet getSigningKeySet(String packageName) {
20569        if (packageName == null) {
20570            return null;
20571        }
20572        synchronized(mPackages) {
20573            final PackageParser.Package pkg = mPackages.get(packageName);
20574            if (pkg == null) {
20575                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20576                throw new IllegalArgumentException("Unknown package: " + packageName);
20577            }
20578            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20579                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20580                throw new SecurityException("May not access signing KeySet of other apps.");
20581            }
20582            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20583            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20584        }
20585    }
20586
20587    @Override
20588    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20589        if (packageName == null || ks == null) {
20590            return false;
20591        }
20592        synchronized(mPackages) {
20593            final PackageParser.Package pkg = mPackages.get(packageName);
20594            if (pkg == null) {
20595                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20596                throw new IllegalArgumentException("Unknown package: " + packageName);
20597            }
20598            IBinder ksh = ks.getToken();
20599            if (ksh instanceof KeySetHandle) {
20600                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20601                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20602            }
20603            return false;
20604        }
20605    }
20606
20607    @Override
20608    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20609        if (packageName == null || ks == null) {
20610            return false;
20611        }
20612        synchronized(mPackages) {
20613            final PackageParser.Package pkg = mPackages.get(packageName);
20614            if (pkg == null) {
20615                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20616                throw new IllegalArgumentException("Unknown package: " + packageName);
20617            }
20618            IBinder ksh = ks.getToken();
20619            if (ksh instanceof KeySetHandle) {
20620                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20621                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20622            }
20623            return false;
20624        }
20625    }
20626
20627    private void deletePackageIfUnusedLPr(final String packageName) {
20628        PackageSetting ps = mSettings.mPackages.get(packageName);
20629        if (ps == null) {
20630            return;
20631        }
20632        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20633            // TODO Implement atomic delete if package is unused
20634            // It is currently possible that the package will be deleted even if it is installed
20635            // after this method returns.
20636            mHandler.post(new Runnable() {
20637                public void run() {
20638                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20639                }
20640            });
20641        }
20642    }
20643
20644    /**
20645     * Check and throw if the given before/after packages would be considered a
20646     * downgrade.
20647     */
20648    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20649            throws PackageManagerException {
20650        if (after.versionCode < before.mVersionCode) {
20651            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20652                    "Update version code " + after.versionCode + " is older than current "
20653                    + before.mVersionCode);
20654        } else if (after.versionCode == before.mVersionCode) {
20655            if (after.baseRevisionCode < before.baseRevisionCode) {
20656                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20657                        "Update base revision code " + after.baseRevisionCode
20658                        + " is older than current " + before.baseRevisionCode);
20659            }
20660
20661            if (!ArrayUtils.isEmpty(after.splitNames)) {
20662                for (int i = 0; i < after.splitNames.length; i++) {
20663                    final String splitName = after.splitNames[i];
20664                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20665                    if (j != -1) {
20666                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20667                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20668                                    "Update split " + splitName + " revision code "
20669                                    + after.splitRevisionCodes[i] + " is older than current "
20670                                    + before.splitRevisionCodes[j]);
20671                        }
20672                    }
20673                }
20674            }
20675        }
20676    }
20677
20678    private static class MoveCallbacks extends Handler {
20679        private static final int MSG_CREATED = 1;
20680        private static final int MSG_STATUS_CHANGED = 2;
20681
20682        private final RemoteCallbackList<IPackageMoveObserver>
20683                mCallbacks = new RemoteCallbackList<>();
20684
20685        private final SparseIntArray mLastStatus = new SparseIntArray();
20686
20687        public MoveCallbacks(Looper looper) {
20688            super(looper);
20689        }
20690
20691        public void register(IPackageMoveObserver callback) {
20692            mCallbacks.register(callback);
20693        }
20694
20695        public void unregister(IPackageMoveObserver callback) {
20696            mCallbacks.unregister(callback);
20697        }
20698
20699        @Override
20700        public void handleMessage(Message msg) {
20701            final SomeArgs args = (SomeArgs) msg.obj;
20702            final int n = mCallbacks.beginBroadcast();
20703            for (int i = 0; i < n; i++) {
20704                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20705                try {
20706                    invokeCallback(callback, msg.what, args);
20707                } catch (RemoteException ignored) {
20708                }
20709            }
20710            mCallbacks.finishBroadcast();
20711            args.recycle();
20712        }
20713
20714        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20715                throws RemoteException {
20716            switch (what) {
20717                case MSG_CREATED: {
20718                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20719                    break;
20720                }
20721                case MSG_STATUS_CHANGED: {
20722                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20723                    break;
20724                }
20725            }
20726        }
20727
20728        private void notifyCreated(int moveId, Bundle extras) {
20729            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20730
20731            final SomeArgs args = SomeArgs.obtain();
20732            args.argi1 = moveId;
20733            args.arg2 = extras;
20734            obtainMessage(MSG_CREATED, args).sendToTarget();
20735        }
20736
20737        private void notifyStatusChanged(int moveId, int status) {
20738            notifyStatusChanged(moveId, status, -1);
20739        }
20740
20741        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20742            Slog.v(TAG, "Move " + moveId + " status " + status);
20743
20744            final SomeArgs args = SomeArgs.obtain();
20745            args.argi1 = moveId;
20746            args.argi2 = status;
20747            args.arg3 = estMillis;
20748            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20749
20750            synchronized (mLastStatus) {
20751                mLastStatus.put(moveId, status);
20752            }
20753        }
20754    }
20755
20756    private final static class OnPermissionChangeListeners extends Handler {
20757        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20758
20759        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20760                new RemoteCallbackList<>();
20761
20762        public OnPermissionChangeListeners(Looper looper) {
20763            super(looper);
20764        }
20765
20766        @Override
20767        public void handleMessage(Message msg) {
20768            switch (msg.what) {
20769                case MSG_ON_PERMISSIONS_CHANGED: {
20770                    final int uid = msg.arg1;
20771                    handleOnPermissionsChanged(uid);
20772                } break;
20773            }
20774        }
20775
20776        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20777            mPermissionListeners.register(listener);
20778
20779        }
20780
20781        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20782            mPermissionListeners.unregister(listener);
20783        }
20784
20785        public void onPermissionsChanged(int uid) {
20786            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20787                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20788            }
20789        }
20790
20791        private void handleOnPermissionsChanged(int uid) {
20792            final int count = mPermissionListeners.beginBroadcast();
20793            try {
20794                for (int i = 0; i < count; i++) {
20795                    IOnPermissionsChangeListener callback = mPermissionListeners
20796                            .getBroadcastItem(i);
20797                    try {
20798                        callback.onPermissionsChanged(uid);
20799                    } catch (RemoteException e) {
20800                        Log.e(TAG, "Permission listener is dead", e);
20801                    }
20802                }
20803            } finally {
20804                mPermissionListeners.finishBroadcast();
20805            }
20806        }
20807    }
20808
20809    private class PackageManagerInternalImpl extends PackageManagerInternal {
20810        @Override
20811        public void setLocationPackagesProvider(PackagesProvider provider) {
20812            synchronized (mPackages) {
20813                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20814            }
20815        }
20816
20817        @Override
20818        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20819            synchronized (mPackages) {
20820                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20821            }
20822        }
20823
20824        @Override
20825        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20826            synchronized (mPackages) {
20827                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20828            }
20829        }
20830
20831        @Override
20832        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20833            synchronized (mPackages) {
20834                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20835            }
20836        }
20837
20838        @Override
20839        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20840            synchronized (mPackages) {
20841                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20842            }
20843        }
20844
20845        @Override
20846        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20847            synchronized (mPackages) {
20848                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20849            }
20850        }
20851
20852        @Override
20853        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20854            synchronized (mPackages) {
20855                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20856                        packageName, userId);
20857            }
20858        }
20859
20860        @Override
20861        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20862            synchronized (mPackages) {
20863                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20864                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20865                        packageName, userId);
20866            }
20867        }
20868
20869        @Override
20870        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20871            synchronized (mPackages) {
20872                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20873                        packageName, userId);
20874            }
20875        }
20876
20877        @Override
20878        public void setKeepUninstalledPackages(final List<String> packageList) {
20879            Preconditions.checkNotNull(packageList);
20880            List<String> removedFromList = null;
20881            synchronized (mPackages) {
20882                if (mKeepUninstalledPackages != null) {
20883                    final int packagesCount = mKeepUninstalledPackages.size();
20884                    for (int i = 0; i < packagesCount; i++) {
20885                        String oldPackage = mKeepUninstalledPackages.get(i);
20886                        if (packageList != null && packageList.contains(oldPackage)) {
20887                            continue;
20888                        }
20889                        if (removedFromList == null) {
20890                            removedFromList = new ArrayList<>();
20891                        }
20892                        removedFromList.add(oldPackage);
20893                    }
20894                }
20895                mKeepUninstalledPackages = new ArrayList<>(packageList);
20896                if (removedFromList != null) {
20897                    final int removedCount = removedFromList.size();
20898                    for (int i = 0; i < removedCount; i++) {
20899                        deletePackageIfUnusedLPr(removedFromList.get(i));
20900                    }
20901                }
20902            }
20903        }
20904
20905        @Override
20906        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20907            synchronized (mPackages) {
20908                // If we do not support permission review, done.
20909                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20910                    return false;
20911                }
20912
20913                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20914                if (packageSetting == null) {
20915                    return false;
20916                }
20917
20918                // Permission review applies only to apps not supporting the new permission model.
20919                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20920                    return false;
20921                }
20922
20923                // Legacy apps have the permission and get user consent on launch.
20924                PermissionsState permissionsState = packageSetting.getPermissionsState();
20925                return permissionsState.isPermissionReviewRequired(userId);
20926            }
20927        }
20928
20929        @Override
20930        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20931            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20932        }
20933
20934        @Override
20935        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20936                int userId) {
20937            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20938        }
20939
20940        @Override
20941        public void setDeviceAndProfileOwnerPackages(
20942                int deviceOwnerUserId, String deviceOwnerPackage,
20943                SparseArray<String> profileOwnerPackages) {
20944            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20945                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20946        }
20947
20948        @Override
20949        public boolean isPackageDataProtected(int userId, String packageName) {
20950            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20951        }
20952    }
20953
20954    @Override
20955    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20956        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20957        synchronized (mPackages) {
20958            final long identity = Binder.clearCallingIdentity();
20959            try {
20960                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20961                        packageNames, userId);
20962            } finally {
20963                Binder.restoreCallingIdentity(identity);
20964            }
20965        }
20966    }
20967
20968    private static void enforceSystemOrPhoneCaller(String tag) {
20969        int callingUid = Binder.getCallingUid();
20970        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20971            throw new SecurityException(
20972                    "Cannot call " + tag + " from UID " + callingUid);
20973        }
20974    }
20975
20976    boolean isHistoricalPackageUsageAvailable() {
20977        return mPackageUsage.isHistoricalPackageUsageAvailable();
20978    }
20979
20980    /**
20981     * Return a <b>copy</b> of the collection of packages known to the package manager.
20982     * @return A copy of the values of mPackages.
20983     */
20984    Collection<PackageParser.Package> getPackages() {
20985        synchronized (mPackages) {
20986            return new ArrayList<>(mPackages.values());
20987        }
20988    }
20989
20990    /**
20991     * Logs process start information (including base APK hash) to the security log.
20992     * @hide
20993     */
20994    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20995            String apkFile, int pid) {
20996        if (!SecurityLog.isLoggingEnabled()) {
20997            return;
20998        }
20999        Bundle data = new Bundle();
21000        data.putLong("startTimestamp", System.currentTimeMillis());
21001        data.putString("processName", processName);
21002        data.putInt("uid", uid);
21003        data.putString("seinfo", seinfo);
21004        data.putString("apkFile", apkFile);
21005        data.putInt("pid", pid);
21006        Message msg = mProcessLoggingHandler.obtainMessage(
21007                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21008        msg.setData(data);
21009        mProcessLoggingHandler.sendMessage(msg);
21010    }
21011}
21012