PackageManagerService.java revision 0bd776207999ccba17e5adb163710bd7b16ac907
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.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
102
103import android.Manifest;
104import android.annotation.NonNull;
105import android.annotation.Nullable;
106import android.annotation.UserIdInt;
107import android.app.ActivityManager;
108import android.app.ActivityManagerNative;
109import android.app.IActivityManager;
110import android.app.ResourcesManager;
111import android.app.admin.IDevicePolicyManager;
112import android.app.admin.SecurityLog;
113import android.app.backup.IBackupManager;
114import android.content.BroadcastReceiver;
115import android.content.ComponentName;
116import android.content.Context;
117import android.content.IIntentReceiver;
118import android.content.Intent;
119import android.content.IntentFilter;
120import android.content.IntentSender;
121import android.content.IntentSender.SendIntentException;
122import android.content.ServiceConnection;
123import android.content.pm.ActivityInfo;
124import android.content.pm.ApplicationInfo;
125import android.content.pm.AppsQueryHelper;
126import android.content.pm.ComponentInfo;
127import android.content.pm.EphemeralApplicationInfo;
128import android.content.pm.EphemeralResolveInfo;
129import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
130import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstrumentationInfo;
142import android.content.pm.IntentFilterVerificationInfo;
143import android.content.pm.KeySet;
144import android.content.pm.PackageCleanItem;
145import android.content.pm.PackageInfo;
146import android.content.pm.PackageInfoLite;
147import android.content.pm.PackageInstaller;
148import android.content.pm.PackageManager;
149import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
150import android.content.pm.PackageManagerInternal;
151import android.content.pm.PackageParser;
152import android.content.pm.PackageParser.ActivityIntentInfo;
153import android.content.pm.PackageParser.PackageLite;
154import android.content.pm.PackageParser.PackageParserException;
155import android.content.pm.PackageStats;
156import android.content.pm.PackageUserState;
157import android.content.pm.ParceledListSlice;
158import android.content.pm.PermissionGroupInfo;
159import android.content.pm.PermissionInfo;
160import android.content.pm.ProviderInfo;
161import android.content.pm.ResolveInfo;
162import android.content.pm.ServiceInfo;
163import android.content.pm.ShortcutServiceInternal;
164import android.content.pm.Signature;
165import android.content.pm.UserInfo;
166import android.content.pm.VerifierDeviceIdentity;
167import android.content.pm.VerifierInfo;
168import android.content.res.Resources;
169import android.graphics.Bitmap;
170import android.hardware.display.DisplayManager;
171import android.net.Uri;
172import android.os.Binder;
173import android.os.Build;
174import android.os.Bundle;
175import android.os.Debug;
176import android.os.Environment;
177import android.os.Environment.UserEnvironment;
178import android.os.FileUtils;
179import android.os.Handler;
180import android.os.IBinder;
181import android.os.Looper;
182import android.os.Message;
183import android.os.Parcel;
184import android.os.ParcelFileDescriptor;
185import android.os.Process;
186import android.os.RemoteCallbackList;
187import android.os.RemoteException;
188import android.os.ResultReceiver;
189import android.os.SELinux;
190import android.os.ServiceManager;
191import android.os.SystemClock;
192import android.os.SystemProperties;
193import android.os.Trace;
194import android.os.UserHandle;
195import android.os.UserManager;
196import android.os.UserManagerInternal;
197import android.os.storage.IMountService;
198import android.os.storage.MountServiceInternal;
199import android.os.storage.StorageEventListener;
200import android.os.storage.StorageManager;
201import android.os.storage.VolumeInfo;
202import android.os.storage.VolumeRecord;
203import android.provider.Settings.Global;
204import android.security.KeyStore;
205import android.security.SystemKeyStore;
206import android.system.ErrnoException;
207import android.system.Os;
208import android.text.TextUtils;
209import android.text.format.DateUtils;
210import android.util.ArrayMap;
211import android.util.ArraySet;
212import android.util.AtomicFile;
213import android.util.DisplayMetrics;
214import android.util.EventLog;
215import android.util.ExceptionUtils;
216import android.util.Log;
217import android.util.LogPrinter;
218import android.util.MathUtils;
219import android.util.PrintStreamPrinter;
220import android.util.Slog;
221import android.util.SparseArray;
222import android.util.SparseBooleanArray;
223import android.util.SparseIntArray;
224import android.util.Xml;
225import android.util.jar.StrictJarFile;
226import android.view.Display;
227
228import com.android.internal.R;
229import com.android.internal.annotations.GuardedBy;
230import com.android.internal.app.IMediaContainerService;
231import com.android.internal.app.ResolverActivity;
232import com.android.internal.content.NativeLibraryHelper;
233import com.android.internal.content.PackageHelper;
234import com.android.internal.logging.MetricsLogger;
235import com.android.internal.os.IParcelFileDescriptorFactory;
236import com.android.internal.os.InstallerConnection.InstallerException;
237import com.android.internal.os.SomeArgs;
238import com.android.internal.os.Zygote;
239import com.android.internal.telephony.CarrierAppUtils;
240import com.android.internal.util.ArrayUtils;
241import com.android.internal.util.FastPrintWriter;
242import com.android.internal.util.FastXmlSerializer;
243import com.android.internal.util.IndentingPrintWriter;
244import com.android.internal.util.Preconditions;
245import com.android.internal.util.XmlUtils;
246import com.android.server.AttributeCache;
247import com.android.server.EventLogTags;
248import com.android.server.FgThread;
249import com.android.server.IntentResolver;
250import com.android.server.LocalServices;
251import com.android.server.ServiceThread;
252import com.android.server.SystemConfig;
253import com.android.server.Watchdog;
254import com.android.server.net.NetworkPolicyManagerInternal;
255import com.android.server.pm.PermissionsState.PermissionState;
256import com.android.server.pm.Settings.DatabaseVersion;
257import com.android.server.pm.Settings.VersionInfo;
258import com.android.server.storage.DeviceStorageMonitorInternal;
259
260import dalvik.system.CloseGuard;
261import dalvik.system.DexFile;
262import dalvik.system.VMRuntime;
263
264import libcore.io.IoUtils;
265import libcore.util.EmptyArray;
266
267import org.xmlpull.v1.XmlPullParser;
268import org.xmlpull.v1.XmlPullParserException;
269import org.xmlpull.v1.XmlSerializer;
270
271import java.io.BufferedInputStream;
272import java.io.BufferedOutputStream;
273import java.io.BufferedReader;
274import java.io.ByteArrayInputStream;
275import java.io.ByteArrayOutputStream;
276import java.io.File;
277import java.io.FileDescriptor;
278import java.io.FileInputStream;
279import java.io.FileNotFoundException;
280import java.io.FileOutputStream;
281import java.io.FileReader;
282import java.io.FilenameFilter;
283import java.io.IOException;
284import java.io.InputStream;
285import java.io.PrintWriter;
286import java.nio.charset.StandardCharsets;
287import java.security.DigestInputStream;
288import java.security.MessageDigest;
289import java.security.NoSuchAlgorithmException;
290import java.security.PublicKey;
291import java.security.cert.Certificate;
292import java.security.cert.CertificateEncodingException;
293import java.security.cert.CertificateException;
294import java.text.SimpleDateFormat;
295import java.util.ArrayList;
296import java.util.Arrays;
297import java.util.Collection;
298import java.util.Collections;
299import java.util.Comparator;
300import java.util.Date;
301import java.util.HashSet;
302import java.util.Iterator;
303import java.util.List;
304import java.util.Map;
305import java.util.Objects;
306import java.util.Set;
307import java.util.concurrent.CountDownLatch;
308import java.util.concurrent.TimeUnit;
309import java.util.concurrent.atomic.AtomicBoolean;
310import java.util.concurrent.atomic.AtomicInteger;
311import java.util.concurrent.atomic.AtomicLong;
312
313/**
314 * Keep track of all those APKs everywhere.
315 * <p>
316 * Internally there are two important locks:
317 * <ul>
318 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
319 * and other related state. It is a fine-grained lock that should only be held
320 * momentarily, as it's one of the most contended locks in the system.
321 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
322 * operations typically involve heavy lifting of application data on disk. Since
323 * {@code installd} is single-threaded, and it's operations can often be slow,
324 * this lock should never be acquired while already holding {@link #mPackages}.
325 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
326 * holding {@link #mInstallLock}.
327 * </ul>
328 * Many internal methods rely on the caller to hold the appropriate locks, and
329 * this contract is expressed through method name suffixes:
330 * <ul>
331 * <li>fooLI(): the caller must hold {@link #mInstallLock}
332 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
333 * being modified must be frozen
334 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
335 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
336 * </ul>
337 * <p>
338 * Because this class is very central to the platform's security; please run all
339 * CTS and unit tests whenever making modifications:
340 *
341 * <pre>
342 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
343 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
344 * </pre>
345 */
346public class PackageManagerService extends IPackageManager.Stub {
347    static final String TAG = "PackageManager";
348    static final boolean DEBUG_SETTINGS = false;
349    static final boolean DEBUG_PREFERRED = false;
350    static final boolean DEBUG_UPGRADE = false;
351    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
352    private static final boolean DEBUG_BACKUP = false;
353    private static final boolean DEBUG_INSTALL = false;
354    private static final boolean DEBUG_REMOVE = false;
355    private static final boolean DEBUG_BROADCASTS = false;
356    private static final boolean DEBUG_SHOW_INFO = false;
357    private static final boolean DEBUG_PACKAGE_INFO = false;
358    private static final boolean DEBUG_INTENT_MATCHING = false;
359    private static final boolean DEBUG_PACKAGE_SCANNING = false;
360    private static final boolean DEBUG_VERIFY = false;
361    private static final boolean DEBUG_FILTERS = false;
362
363    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
364    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
365    // user, but by default initialize to this.
366    static final boolean DEBUG_DEXOPT = false;
367
368    private static final boolean DEBUG_ABI_SELECTION = false;
369    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
370    private static final boolean DEBUG_TRIAGED_MISSING = false;
371    private static final boolean DEBUG_APP_DATA = false;
372
373    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
374
375    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
376
377    private static final int RADIO_UID = Process.PHONE_UID;
378    private static final int LOG_UID = Process.LOG_UID;
379    private static final int NFC_UID = Process.NFC_UID;
380    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
381    private static final int SHELL_UID = Process.SHELL_UID;
382
383    // Cap the size of permission trees that 3rd party apps can define
384    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
385
386    // Suffix used during package installation when copying/moving
387    // package apks to install directory.
388    private static final String INSTALL_PACKAGE_SUFFIX = "-";
389
390    static final int SCAN_NO_DEX = 1<<1;
391    static final int SCAN_FORCE_DEX = 1<<2;
392    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
393    static final int SCAN_NEW_INSTALL = 1<<4;
394    static final int SCAN_NO_PATHS = 1<<5;
395    static final int SCAN_UPDATE_TIME = 1<<6;
396    static final int SCAN_DEFER_DEX = 1<<7;
397    static final int SCAN_BOOTING = 1<<8;
398    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
399    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
400    static final int SCAN_REPLACING = 1<<11;
401    static final int SCAN_REQUIRE_KNOWN = 1<<12;
402    static final int SCAN_MOVE = 1<<13;
403    static final int SCAN_INITIAL = 1<<14;
404    static final int SCAN_CHECK_ONLY = 1<<15;
405    static final int SCAN_DONT_KILL_APP = 1<<17;
406    static final int SCAN_IGNORE_FROZEN = 1<<18;
407
408    static final int REMOVE_CHATTY = 1<<16;
409
410    private static final int[] EMPTY_INT_ARRAY = new int[0];
411
412    /**
413     * Timeout (in milliseconds) after which the watchdog should declare that
414     * our handler thread is wedged.  The usual default for such things is one
415     * minute but we sometimes do very lengthy I/O operations on this thread,
416     * such as installing multi-gigabyte applications, so ours needs to be longer.
417     */
418    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
419
420    /**
421     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
422     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
423     * settings entry if available, otherwise we use the hardcoded default.  If it's been
424     * more than this long since the last fstrim, we force one during the boot sequence.
425     *
426     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
427     * one gets run at the next available charging+idle time.  This final mandatory
428     * no-fstrim check kicks in only of the other scheduling criteria is never met.
429     */
430    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
431
432    /**
433     * Whether verification is enabled by default.
434     */
435    private static final boolean DEFAULT_VERIFY_ENABLE = true;
436
437    /**
438     * The default maximum time to wait for the verification agent to return in
439     * milliseconds.
440     */
441    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
442
443    /**
444     * The default response for package verification timeout.
445     *
446     * This can be either PackageManager.VERIFICATION_ALLOW or
447     * PackageManager.VERIFICATION_REJECT.
448     */
449    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
450
451    static final String PLATFORM_PACKAGE_NAME = "android";
452
453    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
454
455    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
456            DEFAULT_CONTAINER_PACKAGE,
457            "com.android.defcontainer.DefaultContainerService");
458
459    private static final String KILL_APP_REASON_GIDS_CHANGED =
460            "permission grant or revoke changed gids";
461
462    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
463            "permissions revoked";
464
465    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
466
467    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
468
469    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
470    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
471
472    /** Permission grant: not grant the permission. */
473    private static final int GRANT_DENIED = 1;
474
475    /** Permission grant: grant the permission as an install permission. */
476    private static final int GRANT_INSTALL = 2;
477
478    /** Permission grant: grant the permission as a runtime one. */
479    private static final int GRANT_RUNTIME = 3;
480
481    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
482    private static final int GRANT_UPGRADE = 4;
483
484    /** Canonical intent used to identify what counts as a "web browser" app */
485    private static final Intent sBrowserIntent;
486    static {
487        sBrowserIntent = new Intent();
488        sBrowserIntent.setAction(Intent.ACTION_VIEW);
489        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
490        sBrowserIntent.setData(Uri.parse("http:"));
491    }
492
493    /**
494     * The set of all protected actions [i.e. those actions for which a high priority
495     * intent filter is disallowed].
496     */
497    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
498    static {
499        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
500        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
501        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
502        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
503    }
504
505    // Compilation reasons.
506    public static final int REASON_FIRST_BOOT = 0;
507    public static final int REASON_BOOT = 1;
508    public static final int REASON_INSTALL = 2;
509    public static final int REASON_BACKGROUND_DEXOPT = 3;
510    public static final int REASON_AB_OTA = 4;
511    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
512    public static final int REASON_SHARED_APK = 6;
513    public static final int REASON_FORCED_DEXOPT = 7;
514    public static final int REASON_CORE_APP = 8;
515
516    public static final int REASON_LAST = REASON_CORE_APP;
517
518    /** Special library name that skips shared libraries check during compilation. */
519    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
520
521    final ServiceThread mHandlerThread;
522
523    final PackageHandler mHandler;
524
525    private final ProcessLoggingHandler mProcessLoggingHandler;
526
527    /**
528     * Messages for {@link #mHandler} that need to wait for system ready before
529     * being dispatched.
530     */
531    private ArrayList<Message> mPostSystemReadyMessages;
532
533    final int mSdkVersion = Build.VERSION.SDK_INT;
534
535    final Context mContext;
536    final boolean mFactoryTest;
537    final boolean mOnlyCore;
538    final DisplayMetrics mMetrics;
539    final int mDefParseFlags;
540    final String[] mSeparateProcesses;
541    final boolean mIsUpgrade;
542    final boolean mIsPreNUpgrade;
543
544    /** The location for ASEC container files on internal storage. */
545    final String mAsecInternalPath;
546
547    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
548    // LOCK HELD.  Can be called with mInstallLock held.
549    @GuardedBy("mInstallLock")
550    final Installer mInstaller;
551
552    /** Directory where installed third-party apps stored */
553    final File mAppInstallDir;
554    final File mEphemeralInstallDir;
555
556    /**
557     * Directory to which applications installed internally have their
558     * 32 bit native libraries copied.
559     */
560    private File mAppLib32InstallDir;
561
562    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
563    // apps.
564    final File mDrmAppPrivateInstallDir;
565
566    // ----------------------------------------------------------------
567
568    // Lock for state used when installing and doing other long running
569    // operations.  Methods that must be called with this lock held have
570    // the suffix "LI".
571    final Object mInstallLock = new Object();
572
573    // ----------------------------------------------------------------
574
575    // Keys are String (package name), values are Package.  This also serves
576    // as the lock for the global state.  Methods that must be called with
577    // this lock held have the prefix "LP".
578    @GuardedBy("mPackages")
579    final ArrayMap<String, PackageParser.Package> mPackages =
580            new ArrayMap<String, PackageParser.Package>();
581
582    final ArrayMap<String, Set<String>> mKnownCodebase =
583            new ArrayMap<String, Set<String>>();
584
585    // Tracks available target package names -> overlay package paths.
586    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
587        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
588
589    /**
590     * Tracks new system packages [received in an OTA] that we expect to
591     * find updated user-installed versions. Keys are package name, values
592     * are package location.
593     */
594    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
595    /**
596     * Tracks high priority intent filters for protected actions. During boot, certain
597     * filter actions are protected and should never be allowed to have a high priority
598     * intent filter for them. However, there is one, and only one exception -- the
599     * setup wizard. It must be able to define a high priority intent filter for these
600     * actions to ensure there are no escapes from the wizard. We need to delay processing
601     * of these during boot as we need to look at all of the system packages in order
602     * to know which component is the setup wizard.
603     */
604    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
605    /**
606     * Whether or not processing protected filters should be deferred.
607     */
608    private boolean mDeferProtectedFilters = true;
609
610    /**
611     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
612     */
613    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
614    /**
615     * Whether or not system app permissions should be promoted from install to runtime.
616     */
617    boolean mPromoteSystemApps;
618
619    @GuardedBy("mPackages")
620    final Settings mSettings;
621
622    /**
623     * Set of package names that are currently "frozen", which means active
624     * surgery is being done on the code/data for that package. The platform
625     * will refuse to launch frozen packages to avoid race conditions.
626     *
627     * @see PackageFreezer
628     */
629    @GuardedBy("mPackages")
630    final ArraySet<String> mFrozenPackages = new ArraySet<>();
631
632    final ProtectedPackages mProtectedPackages;
633
634    boolean mFirstBoot;
635
636    // System configuration read by SystemConfig.
637    final int[] mGlobalGids;
638    final SparseArray<ArraySet<String>> mSystemPermissions;
639    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
640
641    // If mac_permissions.xml was found for seinfo labeling.
642    boolean mFoundPolicyFile;
643
644    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
645
646    public static final class SharedLibraryEntry {
647        public final String path;
648        public final String apk;
649
650        SharedLibraryEntry(String _path, String _apk) {
651            path = _path;
652            apk = _apk;
653        }
654    }
655
656    // Currently known shared libraries.
657    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
658            new ArrayMap<String, SharedLibraryEntry>();
659
660    // All available activities, for your resolving pleasure.
661    final ActivityIntentResolver mActivities =
662            new ActivityIntentResolver();
663
664    // All available receivers, for your resolving pleasure.
665    final ActivityIntentResolver mReceivers =
666            new ActivityIntentResolver();
667
668    // All available services, for your resolving pleasure.
669    final ServiceIntentResolver mServices = new ServiceIntentResolver();
670
671    // All available providers, for your resolving pleasure.
672    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
673
674    // Mapping from provider base names (first directory in content URI codePath)
675    // to the provider information.
676    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
677            new ArrayMap<String, PackageParser.Provider>();
678
679    // Mapping from instrumentation class names to info about them.
680    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
681            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
682
683    // Mapping from permission names to info about them.
684    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
685            new ArrayMap<String, PackageParser.PermissionGroup>();
686
687    // Packages whose data we have transfered into another package, thus
688    // should no longer exist.
689    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
690
691    // Broadcast actions that are only available to the system.
692    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
693
694    /** List of packages waiting for verification. */
695    final SparseArray<PackageVerificationState> mPendingVerification
696            = new SparseArray<PackageVerificationState>();
697
698    /** Set of packages associated with each app op permission. */
699    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
700
701    final PackageInstallerService mInstallerService;
702
703    private final PackageDexOptimizer mPackageDexOptimizer;
704
705    private AtomicInteger mNextMoveId = new AtomicInteger();
706    private final MoveCallbacks mMoveCallbacks;
707
708    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
709
710    // Cache of users who need badging.
711    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
712
713    /** Token for keys in mPendingVerification. */
714    private int mPendingVerificationToken = 0;
715
716    volatile boolean mSystemReady;
717    volatile boolean mSafeMode;
718    volatile boolean mHasSystemUidErrors;
719
720    ApplicationInfo mAndroidApplication;
721    final ActivityInfo mResolveActivity = new ActivityInfo();
722    final ResolveInfo mResolveInfo = new ResolveInfo();
723    ComponentName mResolveComponentName;
724    PackageParser.Package mPlatformPackage;
725    ComponentName mCustomResolverComponentName;
726
727    boolean mResolverReplaced = false;
728
729    private final @Nullable ComponentName mIntentFilterVerifierComponent;
730    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
731
732    private int mIntentFilterVerificationToken = 0;
733
734    /** Component that knows whether or not an ephemeral application exists */
735    final ComponentName mEphemeralResolverComponent;
736    /** The service connection to the ephemeral resolver */
737    final EphemeralResolverConnection mEphemeralResolverConnection;
738
739    /** Component used to install ephemeral applications */
740    final ComponentName mEphemeralInstallerComponent;
741    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
742    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
743
744    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
745            = new SparseArray<IntentFilterVerificationState>();
746
747    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
748            new DefaultPermissionGrantPolicy(this);
749
750    // List of packages names to keep cached, even if they are uninstalled for all users
751    private List<String> mKeepUninstalledPackages;
752
753    private UserManagerInternal mUserManagerInternal;
754
755    private static class IFVerificationParams {
756        PackageParser.Package pkg;
757        boolean replacing;
758        int userId;
759        int verifierUid;
760
761        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
762                int _userId, int _verifierUid) {
763            pkg = _pkg;
764            replacing = _replacing;
765            userId = _userId;
766            replacing = _replacing;
767            verifierUid = _verifierUid;
768        }
769    }
770
771    private interface IntentFilterVerifier<T extends IntentFilter> {
772        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
773                                               T filter, String packageName);
774        void startVerifications(int userId);
775        void receiveVerificationResponse(int verificationId);
776    }
777
778    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
779        private Context mContext;
780        private ComponentName mIntentFilterVerifierComponent;
781        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
782
783        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
784            mContext = context;
785            mIntentFilterVerifierComponent = verifierComponent;
786        }
787
788        private String getDefaultScheme() {
789            return IntentFilter.SCHEME_HTTPS;
790        }
791
792        @Override
793        public void startVerifications(int userId) {
794            // Launch verifications requests
795            int count = mCurrentIntentFilterVerifications.size();
796            for (int n=0; n<count; n++) {
797                int verificationId = mCurrentIntentFilterVerifications.get(n);
798                final IntentFilterVerificationState ivs =
799                        mIntentFilterVerificationStates.get(verificationId);
800
801                String packageName = ivs.getPackageName();
802
803                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
804                final int filterCount = filters.size();
805                ArraySet<String> domainsSet = new ArraySet<>();
806                for (int m=0; m<filterCount; m++) {
807                    PackageParser.ActivityIntentInfo filter = filters.get(m);
808                    domainsSet.addAll(filter.getHostsList());
809                }
810                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
811                synchronized (mPackages) {
812                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
813                            packageName, domainsList) != null) {
814                        scheduleWriteSettingsLocked();
815                    }
816                }
817                sendVerificationRequest(userId, verificationId, ivs);
818            }
819            mCurrentIntentFilterVerifications.clear();
820        }
821
822        private void sendVerificationRequest(int userId, int verificationId,
823                IntentFilterVerificationState ivs) {
824
825            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
826            verificationIntent.putExtra(
827                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
828                    verificationId);
829            verificationIntent.putExtra(
830                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
831                    getDefaultScheme());
832            verificationIntent.putExtra(
833                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
834                    ivs.getHostsString());
835            verificationIntent.putExtra(
836                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
837                    ivs.getPackageName());
838            verificationIntent.setComponent(mIntentFilterVerifierComponent);
839            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
840
841            UserHandle user = new UserHandle(userId);
842            mContext.sendBroadcastAsUser(verificationIntent, user);
843            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
844                    "Sending IntentFilter verification broadcast");
845        }
846
847        public void receiveVerificationResponse(int verificationId) {
848            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
849
850            final boolean verified = ivs.isVerified();
851
852            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
853            final int count = filters.size();
854            if (DEBUG_DOMAIN_VERIFICATION) {
855                Slog.i(TAG, "Received verification response " + verificationId
856                        + " for " + count + " filters, verified=" + verified);
857            }
858            for (int n=0; n<count; n++) {
859                PackageParser.ActivityIntentInfo filter = filters.get(n);
860                filter.setVerified(verified);
861
862                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
863                        + " verified with result:" + verified + " and hosts:"
864                        + ivs.getHostsString());
865            }
866
867            mIntentFilterVerificationStates.remove(verificationId);
868
869            final String packageName = ivs.getPackageName();
870            IntentFilterVerificationInfo ivi = null;
871
872            synchronized (mPackages) {
873                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
874            }
875            if (ivi == null) {
876                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
877                        + verificationId + " packageName:" + packageName);
878                return;
879            }
880            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
881                    "Updating IntentFilterVerificationInfo for package " + packageName
882                            +" verificationId:" + verificationId);
883
884            synchronized (mPackages) {
885                if (verified) {
886                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
887                } else {
888                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
889                }
890                scheduleWriteSettingsLocked();
891
892                final int userId = ivs.getUserId();
893                if (userId != UserHandle.USER_ALL) {
894                    final int userStatus =
895                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
896
897                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
898                    boolean needUpdate = false;
899
900                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
901                    // already been set by the User thru the Disambiguation dialog
902                    switch (userStatus) {
903                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
904                            if (verified) {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
906                            } else {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
908                            }
909                            needUpdate = true;
910                            break;
911
912                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
913                            if (verified) {
914                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
915                                needUpdate = true;
916                            }
917                            break;
918
919                        default:
920                            // Nothing to do
921                    }
922
923                    if (needUpdate) {
924                        mSettings.updateIntentFilterVerificationStatusLPw(
925                                packageName, updatedStatus, userId);
926                        scheduleWritePackageRestrictionsLocked(userId);
927                    }
928                }
929            }
930        }
931
932        @Override
933        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
934                    ActivityIntentInfo filter, String packageName) {
935            if (!hasValidDomains(filter)) {
936                return false;
937            }
938            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
939            if (ivs == null) {
940                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
941                        packageName);
942            }
943            if (DEBUG_DOMAIN_VERIFICATION) {
944                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
945            }
946            ivs.addFilter(filter);
947            return true;
948        }
949
950        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
951                int userId, int verificationId, String packageName) {
952            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
953                    verifierUid, userId, packageName);
954            ivs.setPendingState();
955            synchronized (mPackages) {
956                mIntentFilterVerificationStates.append(verificationId, ivs);
957                mCurrentIntentFilterVerifications.add(verificationId);
958            }
959            return ivs;
960        }
961    }
962
963    private static boolean hasValidDomains(ActivityIntentInfo filter) {
964        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
965                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
966                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
967    }
968
969    // Set of pending broadcasts for aggregating enable/disable of components.
970    static class PendingPackageBroadcasts {
971        // for each user id, a map of <package name -> components within that package>
972        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
973
974        public PendingPackageBroadcasts() {
975            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
976        }
977
978        public ArrayList<String> get(int userId, String packageName) {
979            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
980            return packages.get(packageName);
981        }
982
983        public void put(int userId, String packageName, ArrayList<String> components) {
984            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
985            packages.put(packageName, components);
986        }
987
988        public void remove(int userId, String packageName) {
989            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
990            if (packages != null) {
991                packages.remove(packageName);
992            }
993        }
994
995        public void remove(int userId) {
996            mUidMap.remove(userId);
997        }
998
999        public int userIdCount() {
1000            return mUidMap.size();
1001        }
1002
1003        public int userIdAt(int n) {
1004            return mUidMap.keyAt(n);
1005        }
1006
1007        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1008            return mUidMap.get(userId);
1009        }
1010
1011        public int size() {
1012            // total number of pending broadcast entries across all userIds
1013            int num = 0;
1014            for (int i = 0; i< mUidMap.size(); i++) {
1015                num += mUidMap.valueAt(i).size();
1016            }
1017            return num;
1018        }
1019
1020        public void clear() {
1021            mUidMap.clear();
1022        }
1023
1024        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1025            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1026            if (map == null) {
1027                map = new ArrayMap<String, ArrayList<String>>();
1028                mUidMap.put(userId, map);
1029            }
1030            return map;
1031        }
1032    }
1033    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1034
1035    // Service Connection to remote media container service to copy
1036    // package uri's from external media onto secure containers
1037    // or internal storage.
1038    private IMediaContainerService mContainerService = null;
1039
1040    static final int SEND_PENDING_BROADCAST = 1;
1041    static final int MCS_BOUND = 3;
1042    static final int END_COPY = 4;
1043    static final int INIT_COPY = 5;
1044    static final int MCS_UNBIND = 6;
1045    static final int START_CLEANING_PACKAGE = 7;
1046    static final int FIND_INSTALL_LOC = 8;
1047    static final int POST_INSTALL = 9;
1048    static final int MCS_RECONNECT = 10;
1049    static final int MCS_GIVE_UP = 11;
1050    static final int UPDATED_MEDIA_STATUS = 12;
1051    static final int WRITE_SETTINGS = 13;
1052    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1053    static final int PACKAGE_VERIFIED = 15;
1054    static final int CHECK_PENDING_VERIFICATION = 16;
1055    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1056    static final int INTENT_FILTER_VERIFIED = 18;
1057    static final int WRITE_PACKAGE_LIST = 19;
1058
1059    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1060
1061    // Delay time in millisecs
1062    static final int BROADCAST_DELAY = 10 * 1000;
1063
1064    static UserManagerService sUserManager;
1065
1066    // Stores a list of users whose package restrictions file needs to be updated
1067    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1068
1069    final private DefaultContainerConnection mDefContainerConn =
1070            new DefaultContainerConnection();
1071    class DefaultContainerConnection implements ServiceConnection {
1072        public void onServiceConnected(ComponentName name, IBinder service) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1074            IMediaContainerService imcs =
1075                IMediaContainerService.Stub.asInterface(service);
1076            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1077        }
1078
1079        public void onServiceDisconnected(ComponentName name) {
1080            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1081        }
1082    }
1083
1084    // Recordkeeping of restore-after-install operations that are currently in flight
1085    // between the Package Manager and the Backup Manager
1086    static class PostInstallData {
1087        public InstallArgs args;
1088        public PackageInstalledInfo res;
1089
1090        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1091            args = _a;
1092            res = _r;
1093        }
1094    }
1095
1096    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1097    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1098
1099    // XML tags for backup/restore of various bits of state
1100    private static final String TAG_PREFERRED_BACKUP = "pa";
1101    private static final String TAG_DEFAULT_APPS = "da";
1102    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1103
1104    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1105    private static final String TAG_ALL_GRANTS = "rt-grants";
1106    private static final String TAG_GRANT = "grant";
1107    private static final String ATTR_PACKAGE_NAME = "pkg";
1108
1109    private static final String TAG_PERMISSION = "perm";
1110    private static final String ATTR_PERMISSION_NAME = "name";
1111    private static final String ATTR_IS_GRANTED = "g";
1112    private static final String ATTR_USER_SET = "set";
1113    private static final String ATTR_USER_FIXED = "fixed";
1114    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1115
1116    // System/policy permission grants are not backed up
1117    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1118            FLAG_PERMISSION_POLICY_FIXED
1119            | FLAG_PERMISSION_SYSTEM_FIXED
1120            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1121
1122    // And we back up these user-adjusted states
1123    private static final int USER_RUNTIME_GRANT_MASK =
1124            FLAG_PERMISSION_USER_SET
1125            | FLAG_PERMISSION_USER_FIXED
1126            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1127
1128    final @Nullable String mRequiredVerifierPackage;
1129    final @NonNull String mRequiredInstallerPackage;
1130    final @Nullable String mSetupWizardPackage;
1131    final @NonNull String mServicesSystemSharedLibraryPackageName;
1132    final @NonNull String mSharedSystemSharedLibraryPackageName;
1133
1134    private final PackageUsage mPackageUsage = new PackageUsage();
1135
1136    private class PackageUsage {
1137        private static final int WRITE_INTERVAL
1138            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1139
1140        private final Object mFileLock = new Object();
1141        private final AtomicLong mLastWritten = new AtomicLong(0);
1142        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1143
1144        private boolean mIsHistoricalPackageUsageAvailable = true;
1145
1146        boolean isHistoricalPackageUsageAvailable() {
1147            return mIsHistoricalPackageUsageAvailable;
1148        }
1149
1150        void write(boolean force) {
1151            if (force) {
1152                writeInternal();
1153                return;
1154            }
1155            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1156                && !DEBUG_DEXOPT) {
1157                return;
1158            }
1159            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1160                new Thread("PackageUsage_DiskWriter") {
1161                    @Override
1162                    public void run() {
1163                        try {
1164                            writeInternal();
1165                        } finally {
1166                            mBackgroundWriteRunning.set(false);
1167                        }
1168                    }
1169                }.start();
1170            }
1171        }
1172
1173        private void writeInternal() {
1174            synchronized (mPackages) {
1175                synchronized (mFileLock) {
1176                    AtomicFile file = getFile();
1177                    FileOutputStream f = null;
1178                    try {
1179                        f = file.startWrite();
1180                        BufferedOutputStream out = new BufferedOutputStream(f);
1181                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1182                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1183                        StringBuilder sb = new StringBuilder();
1184
1185                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1186                        sb.append('\n');
1187                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1188
1189                        for (PackageParser.Package pkg : mPackages.values()) {
1190                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1191                                continue;
1192                            }
1193                            sb.setLength(0);
1194                            sb.append(pkg.packageName);
1195                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1196                                sb.append(' ');
1197                                sb.append(usageTimeInMillis);
1198                            }
1199                            sb.append('\n');
1200                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1201                        }
1202                        out.flush();
1203                        file.finishWrite(f);
1204                    } catch (IOException e) {
1205                        if (f != null) {
1206                            file.failWrite(f);
1207                        }
1208                        Log.e(TAG, "Failed to write package usage times", e);
1209                    }
1210                }
1211            }
1212            mLastWritten.set(SystemClock.elapsedRealtime());
1213        }
1214
1215        void readLP() {
1216            synchronized (mFileLock) {
1217                AtomicFile file = getFile();
1218                BufferedInputStream in = null;
1219                try {
1220                    in = new BufferedInputStream(file.openRead());
1221                    StringBuffer sb = new StringBuffer();
1222
1223                    String firstLine = readLine(in, sb);
1224                    if (firstLine == null) {
1225                        // Empty file. Do nothing.
1226                    } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) {
1227                        readVersion1LP(in, sb);
1228                    } else {
1229                        readVersion0LP(in, sb, firstLine);
1230                    }
1231                } catch (FileNotFoundException expected) {
1232                    mIsHistoricalPackageUsageAvailable = false;
1233                } catch (IOException e) {
1234                    Log.w(TAG, "Failed to read package usage times", e);
1235                } finally {
1236                    IoUtils.closeQuietly(in);
1237                }
1238            }
1239            mLastWritten.set(SystemClock.elapsedRealtime());
1240        }
1241
1242        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1243                throws IOException {
1244            // Initial version of the file had no version number and stored one
1245            // package-timestamp pair per line.
1246            // Note that the first line has already been read from the InputStream.
1247            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1248                String[] tokens = line.split(" ");
1249                if (tokens.length != 2) {
1250                    throw new IOException("Failed to parse " + line +
1251                            " as package-timestamp pair.");
1252                }
1253
1254                String packageName = tokens[0];
1255                PackageParser.Package pkg = mPackages.get(packageName);
1256                if (pkg == null) {
1257                    continue;
1258                }
1259
1260                long timestamp = parseAsLong(tokens[1]);
1261                for (int reason = 0;
1262                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1263                        reason++) {
1264                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1265                }
1266            }
1267        }
1268
1269        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1270            // Version 1 of the file started with the corresponding version
1271            // number and then stored a package name and eight timestamps per line.
1272            String line;
1273            while ((line = readLine(in, sb)) != null) {
1274                String[] tokens = line.split(" ");
1275                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1276                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1277                }
1278
1279                String packageName = tokens[0];
1280                PackageParser.Package pkg = mPackages.get(packageName);
1281                if (pkg == null) {
1282                    continue;
1283                }
1284
1285                for (int reason = 0;
1286                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1287                        reason++) {
1288                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1289                }
1290            }
1291        }
1292
1293        private long parseAsLong(String token) throws IOException {
1294            try {
1295                return Long.parseLong(token);
1296            } catch (NumberFormatException e) {
1297                throw new IOException("Failed to parse " + token + " as a long.", e);
1298            }
1299        }
1300
1301        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1302            return readToken(in, sb, '\n');
1303        }
1304
1305        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1306                throws IOException {
1307            sb.setLength(0);
1308            while (true) {
1309                int ch = in.read();
1310                if (ch == -1) {
1311                    if (sb.length() == 0) {
1312                        return null;
1313                    }
1314                    throw new IOException("Unexpected EOF");
1315                }
1316                if (ch == endOfToken) {
1317                    return sb.toString();
1318                }
1319                sb.append((char)ch);
1320            }
1321        }
1322
1323        private AtomicFile getFile() {
1324            File dataDir = Environment.getDataDirectory();
1325            File systemDir = new File(dataDir, "system");
1326            File fname = new File(systemDir, "package-usage.list");
1327            return new AtomicFile(fname);
1328        }
1329
1330        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1331        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1332    }
1333
1334    class PackageHandler extends Handler {
1335        private boolean mBound = false;
1336        final ArrayList<HandlerParams> mPendingInstalls =
1337            new ArrayList<HandlerParams>();
1338
1339        private boolean connectToService() {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1341                    " DefaultContainerService");
1342            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1343            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1344            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1345                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1346                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1347                mBound = true;
1348                return true;
1349            }
1350            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1351            return false;
1352        }
1353
1354        private void disconnectService() {
1355            mContainerService = null;
1356            mBound = false;
1357            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1358            mContext.unbindService(mDefContainerConn);
1359            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1360        }
1361
1362        PackageHandler(Looper looper) {
1363            super(looper);
1364        }
1365
1366        public void handleMessage(Message msg) {
1367            try {
1368                doHandleMessage(msg);
1369            } finally {
1370                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1371            }
1372        }
1373
1374        void doHandleMessage(Message msg) {
1375            switch (msg.what) {
1376                case INIT_COPY: {
1377                    HandlerParams params = (HandlerParams) msg.obj;
1378                    int idx = mPendingInstalls.size();
1379                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1380                    // If a bind was already initiated we dont really
1381                    // need to do anything. The pending install
1382                    // will be processed later on.
1383                    if (!mBound) {
1384                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1385                                System.identityHashCode(mHandler));
1386                        // If this is the only one pending we might
1387                        // have to bind to the service again.
1388                        if (!connectToService()) {
1389                            Slog.e(TAG, "Failed to bind to media container service");
1390                            params.serviceError();
1391                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1392                                    System.identityHashCode(mHandler));
1393                            if (params.traceMethod != null) {
1394                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1395                                        params.traceCookie);
1396                            }
1397                            return;
1398                        } else {
1399                            // Once we bind to the service, the first
1400                            // pending request will be processed.
1401                            mPendingInstalls.add(idx, params);
1402                        }
1403                    } else {
1404                        mPendingInstalls.add(idx, params);
1405                        // Already bound to the service. Just make
1406                        // sure we trigger off processing the first request.
1407                        if (idx == 0) {
1408                            mHandler.sendEmptyMessage(MCS_BOUND);
1409                        }
1410                    }
1411                    break;
1412                }
1413                case MCS_BOUND: {
1414                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1415                    if (msg.obj != null) {
1416                        mContainerService = (IMediaContainerService) msg.obj;
1417                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1418                                System.identityHashCode(mHandler));
1419                    }
1420                    if (mContainerService == null) {
1421                        if (!mBound) {
1422                            // Something seriously wrong since we are not bound and we are not
1423                            // waiting for connection. Bail out.
1424                            Slog.e(TAG, "Cannot bind to media container service");
1425                            for (HandlerParams params : mPendingInstalls) {
1426                                // Indicate service bind error
1427                                params.serviceError();
1428                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1429                                        System.identityHashCode(params));
1430                                if (params.traceMethod != null) {
1431                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1432                                            params.traceMethod, params.traceCookie);
1433                                }
1434                                return;
1435                            }
1436                            mPendingInstalls.clear();
1437                        } else {
1438                            Slog.w(TAG, "Waiting to connect to media container service");
1439                        }
1440                    } else if (mPendingInstalls.size() > 0) {
1441                        HandlerParams params = mPendingInstalls.get(0);
1442                        if (params != null) {
1443                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1444                                    System.identityHashCode(params));
1445                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1446                            if (params.startCopy()) {
1447                                // We are done...  look for more work or to
1448                                // go idle.
1449                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1450                                        "Checking for more work or unbind...");
1451                                // Delete pending install
1452                                if (mPendingInstalls.size() > 0) {
1453                                    mPendingInstalls.remove(0);
1454                                }
1455                                if (mPendingInstalls.size() == 0) {
1456                                    if (mBound) {
1457                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1458                                                "Posting delayed MCS_UNBIND");
1459                                        removeMessages(MCS_UNBIND);
1460                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1461                                        // Unbind after a little delay, to avoid
1462                                        // continual thrashing.
1463                                        sendMessageDelayed(ubmsg, 10000);
1464                                    }
1465                                } else {
1466                                    // There are more pending requests in queue.
1467                                    // Just post MCS_BOUND message to trigger processing
1468                                    // of next pending install.
1469                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1470                                            "Posting MCS_BOUND for next work");
1471                                    mHandler.sendEmptyMessage(MCS_BOUND);
1472                                }
1473                            }
1474                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1475                        }
1476                    } else {
1477                        // Should never happen ideally.
1478                        Slog.w(TAG, "Empty queue");
1479                    }
1480                    break;
1481                }
1482                case MCS_RECONNECT: {
1483                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1484                    if (mPendingInstalls.size() > 0) {
1485                        if (mBound) {
1486                            disconnectService();
1487                        }
1488                        if (!connectToService()) {
1489                            Slog.e(TAG, "Failed to bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                            }
1496                            mPendingInstalls.clear();
1497                        }
1498                    }
1499                    break;
1500                }
1501                case MCS_UNBIND: {
1502                    // If there is no actual work left, then time to unbind.
1503                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1504
1505                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1506                        if (mBound) {
1507                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1508
1509                            disconnectService();
1510                        }
1511                    } else if (mPendingInstalls.size() > 0) {
1512                        // There are more pending requests in queue.
1513                        // Just post MCS_BOUND message to trigger processing
1514                        // of next pending install.
1515                        mHandler.sendEmptyMessage(MCS_BOUND);
1516                    }
1517
1518                    break;
1519                }
1520                case MCS_GIVE_UP: {
1521                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1522                    HandlerParams params = mPendingInstalls.remove(0);
1523                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1524                            System.identityHashCode(params));
1525                    break;
1526                }
1527                case SEND_PENDING_BROADCAST: {
1528                    String packages[];
1529                    ArrayList<String> components[];
1530                    int size = 0;
1531                    int uids[];
1532                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1533                    synchronized (mPackages) {
1534                        if (mPendingBroadcasts == null) {
1535                            return;
1536                        }
1537                        size = mPendingBroadcasts.size();
1538                        if (size <= 0) {
1539                            // Nothing to be done. Just return
1540                            return;
1541                        }
1542                        packages = new String[size];
1543                        components = new ArrayList[size];
1544                        uids = new int[size];
1545                        int i = 0;  // filling out the above arrays
1546
1547                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1548                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1549                            Iterator<Map.Entry<String, ArrayList<String>>> it
1550                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1551                                            .entrySet().iterator();
1552                            while (it.hasNext() && i < size) {
1553                                Map.Entry<String, ArrayList<String>> ent = it.next();
1554                                packages[i] = ent.getKey();
1555                                components[i] = ent.getValue();
1556                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1557                                uids[i] = (ps != null)
1558                                        ? UserHandle.getUid(packageUserId, ps.appId)
1559                                        : -1;
1560                                i++;
1561                            }
1562                        }
1563                        size = i;
1564                        mPendingBroadcasts.clear();
1565                    }
1566                    // Send broadcasts
1567                    for (int i = 0; i < size; i++) {
1568                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1569                    }
1570                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1571                    break;
1572                }
1573                case START_CLEANING_PACKAGE: {
1574                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1575                    final String packageName = (String)msg.obj;
1576                    final int userId = msg.arg1;
1577                    final boolean andCode = msg.arg2 != 0;
1578                    synchronized (mPackages) {
1579                        if (userId == UserHandle.USER_ALL) {
1580                            int[] users = sUserManager.getUserIds();
1581                            for (int user : users) {
1582                                mSettings.addPackageToCleanLPw(
1583                                        new PackageCleanItem(user, packageName, andCode));
1584                            }
1585                        } else {
1586                            mSettings.addPackageToCleanLPw(
1587                                    new PackageCleanItem(userId, packageName, andCode));
1588                        }
1589                    }
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1591                    startCleaningPackages();
1592                } break;
1593                case POST_INSTALL: {
1594                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1595
1596                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1597                    final boolean didRestore = (msg.arg2 != 0);
1598                    mRunningInstalls.delete(msg.arg1);
1599
1600                    if (data != null) {
1601                        InstallArgs args = data.args;
1602                        PackageInstalledInfo parentRes = data.res;
1603
1604                        final boolean grantPermissions = (args.installFlags
1605                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1606                        final boolean killApp = (args.installFlags
1607                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1608                        final String[] grantedPermissions = args.installGrantPermissions;
1609
1610                        // Handle the parent package
1611                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1612                                grantedPermissions, didRestore, args.installerPackageName,
1613                                args.observer);
1614
1615                        // Handle the child packages
1616                        final int childCount = (parentRes.addedChildPackages != null)
1617                                ? parentRes.addedChildPackages.size() : 0;
1618                        for (int i = 0; i < childCount; i++) {
1619                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1620                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1621                                    grantedPermissions, false, args.installerPackageName,
1622                                    args.observer);
1623                        }
1624
1625                        // Log tracing if needed
1626                        if (args.traceMethod != null) {
1627                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1628                                    args.traceCookie);
1629                        }
1630                    } else {
1631                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1632                    }
1633
1634                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1635                } break;
1636                case UPDATED_MEDIA_STATUS: {
1637                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1638                    boolean reportStatus = msg.arg1 == 1;
1639                    boolean doGc = msg.arg2 == 1;
1640                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1641                    if (doGc) {
1642                        // Force a gc to clear up stale containers.
1643                        Runtime.getRuntime().gc();
1644                    }
1645                    if (msg.obj != null) {
1646                        @SuppressWarnings("unchecked")
1647                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1648                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1649                        // Unload containers
1650                        unloadAllContainers(args);
1651                    }
1652                    if (reportStatus) {
1653                        try {
1654                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1655                            PackageHelper.getMountService().finishMediaUpdate();
1656                        } catch (RemoteException e) {
1657                            Log.e(TAG, "MountService not running?");
1658                        }
1659                    }
1660                } break;
1661                case WRITE_SETTINGS: {
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1663                    synchronized (mPackages) {
1664                        removeMessages(WRITE_SETTINGS);
1665                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1666                        mSettings.writeLPr();
1667                        mDirtyUsers.clear();
1668                    }
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1670                } break;
1671                case WRITE_PACKAGE_RESTRICTIONS: {
1672                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1673                    synchronized (mPackages) {
1674                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1675                        for (int userId : mDirtyUsers) {
1676                            mSettings.writePackageRestrictionsLPr(userId);
1677                        }
1678                        mDirtyUsers.clear();
1679                    }
1680                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1681                } break;
1682                case WRITE_PACKAGE_LIST: {
1683                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1684                    synchronized (mPackages) {
1685                        removeMessages(WRITE_PACKAGE_LIST);
1686                        mSettings.writePackageListLPr(msg.arg1);
1687                    }
1688                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1689                } break;
1690                case CHECK_PENDING_VERIFICATION: {
1691                    final int verificationId = msg.arg1;
1692                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1693
1694                    if ((state != null) && !state.timeoutExtended()) {
1695                        final InstallArgs args = state.getInstallArgs();
1696                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1697
1698                        Slog.i(TAG, "Verification timed out for " + originUri);
1699                        mPendingVerification.remove(verificationId);
1700
1701                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1702
1703                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1704                            Slog.i(TAG, "Continuing with installation of " + originUri);
1705                            state.setVerifierResponse(Binder.getCallingUid(),
1706                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1707                            broadcastPackageVerified(verificationId, originUri,
1708                                    PackageManager.VERIFICATION_ALLOW,
1709                                    state.getInstallArgs().getUser());
1710                            try {
1711                                ret = args.copyApk(mContainerService, true);
1712                            } catch (RemoteException e) {
1713                                Slog.e(TAG, "Could not contact the ContainerService");
1714                            }
1715                        } else {
1716                            broadcastPackageVerified(verificationId, originUri,
1717                                    PackageManager.VERIFICATION_REJECT,
1718                                    state.getInstallArgs().getUser());
1719                        }
1720
1721                        Trace.asyncTraceEnd(
1722                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1723
1724                        processPendingInstall(args, ret);
1725                        mHandler.sendEmptyMessage(MCS_UNBIND);
1726                    }
1727                    break;
1728                }
1729                case PACKAGE_VERIFIED: {
1730                    final int verificationId = msg.arg1;
1731
1732                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1733                    if (state == null) {
1734                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1735                        break;
1736                    }
1737
1738                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1739
1740                    state.setVerifierResponse(response.callerUid, response.code);
1741
1742                    if (state.isVerificationComplete()) {
1743                        mPendingVerification.remove(verificationId);
1744
1745                        final InstallArgs args = state.getInstallArgs();
1746                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1747
1748                        int ret;
1749                        if (state.isInstallAllowed()) {
1750                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    response.code, state.getInstallArgs().getUser());
1753                            try {
1754                                ret = args.copyApk(mContainerService, true);
1755                            } catch (RemoteException e) {
1756                                Slog.e(TAG, "Could not contact the ContainerService");
1757                            }
1758                        } else {
1759                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1760                        }
1761
1762                        Trace.asyncTraceEnd(
1763                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1764
1765                        processPendingInstall(args, ret);
1766                        mHandler.sendEmptyMessage(MCS_UNBIND);
1767                    }
1768
1769                    break;
1770                }
1771                case START_INTENT_FILTER_VERIFICATIONS: {
1772                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1773                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1774                            params.replacing, params.pkg);
1775                    break;
1776                }
1777                case INTENT_FILTER_VERIFIED: {
1778                    final int verificationId = msg.arg1;
1779
1780                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1781                            verificationId);
1782                    if (state == null) {
1783                        Slog.w(TAG, "Invalid IntentFilter verification token "
1784                                + verificationId + " received");
1785                        break;
1786                    }
1787
1788                    final int userId = state.getUserId();
1789
1790                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1791                            "Processing IntentFilter verification with token:"
1792                            + verificationId + " and userId:" + userId);
1793
1794                    final IntentFilterVerificationResponse response =
1795                            (IntentFilterVerificationResponse) msg.obj;
1796
1797                    state.setVerifierResponse(response.callerUid, response.code);
1798
1799                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1800                            "IntentFilter verification with token:" + verificationId
1801                            + " and userId:" + userId
1802                            + " is settings verifier response with response code:"
1803                            + response.code);
1804
1805                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1806                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1807                                + response.getFailedDomainsString());
1808                    }
1809
1810                    if (state.isVerificationComplete()) {
1811                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1812                    } else {
1813                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1814                                "IntentFilter verification with token:" + verificationId
1815                                + " was not said to be complete");
1816                    }
1817
1818                    break;
1819                }
1820            }
1821        }
1822    }
1823
1824    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1825            boolean killApp, String[] grantedPermissions,
1826            boolean launchedForRestore, String installerPackage,
1827            IPackageInstallObserver2 installObserver) {
1828        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1829            // Send the removed broadcasts
1830            if (res.removedInfo != null) {
1831                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1832            }
1833
1834            // Now that we successfully installed the package, grant runtime
1835            // permissions if requested before broadcasting the install.
1836            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1837                    >= Build.VERSION_CODES.M) {
1838                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1839            }
1840
1841            final boolean update = res.removedInfo != null
1842                    && res.removedInfo.removedPackage != null;
1843
1844            // If this is the first time we have child packages for a disabled privileged
1845            // app that had no children, we grant requested runtime permissions to the new
1846            // children if the parent on the system image had them already granted.
1847            if (res.pkg.parentPackage != null) {
1848                synchronized (mPackages) {
1849                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1850                }
1851            }
1852
1853            synchronized (mPackages) {
1854                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1855            }
1856
1857            final String packageName = res.pkg.applicationInfo.packageName;
1858            Bundle extras = new Bundle(1);
1859            extras.putInt(Intent.EXTRA_UID, res.uid);
1860
1861            // Determine the set of users who are adding this package for
1862            // the first time vs. those who are seeing an update.
1863            int[] firstUsers = EMPTY_INT_ARRAY;
1864            int[] updateUsers = EMPTY_INT_ARRAY;
1865            if (res.origUsers == null || res.origUsers.length == 0) {
1866                firstUsers = res.newUsers;
1867            } else {
1868                for (int newUser : res.newUsers) {
1869                    boolean isNew = true;
1870                    for (int origUser : res.origUsers) {
1871                        if (origUser == newUser) {
1872                            isNew = false;
1873                            break;
1874                        }
1875                    }
1876                    if (isNew) {
1877                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1878                    } else {
1879                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1880                    }
1881                }
1882            }
1883
1884            // Send installed broadcasts if the install/update is not ephemeral
1885            if (!isEphemeral(res.pkg)) {
1886                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1887
1888                // Send added for users that see the package for the first time
1889                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1890                        extras, 0 /*flags*/, null /*targetPackage*/,
1891                        null /*finishedReceiver*/, firstUsers);
1892
1893                // Send added for users that don't see the package for the first time
1894                if (update) {
1895                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1896                }
1897                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1898                        extras, 0 /*flags*/, null /*targetPackage*/,
1899                        null /*finishedReceiver*/, updateUsers);
1900
1901                // Send replaced for users that don't see the package for the first time
1902                if (update) {
1903                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1904                            packageName, extras, 0 /*flags*/,
1905                            null /*targetPackage*/, null /*finishedReceiver*/,
1906                            updateUsers);
1907                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1908                            null /*package*/, null /*extras*/, 0 /*flags*/,
1909                            packageName /*targetPackage*/,
1910                            null /*finishedReceiver*/, updateUsers);
1911                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1912                    // First-install and we did a restore, so we're responsible for the
1913                    // first-launch broadcast.
1914                    if (DEBUG_BACKUP) {
1915                        Slog.i(TAG, "Post-restore of " + packageName
1916                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1917                    }
1918                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1919                }
1920
1921                // Send broadcast package appeared if forward locked/external for all users
1922                // treat asec-hosted packages like removable media on upgrade
1923                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1924                    if (DEBUG_INSTALL) {
1925                        Slog.i(TAG, "upgrading pkg " + res.pkg
1926                                + " is ASEC-hosted -> AVAILABLE");
1927                    }
1928                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1929                    ArrayList<String> pkgList = new ArrayList<>(1);
1930                    pkgList.add(packageName);
1931                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1932                }
1933            }
1934
1935            // Work that needs to happen on first install within each user
1936            if (firstUsers != null && firstUsers.length > 0) {
1937                synchronized (mPackages) {
1938                    for (int userId : firstUsers) {
1939                        // If this app is a browser and it's newly-installed for some
1940                        // users, clear any default-browser state in those users. The
1941                        // app's nature doesn't depend on the user, so we can just check
1942                        // its browser nature in any user and generalize.
1943                        if (packageIsBrowser(packageName, userId)) {
1944                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1945                        }
1946
1947                        // We may also need to apply pending (restored) runtime
1948                        // permission grants within these users.
1949                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1950                    }
1951                }
1952            }
1953
1954            // Log current value of "unknown sources" setting
1955            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1956                    getUnknownSourcesSettings());
1957
1958            // Force a gc to clear up things
1959            Runtime.getRuntime().gc();
1960
1961            // Remove the replaced package's older resources safely now
1962            // We delete after a gc for applications  on sdcard.
1963            if (res.removedInfo != null && res.removedInfo.args != null) {
1964                synchronized (mInstallLock) {
1965                    res.removedInfo.args.doPostDeleteLI(true);
1966                }
1967            }
1968        }
1969
1970        // If someone is watching installs - notify them
1971        if (installObserver != null) {
1972            try {
1973                Bundle extras = extrasForInstallResult(res);
1974                installObserver.onPackageInstalled(res.name, res.returnCode,
1975                        res.returnMsg, extras);
1976            } catch (RemoteException e) {
1977                Slog.i(TAG, "Observer no longer exists.");
1978            }
1979        }
1980    }
1981
1982    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1983            PackageParser.Package pkg) {
1984        if (pkg.parentPackage == null) {
1985            return;
1986        }
1987        if (pkg.requestedPermissions == null) {
1988            return;
1989        }
1990        final PackageSetting disabledSysParentPs = mSettings
1991                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1992        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1993                || !disabledSysParentPs.isPrivileged()
1994                || (disabledSysParentPs.childPackageNames != null
1995                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1996            return;
1997        }
1998        final int[] allUserIds = sUserManager.getUserIds();
1999        final int permCount = pkg.requestedPermissions.size();
2000        for (int i = 0; i < permCount; i++) {
2001            String permission = pkg.requestedPermissions.get(i);
2002            BasePermission bp = mSettings.mPermissions.get(permission);
2003            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2004                continue;
2005            }
2006            for (int userId : allUserIds) {
2007                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2008                        permission, userId)) {
2009                    grantRuntimePermission(pkg.packageName, permission, userId);
2010                }
2011            }
2012        }
2013    }
2014
2015    private StorageEventListener mStorageListener = new StorageEventListener() {
2016        @Override
2017        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2018            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2019                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2020                    final String volumeUuid = vol.getFsUuid();
2021
2022                    // Clean up any users or apps that were removed or recreated
2023                    // while this volume was missing
2024                    reconcileUsers(volumeUuid);
2025                    reconcileApps(volumeUuid);
2026
2027                    // Clean up any install sessions that expired or were
2028                    // cancelled while this volume was missing
2029                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2030
2031                    loadPrivatePackages(vol);
2032
2033                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2034                    unloadPrivatePackages(vol);
2035                }
2036            }
2037
2038            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2039                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2040                    updateExternalMediaStatus(true, false);
2041                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2042                    updateExternalMediaStatus(false, false);
2043                }
2044            }
2045        }
2046
2047        @Override
2048        public void onVolumeForgotten(String fsUuid) {
2049            if (TextUtils.isEmpty(fsUuid)) {
2050                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2051                return;
2052            }
2053
2054            // Remove any apps installed on the forgotten volume
2055            synchronized (mPackages) {
2056                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2057                for (PackageSetting ps : packages) {
2058                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2059                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2060                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2061                }
2062
2063                mSettings.onVolumeForgotten(fsUuid);
2064                mSettings.writeLPr();
2065            }
2066        }
2067    };
2068
2069    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2070            String[] grantedPermissions) {
2071        for (int userId : userIds) {
2072            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2073        }
2074
2075        // We could have touched GID membership, so flush out packages.list
2076        synchronized (mPackages) {
2077            mSettings.writePackageListLPr();
2078        }
2079    }
2080
2081    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2082            String[] grantedPermissions) {
2083        SettingBase sb = (SettingBase) pkg.mExtras;
2084        if (sb == null) {
2085            return;
2086        }
2087
2088        PermissionsState permissionsState = sb.getPermissionsState();
2089
2090        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2091                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2092
2093        for (String permission : pkg.requestedPermissions) {
2094            final BasePermission bp;
2095            synchronized (mPackages) {
2096                bp = mSettings.mPermissions.get(permission);
2097            }
2098            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2099                    && (grantedPermissions == null
2100                           || ArrayUtils.contains(grantedPermissions, permission))) {
2101                final int flags = permissionsState.getPermissionFlags(permission, userId);
2102                // Installer cannot change immutable permissions.
2103                if ((flags & immutableFlags) == 0) {
2104                    grantRuntimePermission(pkg.packageName, permission, userId);
2105                }
2106            }
2107        }
2108    }
2109
2110    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2111        Bundle extras = null;
2112        switch (res.returnCode) {
2113            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2114                extras = new Bundle();
2115                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2116                        res.origPermission);
2117                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2118                        res.origPackage);
2119                break;
2120            }
2121            case PackageManager.INSTALL_SUCCEEDED: {
2122                extras = new Bundle();
2123                extras.putBoolean(Intent.EXTRA_REPLACING,
2124                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2125                break;
2126            }
2127        }
2128        return extras;
2129    }
2130
2131    void scheduleWriteSettingsLocked() {
2132        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2133            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2134        }
2135    }
2136
2137    void scheduleWritePackageListLocked(int userId) {
2138        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2139            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2140            msg.arg1 = userId;
2141            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2142        }
2143    }
2144
2145    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2146        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2147        scheduleWritePackageRestrictionsLocked(userId);
2148    }
2149
2150    void scheduleWritePackageRestrictionsLocked(int userId) {
2151        final int[] userIds = (userId == UserHandle.USER_ALL)
2152                ? sUserManager.getUserIds() : new int[]{userId};
2153        for (int nextUserId : userIds) {
2154            if (!sUserManager.exists(nextUserId)) return;
2155            mDirtyUsers.add(nextUserId);
2156            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2157                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2158            }
2159        }
2160    }
2161
2162    public static PackageManagerService main(Context context, Installer installer,
2163            boolean factoryTest, boolean onlyCore) {
2164        // Self-check for initial settings.
2165        PackageManagerServiceCompilerMapping.checkProperties();
2166
2167        PackageManagerService m = new PackageManagerService(context, installer,
2168                factoryTest, onlyCore);
2169        m.enableSystemUserPackages();
2170        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2171        // disabled after already being started.
2172        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2173                UserHandle.USER_SYSTEM);
2174        ServiceManager.addService("package", m);
2175        return m;
2176    }
2177
2178    private void enableSystemUserPackages() {
2179        if (!UserManager.isSplitSystemUser()) {
2180            return;
2181        }
2182        // For system user, enable apps based on the following conditions:
2183        // - app is whitelisted or belong to one of these groups:
2184        //   -- system app which has no launcher icons
2185        //   -- system app which has INTERACT_ACROSS_USERS permission
2186        //   -- system IME app
2187        // - app is not in the blacklist
2188        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2189        Set<String> enableApps = new ArraySet<>();
2190        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2191                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2192                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2193        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2194        enableApps.addAll(wlApps);
2195        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2196                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2197        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2198        enableApps.removeAll(blApps);
2199        Log.i(TAG, "Applications installed for system user: " + enableApps);
2200        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2201                UserHandle.SYSTEM);
2202        final int allAppsSize = allAps.size();
2203        synchronized (mPackages) {
2204            for (int i = 0; i < allAppsSize; i++) {
2205                String pName = allAps.get(i);
2206                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2207                // Should not happen, but we shouldn't be failing if it does
2208                if (pkgSetting == null) {
2209                    continue;
2210                }
2211                boolean install = enableApps.contains(pName);
2212                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2213                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2214                            + " for system user");
2215                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2216                }
2217            }
2218        }
2219    }
2220
2221    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2222        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2223                Context.DISPLAY_SERVICE);
2224        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2225    }
2226
2227    /**
2228     * Requests that files preopted on a secondary system partition be copied to the data partition
2229     * if possible.  Note that the actual copying of the files is accomplished by init for security
2230     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2231     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2232     */
2233    private static void requestCopyPreoptedFiles() {
2234        final int WAIT_TIME_MS = 100;
2235        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2236        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2237            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2238            // We will wait for up to 100 seconds.
2239            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2240            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2241                try {
2242                    Thread.sleep(WAIT_TIME_MS);
2243                } catch (InterruptedException e) {
2244                    // Do nothing
2245                }
2246                if (SystemClock.uptimeMillis() > timeEnd) {
2247                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2248                    Slog.wtf(TAG, "cppreopt did not finish!");
2249                    break;
2250                }
2251            }
2252        }
2253    }
2254
2255    public PackageManagerService(Context context, Installer installer,
2256            boolean factoryTest, boolean onlyCore) {
2257        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2258                SystemClock.uptimeMillis());
2259
2260        if (mSdkVersion <= 0) {
2261            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2262        }
2263
2264        mContext = context;
2265        mFactoryTest = factoryTest;
2266        mOnlyCore = onlyCore;
2267        mMetrics = new DisplayMetrics();
2268        mSettings = new Settings(mPackages);
2269        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2270                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2271        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2272                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2273        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2274                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2275        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2276                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2277        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2278                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2279        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2280                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2281
2282        String separateProcesses = SystemProperties.get("debug.separate_processes");
2283        if (separateProcesses != null && separateProcesses.length() > 0) {
2284            if ("*".equals(separateProcesses)) {
2285                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2286                mSeparateProcesses = null;
2287                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2288            } else {
2289                mDefParseFlags = 0;
2290                mSeparateProcesses = separateProcesses.split(",");
2291                Slog.w(TAG, "Running with debug.separate_processes: "
2292                        + separateProcesses);
2293            }
2294        } else {
2295            mDefParseFlags = 0;
2296            mSeparateProcesses = null;
2297        }
2298
2299        mInstaller = installer;
2300        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2301                "*dexopt*");
2302        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2303
2304        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2305                FgThread.get().getLooper());
2306
2307        getDefaultDisplayMetrics(context, mMetrics);
2308
2309        SystemConfig systemConfig = SystemConfig.getInstance();
2310        mGlobalGids = systemConfig.getGlobalGids();
2311        mSystemPermissions = systemConfig.getSystemPermissions();
2312        mAvailableFeatures = systemConfig.getAvailableFeatures();
2313
2314        mProtectedPackages = new ProtectedPackages(mContext);
2315
2316        synchronized (mInstallLock) {
2317        // writer
2318        synchronized (mPackages) {
2319            mHandlerThread = new ServiceThread(TAG,
2320                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2321            mHandlerThread.start();
2322            mHandler = new PackageHandler(mHandlerThread.getLooper());
2323            mProcessLoggingHandler = new ProcessLoggingHandler();
2324            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2325
2326            File dataDir = Environment.getDataDirectory();
2327            mAppInstallDir = new File(dataDir, "app");
2328            mAppLib32InstallDir = new File(dataDir, "app-lib");
2329            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2330            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2331            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2332
2333            sUserManager = new UserManagerService(context, this, mPackages);
2334
2335            // Propagate permission configuration in to package manager.
2336            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2337                    = systemConfig.getPermissions();
2338            for (int i=0; i<permConfig.size(); i++) {
2339                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2340                BasePermission bp = mSettings.mPermissions.get(perm.name);
2341                if (bp == null) {
2342                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2343                    mSettings.mPermissions.put(perm.name, bp);
2344                }
2345                if (perm.gids != null) {
2346                    bp.setGids(perm.gids, perm.perUser);
2347                }
2348            }
2349
2350            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2351            for (int i=0; i<libConfig.size(); i++) {
2352                mSharedLibraries.put(libConfig.keyAt(i),
2353                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2354            }
2355
2356            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2357
2358            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2359
2360            if (mFirstBoot) {
2361                requestCopyPreoptedFiles();
2362            }
2363
2364            String customResolverActivity = Resources.getSystem().getString(
2365                    R.string.config_customResolverActivity);
2366            if (TextUtils.isEmpty(customResolverActivity)) {
2367                customResolverActivity = null;
2368            } else {
2369                mCustomResolverComponentName = ComponentName.unflattenFromString(
2370                        customResolverActivity);
2371            }
2372
2373            long startTime = SystemClock.uptimeMillis();
2374
2375            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2376                    startTime);
2377
2378            // Set flag to monitor and not change apk file paths when
2379            // scanning install directories.
2380            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2381
2382            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2383            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2384
2385            if (bootClassPath == null) {
2386                Slog.w(TAG, "No BOOTCLASSPATH found!");
2387            }
2388
2389            if (systemServerClassPath == null) {
2390                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2391            }
2392
2393            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2394            final String[] dexCodeInstructionSets =
2395                    getDexCodeInstructionSets(
2396                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2397
2398            /**
2399             * Ensure all external libraries have had dexopt run on them.
2400             */
2401            if (mSharedLibraries.size() > 0) {
2402                // NOTE: For now, we're compiling these system "shared libraries"
2403                // (and framework jars) into all available architectures. It's possible
2404                // to compile them only when we come across an app that uses them (there's
2405                // already logic for that in scanPackageLI) but that adds some complexity.
2406                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2407                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2408                        final String lib = libEntry.path;
2409                        if (lib == null) {
2410                            continue;
2411                        }
2412
2413                        try {
2414                            // Shared libraries do not have profiles so we perform a full
2415                            // AOT compilation (if needed).
2416                            int dexoptNeeded = DexFile.getDexOptNeeded(
2417                                    lib, dexCodeInstructionSet,
2418                                    getCompilerFilterForReason(REASON_SHARED_APK),
2419                                    false /* newProfile */);
2420                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2421                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2422                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2423                                        getCompilerFilterForReason(REASON_SHARED_APK),
2424                                        StorageManager.UUID_PRIVATE_INTERNAL,
2425                                        SKIP_SHARED_LIBRARY_CHECK);
2426                            }
2427                        } catch (FileNotFoundException e) {
2428                            Slog.w(TAG, "Library not found: " + lib);
2429                        } catch (IOException | InstallerException e) {
2430                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2431                                    + e.getMessage());
2432                        }
2433                    }
2434                }
2435            }
2436
2437            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2438
2439            final VersionInfo ver = mSettings.getInternalVersion();
2440            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2441
2442            // when upgrading from pre-M, promote system app permissions from install to runtime
2443            mPromoteSystemApps =
2444                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2445
2446            // When upgrading from pre-N, we need to handle package extraction like first boot,
2447            // as there is no profiling data available.
2448            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2449
2450            // save off the names of pre-existing system packages prior to scanning; we don't
2451            // want to automatically grant runtime permissions for new system apps
2452            if (mPromoteSystemApps) {
2453                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2454                while (pkgSettingIter.hasNext()) {
2455                    PackageSetting ps = pkgSettingIter.next();
2456                    if (isSystemApp(ps)) {
2457                        mExistingSystemPackages.add(ps.name);
2458                    }
2459                }
2460            }
2461
2462            // Collect vendor overlay packages.
2463            // (Do this before scanning any apps.)
2464            // For security and version matching reason, only consider
2465            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2466            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2467            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2468                    | PackageParser.PARSE_IS_SYSTEM
2469                    | PackageParser.PARSE_IS_SYSTEM_DIR
2470                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2471
2472            // Find base frameworks (resource packages without code).
2473            scanDirTracedLI(frameworkDir, mDefParseFlags
2474                    | PackageParser.PARSE_IS_SYSTEM
2475                    | PackageParser.PARSE_IS_SYSTEM_DIR
2476                    | PackageParser.PARSE_IS_PRIVILEGED,
2477                    scanFlags | SCAN_NO_DEX, 0);
2478
2479            // Collected privileged system packages.
2480            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2481            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2482                    | PackageParser.PARSE_IS_SYSTEM
2483                    | PackageParser.PARSE_IS_SYSTEM_DIR
2484                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2485
2486            // Collect ordinary system packages.
2487            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2488            scanDirTracedLI(systemAppDir, mDefParseFlags
2489                    | PackageParser.PARSE_IS_SYSTEM
2490                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2491
2492            // Collect all vendor packages.
2493            File vendorAppDir = new File("/vendor/app");
2494            try {
2495                vendorAppDir = vendorAppDir.getCanonicalFile();
2496            } catch (IOException e) {
2497                // failed to look up canonical path, continue with original one
2498            }
2499            scanDirTracedLI(vendorAppDir, mDefParseFlags
2500                    | PackageParser.PARSE_IS_SYSTEM
2501                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2502
2503            // Collect all OEM packages.
2504            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2505            scanDirTracedLI(oemAppDir, mDefParseFlags
2506                    | PackageParser.PARSE_IS_SYSTEM
2507                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2508
2509            // Prune any system packages that no longer exist.
2510            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2511            if (!mOnlyCore) {
2512                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2513                while (psit.hasNext()) {
2514                    PackageSetting ps = psit.next();
2515
2516                    /*
2517                     * If this is not a system app, it can't be a
2518                     * disable system app.
2519                     */
2520                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2521                        continue;
2522                    }
2523
2524                    /*
2525                     * If the package is scanned, it's not erased.
2526                     */
2527                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2528                    if (scannedPkg != null) {
2529                        /*
2530                         * If the system app is both scanned and in the
2531                         * disabled packages list, then it must have been
2532                         * added via OTA. Remove it from the currently
2533                         * scanned package so the previously user-installed
2534                         * application can be scanned.
2535                         */
2536                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2537                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2538                                    + ps.name + "; removing system app.  Last known codePath="
2539                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2540                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2541                                    + scannedPkg.mVersionCode);
2542                            removePackageLI(scannedPkg, true);
2543                            mExpectingBetter.put(ps.name, ps.codePath);
2544                        }
2545
2546                        continue;
2547                    }
2548
2549                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2550                        psit.remove();
2551                        logCriticalInfo(Log.WARN, "System package " + ps.name
2552                                + " no longer exists; it's data will be wiped");
2553                        // Actual deletion of code and data will be handled by later
2554                        // reconciliation step
2555                    } else {
2556                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2557                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2558                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2559                        }
2560                    }
2561                }
2562            }
2563
2564            //look for any incomplete package installations
2565            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2566            for (int i = 0; i < deletePkgsList.size(); i++) {
2567                // Actual deletion of code and data will be handled by later
2568                // reconciliation step
2569                final String packageName = deletePkgsList.get(i).name;
2570                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2571                synchronized (mPackages) {
2572                    mSettings.removePackageLPw(packageName);
2573                }
2574            }
2575
2576            //delete tmp files
2577            deleteTempPackageFiles();
2578
2579            // Remove any shared userIDs that have no associated packages
2580            mSettings.pruneSharedUsersLPw();
2581
2582            if (!mOnlyCore) {
2583                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2584                        SystemClock.uptimeMillis());
2585                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2586
2587                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2588                        | PackageParser.PARSE_FORWARD_LOCK,
2589                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2590
2591                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2592                        | PackageParser.PARSE_IS_EPHEMERAL,
2593                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2594
2595                /**
2596                 * Remove disable package settings for any updated system
2597                 * apps that were removed via an OTA. If they're not a
2598                 * previously-updated app, remove them completely.
2599                 * Otherwise, just revoke their system-level permissions.
2600                 */
2601                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2602                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2603                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2604
2605                    String msg;
2606                    if (deletedPkg == null) {
2607                        msg = "Updated system package " + deletedAppName
2608                                + " no longer exists; it's data will be wiped";
2609                        // Actual deletion of code and data will be handled by later
2610                        // reconciliation step
2611                    } else {
2612                        msg = "Updated system app + " + deletedAppName
2613                                + " no longer present; removing system privileges for "
2614                                + deletedAppName;
2615
2616                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2617
2618                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2619                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2620                    }
2621                    logCriticalInfo(Log.WARN, msg);
2622                }
2623
2624                /**
2625                 * Make sure all system apps that we expected to appear on
2626                 * the userdata partition actually showed up. If they never
2627                 * appeared, crawl back and revive the system version.
2628                 */
2629                for (int i = 0; i < mExpectingBetter.size(); i++) {
2630                    final String packageName = mExpectingBetter.keyAt(i);
2631                    if (!mPackages.containsKey(packageName)) {
2632                        final File scanFile = mExpectingBetter.valueAt(i);
2633
2634                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2635                                + " but never showed up; reverting to system");
2636
2637                        int reparseFlags = mDefParseFlags;
2638                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2639                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2640                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2641                                    | PackageParser.PARSE_IS_PRIVILEGED;
2642                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2643                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2644                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2645                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2646                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2647                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2648                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2649                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2650                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2651                        } else {
2652                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2653                            continue;
2654                        }
2655
2656                        mSettings.enableSystemPackageLPw(packageName);
2657
2658                        try {
2659                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2660                        } catch (PackageManagerException e) {
2661                            Slog.e(TAG, "Failed to parse original system package: "
2662                                    + e.getMessage());
2663                        }
2664                    }
2665                }
2666            }
2667            mExpectingBetter.clear();
2668
2669            // Resolve protected action filters. Only the setup wizard is allowed to
2670            // have a high priority filter for these actions.
2671            mSetupWizardPackage = getSetupWizardPackageName();
2672            if (mProtectedFilters.size() > 0) {
2673                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2674                    Slog.i(TAG, "No setup wizard;"
2675                        + " All protected intents capped to priority 0");
2676                }
2677                for (ActivityIntentInfo filter : mProtectedFilters) {
2678                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2679                        if (DEBUG_FILTERS) {
2680                            Slog.i(TAG, "Found setup wizard;"
2681                                + " allow priority " + filter.getPriority() + ";"
2682                                + " package: " + filter.activity.info.packageName
2683                                + " activity: " + filter.activity.className
2684                                + " priority: " + filter.getPriority());
2685                        }
2686                        // skip setup wizard; allow it to keep the high priority filter
2687                        continue;
2688                    }
2689                    Slog.w(TAG, "Protected action; cap priority to 0;"
2690                            + " package: " + filter.activity.info.packageName
2691                            + " activity: " + filter.activity.className
2692                            + " origPrio: " + filter.getPriority());
2693                    filter.setPriority(0);
2694                }
2695            }
2696            mDeferProtectedFilters = false;
2697            mProtectedFilters.clear();
2698
2699            // Now that we know all of the shared libraries, update all clients to have
2700            // the correct library paths.
2701            updateAllSharedLibrariesLPw();
2702
2703            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2704                // NOTE: We ignore potential failures here during a system scan (like
2705                // the rest of the commands above) because there's precious little we
2706                // can do about it. A settings error is reported, though.
2707                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2708                        false /* boot complete */);
2709            }
2710
2711            // Now that we know all the packages we are keeping,
2712            // read and update their last usage times.
2713            mPackageUsage.readLP();
2714
2715            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2716                    SystemClock.uptimeMillis());
2717            Slog.i(TAG, "Time to scan packages: "
2718                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2719                    + " seconds");
2720
2721            // If the platform SDK has changed since the last time we booted,
2722            // we need to re-grant app permission to catch any new ones that
2723            // appear.  This is really a hack, and means that apps can in some
2724            // cases get permissions that the user didn't initially explicitly
2725            // allow...  it would be nice to have some better way to handle
2726            // this situation.
2727            int updateFlags = UPDATE_PERMISSIONS_ALL;
2728            if (ver.sdkVersion != mSdkVersion) {
2729                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2730                        + mSdkVersion + "; regranting permissions for internal storage");
2731                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2732            }
2733            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2734            ver.sdkVersion = mSdkVersion;
2735
2736            // If this is the first boot or an update from pre-M, and it is a normal
2737            // boot, then we need to initialize the default preferred apps across
2738            // all defined users.
2739            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2740                for (UserInfo user : sUserManager.getUsers(true)) {
2741                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2742                    applyFactoryDefaultBrowserLPw(user.id);
2743                    primeDomainVerificationsLPw(user.id);
2744                }
2745            }
2746
2747            // Prepare storage for system user really early during boot,
2748            // since core system apps like SettingsProvider and SystemUI
2749            // can't wait for user to start
2750            final int storageFlags;
2751            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2752                storageFlags = StorageManager.FLAG_STORAGE_DE;
2753            } else {
2754                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2755            }
2756            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2757                    storageFlags);
2758
2759            // If this is first boot after an OTA, and a normal boot, then
2760            // we need to clear code cache directories.
2761            // Note that we do *not* clear the application profiles. These remain valid
2762            // across OTAs and are used to drive profile verification (post OTA) and
2763            // profile compilation (without waiting to collect a fresh set of profiles).
2764            if (mIsUpgrade && !onlyCore) {
2765                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2766                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2767                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2768                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2769                        // No apps are running this early, so no need to freeze
2770                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2771                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2772                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2773                    }
2774                }
2775                ver.fingerprint = Build.FINGERPRINT;
2776            }
2777
2778            checkDefaultBrowser();
2779
2780            // clear only after permissions and other defaults have been updated
2781            mExistingSystemPackages.clear();
2782            mPromoteSystemApps = false;
2783
2784            // All the changes are done during package scanning.
2785            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2786
2787            // can downgrade to reader
2788            mSettings.writeLPr();
2789
2790            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2791            // early on (before the package manager declares itself as early) because other
2792            // components in the system server might ask for package contexts for these apps.
2793            //
2794            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2795            // (i.e, that the data partition is unavailable).
2796            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2797                long start = System.nanoTime();
2798                List<PackageParser.Package> coreApps = new ArrayList<>();
2799                for (PackageParser.Package pkg : mPackages.values()) {
2800                    if (pkg.coreApp) {
2801                        coreApps.add(pkg);
2802                    }
2803                }
2804
2805                int[] stats = performDexOptUpgrade(coreApps, false,
2806                        getCompilerFilterForReason(REASON_CORE_APP));
2807
2808                final int elapsedTimeSeconds =
2809                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2810                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2811
2812                if (DEBUG_DEXOPT) {
2813                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2814                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2815                }
2816
2817
2818                // TODO: Should we log these stats to tron too ?
2819                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2820                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2821                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2822                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2823            }
2824
2825            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2826                    SystemClock.uptimeMillis());
2827
2828            if (!mOnlyCore) {
2829                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2830                mRequiredInstallerPackage = getRequiredInstallerLPr();
2831                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2832                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2833                        mIntentFilterVerifierComponent);
2834                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2835                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2836                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2837                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2838            } else {
2839                mRequiredVerifierPackage = null;
2840                mRequiredInstallerPackage = null;
2841                mIntentFilterVerifierComponent = null;
2842                mIntentFilterVerifier = null;
2843                mServicesSystemSharedLibraryPackageName = null;
2844                mSharedSystemSharedLibraryPackageName = null;
2845            }
2846
2847            mInstallerService = new PackageInstallerService(context, this);
2848
2849            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2850            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2851            // both the installer and resolver must be present to enable ephemeral
2852            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2853                if (DEBUG_EPHEMERAL) {
2854                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2855                            + " installer:" + ephemeralInstallerComponent);
2856                }
2857                mEphemeralResolverComponent = ephemeralResolverComponent;
2858                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2859                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2860                mEphemeralResolverConnection =
2861                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2862            } else {
2863                if (DEBUG_EPHEMERAL) {
2864                    final String missingComponent =
2865                            (ephemeralResolverComponent == null)
2866                            ? (ephemeralInstallerComponent == null)
2867                                    ? "resolver and installer"
2868                                    : "resolver"
2869                            : "installer";
2870                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2871                }
2872                mEphemeralResolverComponent = null;
2873                mEphemeralInstallerComponent = null;
2874                mEphemeralResolverConnection = null;
2875            }
2876
2877            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2878        } // synchronized (mPackages)
2879        } // synchronized (mInstallLock)
2880
2881        // Now after opening every single application zip, make sure they
2882        // are all flushed.  Not really needed, but keeps things nice and
2883        // tidy.
2884        Runtime.getRuntime().gc();
2885
2886        // The initial scanning above does many calls into installd while
2887        // holding the mPackages lock, but we're mostly interested in yelling
2888        // once we have a booted system.
2889        mInstaller.setWarnIfHeld(mPackages);
2890
2891        // Expose private service for system components to use.
2892        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2893    }
2894
2895    @Override
2896    public boolean isFirstBoot() {
2897        return mFirstBoot;
2898    }
2899
2900    @Override
2901    public boolean isOnlyCoreApps() {
2902        return mOnlyCore;
2903    }
2904
2905    @Override
2906    public boolean isUpgrade() {
2907        return mIsUpgrade;
2908    }
2909
2910    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2911        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2912
2913        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2914                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2915                UserHandle.USER_SYSTEM);
2916        if (matches.size() == 1) {
2917            return matches.get(0).getComponentInfo().packageName;
2918        } else {
2919            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2920            return null;
2921        }
2922    }
2923
2924    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2925        synchronized (mPackages) {
2926            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2927            if (libraryEntry == null) {
2928                throw new IllegalStateException("Missing required shared library:" + libraryName);
2929            }
2930            return libraryEntry.apk;
2931        }
2932    }
2933
2934    private @NonNull String getRequiredInstallerLPr() {
2935        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2936        intent.addCategory(Intent.CATEGORY_DEFAULT);
2937        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2938
2939        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2940                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2941                UserHandle.USER_SYSTEM);
2942        if (matches.size() == 1) {
2943            ResolveInfo resolveInfo = matches.get(0);
2944            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2945                throw new RuntimeException("The installer must be a privileged app");
2946            }
2947            return matches.get(0).getComponentInfo().packageName;
2948        } else {
2949            throw new RuntimeException("There must be exactly one installer; found " + matches);
2950        }
2951    }
2952
2953    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2954        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2955
2956        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2957                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2958                UserHandle.USER_SYSTEM);
2959        ResolveInfo best = null;
2960        final int N = matches.size();
2961        for (int i = 0; i < N; i++) {
2962            final ResolveInfo cur = matches.get(i);
2963            final String packageName = cur.getComponentInfo().packageName;
2964            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2965                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2966                continue;
2967            }
2968
2969            if (best == null || cur.priority > best.priority) {
2970                best = cur;
2971            }
2972        }
2973
2974        if (best != null) {
2975            return best.getComponentInfo().getComponentName();
2976        } else {
2977            throw new RuntimeException("There must be at least one intent filter verifier");
2978        }
2979    }
2980
2981    private @Nullable ComponentName getEphemeralResolverLPr() {
2982        final String[] packageArray =
2983                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2984        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2985            if (DEBUG_EPHEMERAL) {
2986                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2987            }
2988            return null;
2989        }
2990
2991        final int resolveFlags =
2992                MATCH_DIRECT_BOOT_AWARE
2993                | MATCH_DIRECT_BOOT_UNAWARE
2994                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2995        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2996        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2997                resolveFlags, UserHandle.USER_SYSTEM);
2998
2999        final int N = resolvers.size();
3000        if (N == 0) {
3001            if (DEBUG_EPHEMERAL) {
3002                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3003            }
3004            return null;
3005        }
3006
3007        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3008        for (int i = 0; i < N; i++) {
3009            final ResolveInfo info = resolvers.get(i);
3010
3011            if (info.serviceInfo == null) {
3012                continue;
3013            }
3014
3015            final String packageName = info.serviceInfo.packageName;
3016            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3017                if (DEBUG_EPHEMERAL) {
3018                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3019                            + " pkg: " + packageName + ", info:" + info);
3020                }
3021                continue;
3022            }
3023
3024            if (DEBUG_EPHEMERAL) {
3025                Slog.v(TAG, "Ephemeral resolver found;"
3026                        + " pkg: " + packageName + ", info:" + info);
3027            }
3028            return new ComponentName(packageName, info.serviceInfo.name);
3029        }
3030        if (DEBUG_EPHEMERAL) {
3031            Slog.v(TAG, "Ephemeral resolver NOT found");
3032        }
3033        return null;
3034    }
3035
3036    private @Nullable ComponentName getEphemeralInstallerLPr() {
3037        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3038        intent.addCategory(Intent.CATEGORY_DEFAULT);
3039        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3040
3041        final int resolveFlags =
3042                MATCH_DIRECT_BOOT_AWARE
3043                | MATCH_DIRECT_BOOT_UNAWARE
3044                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3045        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3046                resolveFlags, UserHandle.USER_SYSTEM);
3047        if (matches.size() == 0) {
3048            return null;
3049        } else if (matches.size() == 1) {
3050            return matches.get(0).getComponentInfo().getComponentName();
3051        } else {
3052            throw new RuntimeException(
3053                    "There must be at most one ephemeral installer; found " + matches);
3054        }
3055    }
3056
3057    private void primeDomainVerificationsLPw(int userId) {
3058        if (DEBUG_DOMAIN_VERIFICATION) {
3059            Slog.d(TAG, "Priming domain verifications in user " + userId);
3060        }
3061
3062        SystemConfig systemConfig = SystemConfig.getInstance();
3063        ArraySet<String> packages = systemConfig.getLinkedApps();
3064        ArraySet<String> domains = new ArraySet<String>();
3065
3066        for (String packageName : packages) {
3067            PackageParser.Package pkg = mPackages.get(packageName);
3068            if (pkg != null) {
3069                if (!pkg.isSystemApp()) {
3070                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3071                    continue;
3072                }
3073
3074                domains.clear();
3075                for (PackageParser.Activity a : pkg.activities) {
3076                    for (ActivityIntentInfo filter : a.intents) {
3077                        if (hasValidDomains(filter)) {
3078                            domains.addAll(filter.getHostsList());
3079                        }
3080                    }
3081                }
3082
3083                if (domains.size() > 0) {
3084                    if (DEBUG_DOMAIN_VERIFICATION) {
3085                        Slog.v(TAG, "      + " + packageName);
3086                    }
3087                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3088                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3089                    // and then 'always' in the per-user state actually used for intent resolution.
3090                    final IntentFilterVerificationInfo ivi;
3091                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3092                            new ArrayList<String>(domains));
3093                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3094                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3095                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3096                } else {
3097                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3098                            + "' does not handle web links");
3099                }
3100            } else {
3101                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3102            }
3103        }
3104
3105        scheduleWritePackageRestrictionsLocked(userId);
3106        scheduleWriteSettingsLocked();
3107    }
3108
3109    private void applyFactoryDefaultBrowserLPw(int userId) {
3110        // The default browser app's package name is stored in a string resource,
3111        // with a product-specific overlay used for vendor customization.
3112        String browserPkg = mContext.getResources().getString(
3113                com.android.internal.R.string.default_browser);
3114        if (!TextUtils.isEmpty(browserPkg)) {
3115            // non-empty string => required to be a known package
3116            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3117            if (ps == null) {
3118                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3119                browserPkg = null;
3120            } else {
3121                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3122            }
3123        }
3124
3125        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3126        // default.  If there's more than one, just leave everything alone.
3127        if (browserPkg == null) {
3128            calculateDefaultBrowserLPw(userId);
3129        }
3130    }
3131
3132    private void calculateDefaultBrowserLPw(int userId) {
3133        List<String> allBrowsers = resolveAllBrowserApps(userId);
3134        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3135        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3136    }
3137
3138    private List<String> resolveAllBrowserApps(int userId) {
3139        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3140        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3141                PackageManager.MATCH_ALL, userId);
3142
3143        final int count = list.size();
3144        List<String> result = new ArrayList<String>(count);
3145        for (int i=0; i<count; i++) {
3146            ResolveInfo info = list.get(i);
3147            if (info.activityInfo == null
3148                    || !info.handleAllWebDataURI
3149                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3150                    || result.contains(info.activityInfo.packageName)) {
3151                continue;
3152            }
3153            result.add(info.activityInfo.packageName);
3154        }
3155
3156        return result;
3157    }
3158
3159    private boolean packageIsBrowser(String packageName, int userId) {
3160        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3161                PackageManager.MATCH_ALL, userId);
3162        final int N = list.size();
3163        for (int i = 0; i < N; i++) {
3164            ResolveInfo info = list.get(i);
3165            if (packageName.equals(info.activityInfo.packageName)) {
3166                return true;
3167            }
3168        }
3169        return false;
3170    }
3171
3172    private void checkDefaultBrowser() {
3173        final int myUserId = UserHandle.myUserId();
3174        final String packageName = getDefaultBrowserPackageName(myUserId);
3175        if (packageName != null) {
3176            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3177            if (info == null) {
3178                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3179                synchronized (mPackages) {
3180                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3181                }
3182            }
3183        }
3184    }
3185
3186    @Override
3187    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3188            throws RemoteException {
3189        try {
3190            return super.onTransact(code, data, reply, flags);
3191        } catch (RuntimeException e) {
3192            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3193                Slog.wtf(TAG, "Package Manager Crash", e);
3194            }
3195            throw e;
3196        }
3197    }
3198
3199    static int[] appendInts(int[] cur, int[] add) {
3200        if (add == null) return cur;
3201        if (cur == null) return add;
3202        final int N = add.length;
3203        for (int i=0; i<N; i++) {
3204            cur = appendInt(cur, add[i]);
3205        }
3206        return cur;
3207    }
3208
3209    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3210        if (!sUserManager.exists(userId)) return null;
3211        if (ps == null) {
3212            return null;
3213        }
3214        final PackageParser.Package p = ps.pkg;
3215        if (p == null) {
3216            return null;
3217        }
3218
3219        final PermissionsState permissionsState = ps.getPermissionsState();
3220
3221        // Compute GIDs only if requested
3222        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3223                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3224        // Compute granted permissions only if package has requested permissions
3225        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3226                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3227        final PackageUserState state = ps.readUserState(userId);
3228
3229        return PackageParser.generatePackageInfo(p, gids, flags,
3230                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3231    }
3232
3233    @Override
3234    public void checkPackageStartable(String packageName, int userId) {
3235        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3236
3237        synchronized (mPackages) {
3238            final PackageSetting ps = mSettings.mPackages.get(packageName);
3239            if (ps == null) {
3240                throw new SecurityException("Package " + packageName + " was not found!");
3241            }
3242
3243            if (!ps.getInstalled(userId)) {
3244                throw new SecurityException(
3245                        "Package " + packageName + " was not installed for user " + userId + "!");
3246            }
3247
3248            if (mSafeMode && !ps.isSystem()) {
3249                throw new SecurityException("Package " + packageName + " not a system app!");
3250            }
3251
3252            if (mFrozenPackages.contains(packageName)) {
3253                throw new SecurityException("Package " + packageName + " is currently frozen!");
3254            }
3255
3256            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3257                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3258                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3259            }
3260        }
3261    }
3262
3263    @Override
3264    public boolean isPackageAvailable(String packageName, int userId) {
3265        if (!sUserManager.exists(userId)) return false;
3266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3267                false /* requireFullPermission */, false /* checkShell */, "is package available");
3268        synchronized (mPackages) {
3269            PackageParser.Package p = mPackages.get(packageName);
3270            if (p != null) {
3271                final PackageSetting ps = (PackageSetting) p.mExtras;
3272                if (ps != null) {
3273                    final PackageUserState state = ps.readUserState(userId);
3274                    if (state != null) {
3275                        return PackageParser.isAvailable(state);
3276                    }
3277                }
3278            }
3279        }
3280        return false;
3281    }
3282
3283    @Override
3284    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3285        if (!sUserManager.exists(userId)) return null;
3286        flags = updateFlagsForPackage(flags, userId, packageName);
3287        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3288                false /* requireFullPermission */, false /* checkShell */, "get package info");
3289        // reader
3290        synchronized (mPackages) {
3291            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3292            PackageParser.Package p = null;
3293            if (matchFactoryOnly) {
3294                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3295                if (ps != null) {
3296                    return generatePackageInfo(ps, flags, userId);
3297                }
3298            }
3299            if (p == null) {
3300                p = mPackages.get(packageName);
3301                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3302                    return null;
3303                }
3304            }
3305            if (DEBUG_PACKAGE_INFO)
3306                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3307            if (p != null) {
3308                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3309            }
3310            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3311                final PackageSetting ps = mSettings.mPackages.get(packageName);
3312                return generatePackageInfo(ps, flags, userId);
3313            }
3314        }
3315        return null;
3316    }
3317
3318    @Override
3319    public String[] currentToCanonicalPackageNames(String[] names) {
3320        String[] out = new String[names.length];
3321        // reader
3322        synchronized (mPackages) {
3323            for (int i=names.length-1; i>=0; i--) {
3324                PackageSetting ps = mSettings.mPackages.get(names[i]);
3325                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3326            }
3327        }
3328        return out;
3329    }
3330
3331    @Override
3332    public String[] canonicalToCurrentPackageNames(String[] names) {
3333        String[] out = new String[names.length];
3334        // reader
3335        synchronized (mPackages) {
3336            for (int i=names.length-1; i>=0; i--) {
3337                String cur = mSettings.mRenamedPackages.get(names[i]);
3338                out[i] = cur != null ? cur : names[i];
3339            }
3340        }
3341        return out;
3342    }
3343
3344    @Override
3345    public int getPackageUid(String packageName, int flags, int userId) {
3346        if (!sUserManager.exists(userId)) return -1;
3347        flags = updateFlagsForPackage(flags, userId, packageName);
3348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3349                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3350
3351        // reader
3352        synchronized (mPackages) {
3353            final PackageParser.Package p = mPackages.get(packageName);
3354            if (p != null && p.isMatch(flags)) {
3355                return UserHandle.getUid(userId, p.applicationInfo.uid);
3356            }
3357            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3358                final PackageSetting ps = mSettings.mPackages.get(packageName);
3359                if (ps != null && ps.isMatch(flags)) {
3360                    return UserHandle.getUid(userId, ps.appId);
3361                }
3362            }
3363        }
3364
3365        return -1;
3366    }
3367
3368    @Override
3369    public int[] getPackageGids(String packageName, int flags, int userId) {
3370        if (!sUserManager.exists(userId)) return null;
3371        flags = updateFlagsForPackage(flags, userId, packageName);
3372        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3373                false /* requireFullPermission */, false /* checkShell */,
3374                "getPackageGids");
3375
3376        // reader
3377        synchronized (mPackages) {
3378            final PackageParser.Package p = mPackages.get(packageName);
3379            if (p != null && p.isMatch(flags)) {
3380                PackageSetting ps = (PackageSetting) p.mExtras;
3381                return ps.getPermissionsState().computeGids(userId);
3382            }
3383            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3384                final PackageSetting ps = mSettings.mPackages.get(packageName);
3385                if (ps != null && ps.isMatch(flags)) {
3386                    return ps.getPermissionsState().computeGids(userId);
3387                }
3388            }
3389        }
3390
3391        return null;
3392    }
3393
3394    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3395        if (bp.perm != null) {
3396            return PackageParser.generatePermissionInfo(bp.perm, flags);
3397        }
3398        PermissionInfo pi = new PermissionInfo();
3399        pi.name = bp.name;
3400        pi.packageName = bp.sourcePackage;
3401        pi.nonLocalizedLabel = bp.name;
3402        pi.protectionLevel = bp.protectionLevel;
3403        return pi;
3404    }
3405
3406    @Override
3407    public PermissionInfo getPermissionInfo(String name, int flags) {
3408        // reader
3409        synchronized (mPackages) {
3410            final BasePermission p = mSettings.mPermissions.get(name);
3411            if (p != null) {
3412                return generatePermissionInfo(p, flags);
3413            }
3414            return null;
3415        }
3416    }
3417
3418    @Override
3419    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3420            int flags) {
3421        // reader
3422        synchronized (mPackages) {
3423            if (group != null && !mPermissionGroups.containsKey(group)) {
3424                // This is thrown as NameNotFoundException
3425                return null;
3426            }
3427
3428            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3429            for (BasePermission p : mSettings.mPermissions.values()) {
3430                if (group == null) {
3431                    if (p.perm == null || p.perm.info.group == null) {
3432                        out.add(generatePermissionInfo(p, flags));
3433                    }
3434                } else {
3435                    if (p.perm != null && group.equals(p.perm.info.group)) {
3436                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3437                    }
3438                }
3439            }
3440            return new ParceledListSlice<>(out);
3441        }
3442    }
3443
3444    @Override
3445    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3446        // reader
3447        synchronized (mPackages) {
3448            return PackageParser.generatePermissionGroupInfo(
3449                    mPermissionGroups.get(name), flags);
3450        }
3451    }
3452
3453    @Override
3454    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3455        // reader
3456        synchronized (mPackages) {
3457            final int N = mPermissionGroups.size();
3458            ArrayList<PermissionGroupInfo> out
3459                    = new ArrayList<PermissionGroupInfo>(N);
3460            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3461                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3462            }
3463            return new ParceledListSlice<>(out);
3464        }
3465    }
3466
3467    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3468            int userId) {
3469        if (!sUserManager.exists(userId)) return null;
3470        PackageSetting ps = mSettings.mPackages.get(packageName);
3471        if (ps != null) {
3472            if (ps.pkg == null) {
3473                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3474                if (pInfo != null) {
3475                    return pInfo.applicationInfo;
3476                }
3477                return null;
3478            }
3479            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3480                    ps.readUserState(userId), userId);
3481        }
3482        return null;
3483    }
3484
3485    @Override
3486    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3487        if (!sUserManager.exists(userId)) return null;
3488        flags = updateFlagsForApplication(flags, userId, packageName);
3489        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3490                false /* requireFullPermission */, false /* checkShell */, "get application info");
3491        // writer
3492        synchronized (mPackages) {
3493            PackageParser.Package p = mPackages.get(packageName);
3494            if (DEBUG_PACKAGE_INFO) Log.v(
3495                    TAG, "getApplicationInfo " + packageName
3496                    + ": " + p);
3497            if (p != null) {
3498                PackageSetting ps = mSettings.mPackages.get(packageName);
3499                if (ps == null) return null;
3500                // Note: isEnabledLP() does not apply here - always return info
3501                return PackageParser.generateApplicationInfo(
3502                        p, flags, ps.readUserState(userId), userId);
3503            }
3504            if ("android".equals(packageName)||"system".equals(packageName)) {
3505                return mAndroidApplication;
3506            }
3507            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3508                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3509            }
3510        }
3511        return null;
3512    }
3513
3514    @Override
3515    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3516            final IPackageDataObserver observer) {
3517        mContext.enforceCallingOrSelfPermission(
3518                android.Manifest.permission.CLEAR_APP_CACHE, null);
3519        // Queue up an async operation since clearing cache may take a little while.
3520        mHandler.post(new Runnable() {
3521            public void run() {
3522                mHandler.removeCallbacks(this);
3523                boolean success = true;
3524                synchronized (mInstallLock) {
3525                    try {
3526                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3527                    } catch (InstallerException e) {
3528                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3529                        success = false;
3530                    }
3531                }
3532                if (observer != null) {
3533                    try {
3534                        observer.onRemoveCompleted(null, success);
3535                    } catch (RemoteException e) {
3536                        Slog.w(TAG, "RemoveException when invoking call back");
3537                    }
3538                }
3539            }
3540        });
3541    }
3542
3543    @Override
3544    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3545            final IntentSender pi) {
3546        mContext.enforceCallingOrSelfPermission(
3547                android.Manifest.permission.CLEAR_APP_CACHE, null);
3548        // Queue up an async operation since clearing cache may take a little while.
3549        mHandler.post(new Runnable() {
3550            public void run() {
3551                mHandler.removeCallbacks(this);
3552                boolean success = true;
3553                synchronized (mInstallLock) {
3554                    try {
3555                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3556                    } catch (InstallerException e) {
3557                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3558                        success = false;
3559                    }
3560                }
3561                if(pi != null) {
3562                    try {
3563                        // Callback via pending intent
3564                        int code = success ? 1 : 0;
3565                        pi.sendIntent(null, code, null,
3566                                null, null);
3567                    } catch (SendIntentException e1) {
3568                        Slog.i(TAG, "Failed to send pending intent");
3569                    }
3570                }
3571            }
3572        });
3573    }
3574
3575    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3576        synchronized (mInstallLock) {
3577            try {
3578                mInstaller.freeCache(volumeUuid, freeStorageSize);
3579            } catch (InstallerException e) {
3580                throw new IOException("Failed to free enough space", e);
3581            }
3582        }
3583    }
3584
3585    /**
3586     * Update given flags based on encryption status of current user.
3587     */
3588    private int updateFlags(int flags, int userId) {
3589        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3590                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3591            // Caller expressed an explicit opinion about what encryption
3592            // aware/unaware components they want to see, so fall through and
3593            // give them what they want
3594        } else {
3595            // Caller expressed no opinion, so match based on user state
3596            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3597                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3598            } else {
3599                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3600            }
3601        }
3602        return flags;
3603    }
3604
3605    private UserManagerInternal getUserManagerInternal() {
3606        if (mUserManagerInternal == null) {
3607            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3608        }
3609        return mUserManagerInternal;
3610    }
3611
3612    /**
3613     * Update given flags when being used to request {@link PackageInfo}.
3614     */
3615    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3616        boolean triaged = true;
3617        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3618                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3619            // Caller is asking for component details, so they'd better be
3620            // asking for specific encryption matching behavior, or be triaged
3621            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3622                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3623                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3624                triaged = false;
3625            }
3626        }
3627        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3628                | PackageManager.MATCH_SYSTEM_ONLY
3629                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3630            triaged = false;
3631        }
3632        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3633            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3634                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3635        }
3636        return updateFlags(flags, userId);
3637    }
3638
3639    /**
3640     * Update given flags when being used to request {@link ApplicationInfo}.
3641     */
3642    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3643        return updateFlagsForPackage(flags, userId, cookie);
3644    }
3645
3646    /**
3647     * Update given flags when being used to request {@link ComponentInfo}.
3648     */
3649    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3650        if (cookie instanceof Intent) {
3651            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3652                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3653            }
3654        }
3655
3656        boolean triaged = true;
3657        // Caller is asking for component details, so they'd better be
3658        // asking for specific encryption matching behavior, or be triaged
3659        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3660                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3661                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3662            triaged = false;
3663        }
3664        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3665            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3666                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3667        }
3668
3669        return updateFlags(flags, userId);
3670    }
3671
3672    /**
3673     * Update given flags when being used to request {@link ResolveInfo}.
3674     */
3675    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3676        // Safe mode means we shouldn't match any third-party components
3677        if (mSafeMode) {
3678            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3679        }
3680
3681        return updateFlagsForComponent(flags, userId, cookie);
3682    }
3683
3684    @Override
3685    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3686        if (!sUserManager.exists(userId)) return null;
3687        flags = updateFlagsForComponent(flags, userId, component);
3688        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3689                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3690        synchronized (mPackages) {
3691            PackageParser.Activity a = mActivities.mActivities.get(component);
3692
3693            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3694            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3695                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3696                if (ps == null) return null;
3697                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3698                        userId);
3699            }
3700            if (mResolveComponentName.equals(component)) {
3701                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3702                        new PackageUserState(), userId);
3703            }
3704        }
3705        return null;
3706    }
3707
3708    @Override
3709    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3710            String resolvedType) {
3711        synchronized (mPackages) {
3712            if (component.equals(mResolveComponentName)) {
3713                // The resolver supports EVERYTHING!
3714                return true;
3715            }
3716            PackageParser.Activity a = mActivities.mActivities.get(component);
3717            if (a == null) {
3718                return false;
3719            }
3720            for (int i=0; i<a.intents.size(); i++) {
3721                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3722                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3723                    return true;
3724                }
3725            }
3726            return false;
3727        }
3728    }
3729
3730    @Override
3731    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3732        if (!sUserManager.exists(userId)) return null;
3733        flags = updateFlagsForComponent(flags, userId, component);
3734        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3735                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3736        synchronized (mPackages) {
3737            PackageParser.Activity a = mReceivers.mActivities.get(component);
3738            if (DEBUG_PACKAGE_INFO) Log.v(
3739                TAG, "getReceiverInfo " + component + ": " + a);
3740            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3741                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3742                if (ps == null) return null;
3743                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3744                        userId);
3745            }
3746        }
3747        return null;
3748    }
3749
3750    @Override
3751    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3752        if (!sUserManager.exists(userId)) return null;
3753        flags = updateFlagsForComponent(flags, userId, component);
3754        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3755                false /* requireFullPermission */, false /* checkShell */, "get service info");
3756        synchronized (mPackages) {
3757            PackageParser.Service s = mServices.mServices.get(component);
3758            if (DEBUG_PACKAGE_INFO) Log.v(
3759                TAG, "getServiceInfo " + component + ": " + s);
3760            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3761                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3762                if (ps == null) return null;
3763                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3764                        userId);
3765            }
3766        }
3767        return null;
3768    }
3769
3770    @Override
3771    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3772        if (!sUserManager.exists(userId)) return null;
3773        flags = updateFlagsForComponent(flags, userId, component);
3774        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3775                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3776        synchronized (mPackages) {
3777            PackageParser.Provider p = mProviders.mProviders.get(component);
3778            if (DEBUG_PACKAGE_INFO) Log.v(
3779                TAG, "getProviderInfo " + component + ": " + p);
3780            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3781                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3782                if (ps == null) return null;
3783                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3784                        userId);
3785            }
3786        }
3787        return null;
3788    }
3789
3790    @Override
3791    public String[] getSystemSharedLibraryNames() {
3792        Set<String> libSet;
3793        synchronized (mPackages) {
3794            libSet = mSharedLibraries.keySet();
3795            int size = libSet.size();
3796            if (size > 0) {
3797                String[] libs = new String[size];
3798                libSet.toArray(libs);
3799                return libs;
3800            }
3801        }
3802        return null;
3803    }
3804
3805    @Override
3806    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3807        synchronized (mPackages) {
3808            return mServicesSystemSharedLibraryPackageName;
3809        }
3810    }
3811
3812    @Override
3813    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3814        synchronized (mPackages) {
3815            return mSharedSystemSharedLibraryPackageName;
3816        }
3817    }
3818
3819    @Override
3820    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3821        synchronized (mPackages) {
3822            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3823
3824            final FeatureInfo fi = new FeatureInfo();
3825            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3826                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3827            res.add(fi);
3828
3829            return new ParceledListSlice<>(res);
3830        }
3831    }
3832
3833    @Override
3834    public boolean hasSystemFeature(String name, int version) {
3835        synchronized (mPackages) {
3836            final FeatureInfo feat = mAvailableFeatures.get(name);
3837            if (feat == null) {
3838                return false;
3839            } else {
3840                return feat.version >= version;
3841            }
3842        }
3843    }
3844
3845    @Override
3846    public int checkPermission(String permName, String pkgName, int userId) {
3847        if (!sUserManager.exists(userId)) {
3848            return PackageManager.PERMISSION_DENIED;
3849        }
3850
3851        synchronized (mPackages) {
3852            final PackageParser.Package p = mPackages.get(pkgName);
3853            if (p != null && p.mExtras != null) {
3854                final PackageSetting ps = (PackageSetting) p.mExtras;
3855                final PermissionsState permissionsState = ps.getPermissionsState();
3856                if (permissionsState.hasPermission(permName, userId)) {
3857                    return PackageManager.PERMISSION_GRANTED;
3858                }
3859                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3860                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3861                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3862                    return PackageManager.PERMISSION_GRANTED;
3863                }
3864            }
3865        }
3866
3867        return PackageManager.PERMISSION_DENIED;
3868    }
3869
3870    @Override
3871    public int checkUidPermission(String permName, int uid) {
3872        final int userId = UserHandle.getUserId(uid);
3873
3874        if (!sUserManager.exists(userId)) {
3875            return PackageManager.PERMISSION_DENIED;
3876        }
3877
3878        synchronized (mPackages) {
3879            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3880            if (obj != null) {
3881                final SettingBase ps = (SettingBase) obj;
3882                final PermissionsState permissionsState = ps.getPermissionsState();
3883                if (permissionsState.hasPermission(permName, userId)) {
3884                    return PackageManager.PERMISSION_GRANTED;
3885                }
3886                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3887                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3888                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3889                    return PackageManager.PERMISSION_GRANTED;
3890                }
3891            } else {
3892                ArraySet<String> perms = mSystemPermissions.get(uid);
3893                if (perms != null) {
3894                    if (perms.contains(permName)) {
3895                        return PackageManager.PERMISSION_GRANTED;
3896                    }
3897                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3898                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3899                        return PackageManager.PERMISSION_GRANTED;
3900                    }
3901                }
3902            }
3903        }
3904
3905        return PackageManager.PERMISSION_DENIED;
3906    }
3907
3908    @Override
3909    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3910        if (UserHandle.getCallingUserId() != userId) {
3911            mContext.enforceCallingPermission(
3912                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3913                    "isPermissionRevokedByPolicy for user " + userId);
3914        }
3915
3916        if (checkPermission(permission, packageName, userId)
3917                == PackageManager.PERMISSION_GRANTED) {
3918            return false;
3919        }
3920
3921        final long identity = Binder.clearCallingIdentity();
3922        try {
3923            final int flags = getPermissionFlags(permission, packageName, userId);
3924            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3925        } finally {
3926            Binder.restoreCallingIdentity(identity);
3927        }
3928    }
3929
3930    @Override
3931    public String getPermissionControllerPackageName() {
3932        synchronized (mPackages) {
3933            return mRequiredInstallerPackage;
3934        }
3935    }
3936
3937    /**
3938     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3939     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3940     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3941     * @param message the message to log on security exception
3942     */
3943    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3944            boolean checkShell, String message) {
3945        if (userId < 0) {
3946            throw new IllegalArgumentException("Invalid userId " + userId);
3947        }
3948        if (checkShell) {
3949            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3950        }
3951        if (userId == UserHandle.getUserId(callingUid)) return;
3952        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3953            if (requireFullPermission) {
3954                mContext.enforceCallingOrSelfPermission(
3955                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3956            } else {
3957                try {
3958                    mContext.enforceCallingOrSelfPermission(
3959                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3960                } catch (SecurityException se) {
3961                    mContext.enforceCallingOrSelfPermission(
3962                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3963                }
3964            }
3965        }
3966    }
3967
3968    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3969        if (callingUid == Process.SHELL_UID) {
3970            if (userHandle >= 0
3971                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3972                throw new SecurityException("Shell does not have permission to access user "
3973                        + userHandle);
3974            } else if (userHandle < 0) {
3975                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3976                        + Debug.getCallers(3));
3977            }
3978        }
3979    }
3980
3981    private BasePermission findPermissionTreeLP(String permName) {
3982        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3983            if (permName.startsWith(bp.name) &&
3984                    permName.length() > bp.name.length() &&
3985                    permName.charAt(bp.name.length()) == '.') {
3986                return bp;
3987            }
3988        }
3989        return null;
3990    }
3991
3992    private BasePermission checkPermissionTreeLP(String permName) {
3993        if (permName != null) {
3994            BasePermission bp = findPermissionTreeLP(permName);
3995            if (bp != null) {
3996                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3997                    return bp;
3998                }
3999                throw new SecurityException("Calling uid "
4000                        + Binder.getCallingUid()
4001                        + " is not allowed to add to permission tree "
4002                        + bp.name + " owned by uid " + bp.uid);
4003            }
4004        }
4005        throw new SecurityException("No permission tree found for " + permName);
4006    }
4007
4008    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4009        if (s1 == null) {
4010            return s2 == null;
4011        }
4012        if (s2 == null) {
4013            return false;
4014        }
4015        if (s1.getClass() != s2.getClass()) {
4016            return false;
4017        }
4018        return s1.equals(s2);
4019    }
4020
4021    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4022        if (pi1.icon != pi2.icon) return false;
4023        if (pi1.logo != pi2.logo) return false;
4024        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4025        if (!compareStrings(pi1.name, pi2.name)) return false;
4026        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4027        // We'll take care of setting this one.
4028        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4029        // These are not currently stored in settings.
4030        //if (!compareStrings(pi1.group, pi2.group)) return false;
4031        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4032        //if (pi1.labelRes != pi2.labelRes) return false;
4033        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4034        return true;
4035    }
4036
4037    int permissionInfoFootprint(PermissionInfo info) {
4038        int size = info.name.length();
4039        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4040        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4041        return size;
4042    }
4043
4044    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4045        int size = 0;
4046        for (BasePermission perm : mSettings.mPermissions.values()) {
4047            if (perm.uid == tree.uid) {
4048                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4049            }
4050        }
4051        return size;
4052    }
4053
4054    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4055        // We calculate the max size of permissions defined by this uid and throw
4056        // if that plus the size of 'info' would exceed our stated maximum.
4057        if (tree.uid != Process.SYSTEM_UID) {
4058            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4059            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4060                throw new SecurityException("Permission tree size cap exceeded");
4061            }
4062        }
4063    }
4064
4065    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4066        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4067            throw new SecurityException("Label must be specified in permission");
4068        }
4069        BasePermission tree = checkPermissionTreeLP(info.name);
4070        BasePermission bp = mSettings.mPermissions.get(info.name);
4071        boolean added = bp == null;
4072        boolean changed = true;
4073        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4074        if (added) {
4075            enforcePermissionCapLocked(info, tree);
4076            bp = new BasePermission(info.name, tree.sourcePackage,
4077                    BasePermission.TYPE_DYNAMIC);
4078        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4079            throw new SecurityException(
4080                    "Not allowed to modify non-dynamic permission "
4081                    + info.name);
4082        } else {
4083            if (bp.protectionLevel == fixedLevel
4084                    && bp.perm.owner.equals(tree.perm.owner)
4085                    && bp.uid == tree.uid
4086                    && comparePermissionInfos(bp.perm.info, info)) {
4087                changed = false;
4088            }
4089        }
4090        bp.protectionLevel = fixedLevel;
4091        info = new PermissionInfo(info);
4092        info.protectionLevel = fixedLevel;
4093        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4094        bp.perm.info.packageName = tree.perm.info.packageName;
4095        bp.uid = tree.uid;
4096        if (added) {
4097            mSettings.mPermissions.put(info.name, bp);
4098        }
4099        if (changed) {
4100            if (!async) {
4101                mSettings.writeLPr();
4102            } else {
4103                scheduleWriteSettingsLocked();
4104            }
4105        }
4106        return added;
4107    }
4108
4109    @Override
4110    public boolean addPermission(PermissionInfo info) {
4111        synchronized (mPackages) {
4112            return addPermissionLocked(info, false);
4113        }
4114    }
4115
4116    @Override
4117    public boolean addPermissionAsync(PermissionInfo info) {
4118        synchronized (mPackages) {
4119            return addPermissionLocked(info, true);
4120        }
4121    }
4122
4123    @Override
4124    public void removePermission(String name) {
4125        synchronized (mPackages) {
4126            checkPermissionTreeLP(name);
4127            BasePermission bp = mSettings.mPermissions.get(name);
4128            if (bp != null) {
4129                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4130                    throw new SecurityException(
4131                            "Not allowed to modify non-dynamic permission "
4132                            + name);
4133                }
4134                mSettings.mPermissions.remove(name);
4135                mSettings.writeLPr();
4136            }
4137        }
4138    }
4139
4140    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4141            BasePermission bp) {
4142        int index = pkg.requestedPermissions.indexOf(bp.name);
4143        if (index == -1) {
4144            throw new SecurityException("Package " + pkg.packageName
4145                    + " has not requested permission " + bp.name);
4146        }
4147        if (!bp.isRuntime() && !bp.isDevelopment()) {
4148            throw new SecurityException("Permission " + bp.name
4149                    + " is not a changeable permission type");
4150        }
4151    }
4152
4153    @Override
4154    public void grantRuntimePermission(String packageName, String name, final int userId) {
4155        if (!sUserManager.exists(userId)) {
4156            Log.e(TAG, "No such user:" + userId);
4157            return;
4158        }
4159
4160        mContext.enforceCallingOrSelfPermission(
4161                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4162                "grantRuntimePermission");
4163
4164        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4165                true /* requireFullPermission */, true /* checkShell */,
4166                "grantRuntimePermission");
4167
4168        final int uid;
4169        final SettingBase sb;
4170
4171        synchronized (mPackages) {
4172            final PackageParser.Package pkg = mPackages.get(packageName);
4173            if (pkg == null) {
4174                throw new IllegalArgumentException("Unknown package: " + packageName);
4175            }
4176
4177            final BasePermission bp = mSettings.mPermissions.get(name);
4178            if (bp == null) {
4179                throw new IllegalArgumentException("Unknown permission: " + name);
4180            }
4181
4182            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4183
4184            // If a permission review is required for legacy apps we represent
4185            // their permissions as always granted runtime ones since we need
4186            // to keep the review required permission flag per user while an
4187            // install permission's state is shared across all users.
4188            if (Build.PERMISSIONS_REVIEW_REQUIRED
4189                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4190                    && bp.isRuntime()) {
4191                return;
4192            }
4193
4194            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4195            sb = (SettingBase) pkg.mExtras;
4196            if (sb == null) {
4197                throw new IllegalArgumentException("Unknown package: " + packageName);
4198            }
4199
4200            final PermissionsState permissionsState = sb.getPermissionsState();
4201
4202            final int flags = permissionsState.getPermissionFlags(name, userId);
4203            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4204                throw new SecurityException("Cannot grant system fixed permission "
4205                        + name + " for package " + packageName);
4206            }
4207
4208            if (bp.isDevelopment()) {
4209                // Development permissions must be handled specially, since they are not
4210                // normal runtime permissions.  For now they apply to all users.
4211                if (permissionsState.grantInstallPermission(bp) !=
4212                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4213                    scheduleWriteSettingsLocked();
4214                }
4215                return;
4216            }
4217
4218            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4219                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4220                return;
4221            }
4222
4223            final int result = permissionsState.grantRuntimePermission(bp, userId);
4224            switch (result) {
4225                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4226                    return;
4227                }
4228
4229                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4230                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4231                    mHandler.post(new Runnable() {
4232                        @Override
4233                        public void run() {
4234                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4235                        }
4236                    });
4237                }
4238                break;
4239            }
4240
4241            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4242
4243            // Not critical if that is lost - app has to request again.
4244            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4245        }
4246
4247        // Only need to do this if user is initialized. Otherwise it's a new user
4248        // and there are no processes running as the user yet and there's no need
4249        // to make an expensive call to remount processes for the changed permissions.
4250        if (READ_EXTERNAL_STORAGE.equals(name)
4251                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4252            final long token = Binder.clearCallingIdentity();
4253            try {
4254                if (sUserManager.isInitialized(userId)) {
4255                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4256                            MountServiceInternal.class);
4257                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4258                }
4259            } finally {
4260                Binder.restoreCallingIdentity(token);
4261            }
4262        }
4263    }
4264
4265    @Override
4266    public void revokeRuntimePermission(String packageName, String name, int userId) {
4267        if (!sUserManager.exists(userId)) {
4268            Log.e(TAG, "No such user:" + userId);
4269            return;
4270        }
4271
4272        mContext.enforceCallingOrSelfPermission(
4273                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4274                "revokeRuntimePermission");
4275
4276        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4277                true /* requireFullPermission */, true /* checkShell */,
4278                "revokeRuntimePermission");
4279
4280        final int appId;
4281
4282        synchronized (mPackages) {
4283            final PackageParser.Package pkg = mPackages.get(packageName);
4284            if (pkg == null) {
4285                throw new IllegalArgumentException("Unknown package: " + packageName);
4286            }
4287
4288            final BasePermission bp = mSettings.mPermissions.get(name);
4289            if (bp == null) {
4290                throw new IllegalArgumentException("Unknown permission: " + name);
4291            }
4292
4293            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4294
4295            // If a permission review is required for legacy apps we represent
4296            // their permissions as always granted runtime ones since we need
4297            // to keep the review required permission flag per user while an
4298            // install permission's state is shared across all users.
4299            if (Build.PERMISSIONS_REVIEW_REQUIRED
4300                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4301                    && bp.isRuntime()) {
4302                return;
4303            }
4304
4305            SettingBase sb = (SettingBase) pkg.mExtras;
4306            if (sb == null) {
4307                throw new IllegalArgumentException("Unknown package: " + packageName);
4308            }
4309
4310            final PermissionsState permissionsState = sb.getPermissionsState();
4311
4312            final int flags = permissionsState.getPermissionFlags(name, userId);
4313            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4314                throw new SecurityException("Cannot revoke system fixed permission "
4315                        + name + " for package " + packageName);
4316            }
4317
4318            if (bp.isDevelopment()) {
4319                // Development permissions must be handled specially, since they are not
4320                // normal runtime permissions.  For now they apply to all users.
4321                if (permissionsState.revokeInstallPermission(bp) !=
4322                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4323                    scheduleWriteSettingsLocked();
4324                }
4325                return;
4326            }
4327
4328            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4329                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4330                return;
4331            }
4332
4333            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4334
4335            // Critical, after this call app should never have the permission.
4336            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4337
4338            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4339        }
4340
4341        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4342    }
4343
4344    @Override
4345    public void resetRuntimePermissions() {
4346        mContext.enforceCallingOrSelfPermission(
4347                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4348                "revokeRuntimePermission");
4349
4350        int callingUid = Binder.getCallingUid();
4351        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4352            mContext.enforceCallingOrSelfPermission(
4353                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4354                    "resetRuntimePermissions");
4355        }
4356
4357        synchronized (mPackages) {
4358            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4359            for (int userId : UserManagerService.getInstance().getUserIds()) {
4360                final int packageCount = mPackages.size();
4361                for (int i = 0; i < packageCount; i++) {
4362                    PackageParser.Package pkg = mPackages.valueAt(i);
4363                    if (!(pkg.mExtras instanceof PackageSetting)) {
4364                        continue;
4365                    }
4366                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4367                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4368                }
4369            }
4370        }
4371    }
4372
4373    @Override
4374    public int getPermissionFlags(String name, String packageName, int userId) {
4375        if (!sUserManager.exists(userId)) {
4376            return 0;
4377        }
4378
4379        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4380
4381        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4382                true /* requireFullPermission */, false /* checkShell */,
4383                "getPermissionFlags");
4384
4385        synchronized (mPackages) {
4386            final PackageParser.Package pkg = mPackages.get(packageName);
4387            if (pkg == null) {
4388                return 0;
4389            }
4390
4391            final BasePermission bp = mSettings.mPermissions.get(name);
4392            if (bp == null) {
4393                return 0;
4394            }
4395
4396            SettingBase sb = (SettingBase) pkg.mExtras;
4397            if (sb == null) {
4398                return 0;
4399            }
4400
4401            PermissionsState permissionsState = sb.getPermissionsState();
4402            return permissionsState.getPermissionFlags(name, userId);
4403        }
4404    }
4405
4406    @Override
4407    public void updatePermissionFlags(String name, String packageName, int flagMask,
4408            int flagValues, int userId) {
4409        if (!sUserManager.exists(userId)) {
4410            return;
4411        }
4412
4413        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4414
4415        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4416                true /* requireFullPermission */, true /* checkShell */,
4417                "updatePermissionFlags");
4418
4419        // Only the system can change these flags and nothing else.
4420        if (getCallingUid() != Process.SYSTEM_UID) {
4421            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4422            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4423            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4424            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4425            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4426        }
4427
4428        synchronized (mPackages) {
4429            final PackageParser.Package pkg = mPackages.get(packageName);
4430            if (pkg == null) {
4431                throw new IllegalArgumentException("Unknown package: " + packageName);
4432            }
4433
4434            final BasePermission bp = mSettings.mPermissions.get(name);
4435            if (bp == null) {
4436                throw new IllegalArgumentException("Unknown permission: " + name);
4437            }
4438
4439            SettingBase sb = (SettingBase) pkg.mExtras;
4440            if (sb == null) {
4441                throw new IllegalArgumentException("Unknown package: " + packageName);
4442            }
4443
4444            PermissionsState permissionsState = sb.getPermissionsState();
4445
4446            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4447
4448            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4449                // Install and runtime permissions are stored in different places,
4450                // so figure out what permission changed and persist the change.
4451                if (permissionsState.getInstallPermissionState(name) != null) {
4452                    scheduleWriteSettingsLocked();
4453                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4454                        || hadState) {
4455                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4456                }
4457            }
4458        }
4459    }
4460
4461    /**
4462     * Update the permission flags for all packages and runtime permissions of a user in order
4463     * to allow device or profile owner to remove POLICY_FIXED.
4464     */
4465    @Override
4466    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4467        if (!sUserManager.exists(userId)) {
4468            return;
4469        }
4470
4471        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4472
4473        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4474                true /* requireFullPermission */, true /* checkShell */,
4475                "updatePermissionFlagsForAllApps");
4476
4477        // Only the system can change system fixed flags.
4478        if (getCallingUid() != Process.SYSTEM_UID) {
4479            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4480            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4481        }
4482
4483        synchronized (mPackages) {
4484            boolean changed = false;
4485            final int packageCount = mPackages.size();
4486            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4487                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4488                SettingBase sb = (SettingBase) pkg.mExtras;
4489                if (sb == null) {
4490                    continue;
4491                }
4492                PermissionsState permissionsState = sb.getPermissionsState();
4493                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4494                        userId, flagMask, flagValues);
4495            }
4496            if (changed) {
4497                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4498            }
4499        }
4500    }
4501
4502    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4503        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4504                != PackageManager.PERMISSION_GRANTED
4505            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4506                != PackageManager.PERMISSION_GRANTED) {
4507            throw new SecurityException(message + " requires "
4508                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4509                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4510        }
4511    }
4512
4513    @Override
4514    public boolean shouldShowRequestPermissionRationale(String permissionName,
4515            String packageName, int userId) {
4516        if (UserHandle.getCallingUserId() != userId) {
4517            mContext.enforceCallingPermission(
4518                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4519                    "canShowRequestPermissionRationale for user " + userId);
4520        }
4521
4522        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4523        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4524            return false;
4525        }
4526
4527        if (checkPermission(permissionName, packageName, userId)
4528                == PackageManager.PERMISSION_GRANTED) {
4529            return false;
4530        }
4531
4532        final int flags;
4533
4534        final long identity = Binder.clearCallingIdentity();
4535        try {
4536            flags = getPermissionFlags(permissionName,
4537                    packageName, userId);
4538        } finally {
4539            Binder.restoreCallingIdentity(identity);
4540        }
4541
4542        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4543                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4544                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4545
4546        if ((flags & fixedFlags) != 0) {
4547            return false;
4548        }
4549
4550        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4551    }
4552
4553    @Override
4554    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4555        mContext.enforceCallingOrSelfPermission(
4556                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4557                "addOnPermissionsChangeListener");
4558
4559        synchronized (mPackages) {
4560            mOnPermissionChangeListeners.addListenerLocked(listener);
4561        }
4562    }
4563
4564    @Override
4565    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4566        synchronized (mPackages) {
4567            mOnPermissionChangeListeners.removeListenerLocked(listener);
4568        }
4569    }
4570
4571    @Override
4572    public boolean isProtectedBroadcast(String actionName) {
4573        synchronized (mPackages) {
4574            if (mProtectedBroadcasts.contains(actionName)) {
4575                return true;
4576            } else if (actionName != null) {
4577                // TODO: remove these terrible hacks
4578                if (actionName.startsWith("android.net.netmon.lingerExpired")
4579                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4580                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4581                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4582                    return true;
4583                }
4584            }
4585        }
4586        return false;
4587    }
4588
4589    @Override
4590    public int checkSignatures(String pkg1, String pkg2) {
4591        synchronized (mPackages) {
4592            final PackageParser.Package p1 = mPackages.get(pkg1);
4593            final PackageParser.Package p2 = mPackages.get(pkg2);
4594            if (p1 == null || p1.mExtras == null
4595                    || p2 == null || p2.mExtras == null) {
4596                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4597            }
4598            return compareSignatures(p1.mSignatures, p2.mSignatures);
4599        }
4600    }
4601
4602    @Override
4603    public int checkUidSignatures(int uid1, int uid2) {
4604        // Map to base uids.
4605        uid1 = UserHandle.getAppId(uid1);
4606        uid2 = UserHandle.getAppId(uid2);
4607        // reader
4608        synchronized (mPackages) {
4609            Signature[] s1;
4610            Signature[] s2;
4611            Object obj = mSettings.getUserIdLPr(uid1);
4612            if (obj != null) {
4613                if (obj instanceof SharedUserSetting) {
4614                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4615                } else if (obj instanceof PackageSetting) {
4616                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4617                } else {
4618                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4619                }
4620            } else {
4621                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4622            }
4623            obj = mSettings.getUserIdLPr(uid2);
4624            if (obj != null) {
4625                if (obj instanceof SharedUserSetting) {
4626                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4627                } else if (obj instanceof PackageSetting) {
4628                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4629                } else {
4630                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4631                }
4632            } else {
4633                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4634            }
4635            return compareSignatures(s1, s2);
4636        }
4637    }
4638
4639    /**
4640     * This method should typically only be used when granting or revoking
4641     * permissions, since the app may immediately restart after this call.
4642     * <p>
4643     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4644     * guard your work against the app being relaunched.
4645     */
4646    private void killUid(int appId, int userId, String reason) {
4647        final long identity = Binder.clearCallingIdentity();
4648        try {
4649            IActivityManager am = ActivityManagerNative.getDefault();
4650            if (am != null) {
4651                try {
4652                    am.killUid(appId, userId, reason);
4653                } catch (RemoteException e) {
4654                    /* ignore - same process */
4655                }
4656            }
4657        } finally {
4658            Binder.restoreCallingIdentity(identity);
4659        }
4660    }
4661
4662    /**
4663     * Compares two sets of signatures. Returns:
4664     * <br />
4665     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4666     * <br />
4667     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4668     * <br />
4669     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4670     * <br />
4671     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4672     * <br />
4673     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4674     */
4675    static int compareSignatures(Signature[] s1, Signature[] s2) {
4676        if (s1 == null) {
4677            return s2 == null
4678                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4679                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4680        }
4681
4682        if (s2 == null) {
4683            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4684        }
4685
4686        if (s1.length != s2.length) {
4687            return PackageManager.SIGNATURE_NO_MATCH;
4688        }
4689
4690        // Since both signature sets are of size 1, we can compare without HashSets.
4691        if (s1.length == 1) {
4692            return s1[0].equals(s2[0]) ?
4693                    PackageManager.SIGNATURE_MATCH :
4694                    PackageManager.SIGNATURE_NO_MATCH;
4695        }
4696
4697        ArraySet<Signature> set1 = new ArraySet<Signature>();
4698        for (Signature sig : s1) {
4699            set1.add(sig);
4700        }
4701        ArraySet<Signature> set2 = new ArraySet<Signature>();
4702        for (Signature sig : s2) {
4703            set2.add(sig);
4704        }
4705        // Make sure s2 contains all signatures in s1.
4706        if (set1.equals(set2)) {
4707            return PackageManager.SIGNATURE_MATCH;
4708        }
4709        return PackageManager.SIGNATURE_NO_MATCH;
4710    }
4711
4712    /**
4713     * If the database version for this type of package (internal storage or
4714     * external storage) is less than the version where package signatures
4715     * were updated, return true.
4716     */
4717    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4718        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4719        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4720    }
4721
4722    /**
4723     * Used for backward compatibility to make sure any packages with
4724     * certificate chains get upgraded to the new style. {@code existingSigs}
4725     * will be in the old format (since they were stored on disk from before the
4726     * system upgrade) and {@code scannedSigs} will be in the newer format.
4727     */
4728    private int compareSignaturesCompat(PackageSignatures existingSigs,
4729            PackageParser.Package scannedPkg) {
4730        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4731            return PackageManager.SIGNATURE_NO_MATCH;
4732        }
4733
4734        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4735        for (Signature sig : existingSigs.mSignatures) {
4736            existingSet.add(sig);
4737        }
4738        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4739        for (Signature sig : scannedPkg.mSignatures) {
4740            try {
4741                Signature[] chainSignatures = sig.getChainSignatures();
4742                for (Signature chainSig : chainSignatures) {
4743                    scannedCompatSet.add(chainSig);
4744                }
4745            } catch (CertificateEncodingException e) {
4746                scannedCompatSet.add(sig);
4747            }
4748        }
4749        /*
4750         * Make sure the expanded scanned set contains all signatures in the
4751         * existing one.
4752         */
4753        if (scannedCompatSet.equals(existingSet)) {
4754            // Migrate the old signatures to the new scheme.
4755            existingSigs.assignSignatures(scannedPkg.mSignatures);
4756            // The new KeySets will be re-added later in the scanning process.
4757            synchronized (mPackages) {
4758                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4759            }
4760            return PackageManager.SIGNATURE_MATCH;
4761        }
4762        return PackageManager.SIGNATURE_NO_MATCH;
4763    }
4764
4765    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4766        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4767        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4768    }
4769
4770    private int compareSignaturesRecover(PackageSignatures existingSigs,
4771            PackageParser.Package scannedPkg) {
4772        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4773            return PackageManager.SIGNATURE_NO_MATCH;
4774        }
4775
4776        String msg = null;
4777        try {
4778            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4779                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4780                        + scannedPkg.packageName);
4781                return PackageManager.SIGNATURE_MATCH;
4782            }
4783        } catch (CertificateException e) {
4784            msg = e.getMessage();
4785        }
4786
4787        logCriticalInfo(Log.INFO,
4788                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4789        return PackageManager.SIGNATURE_NO_MATCH;
4790    }
4791
4792    @Override
4793    public List<String> getAllPackages() {
4794        synchronized (mPackages) {
4795            return new ArrayList<String>(mPackages.keySet());
4796        }
4797    }
4798
4799    @Override
4800    public String[] getPackagesForUid(int uid) {
4801        uid = UserHandle.getAppId(uid);
4802        // reader
4803        synchronized (mPackages) {
4804            Object obj = mSettings.getUserIdLPr(uid);
4805            if (obj instanceof SharedUserSetting) {
4806                final SharedUserSetting sus = (SharedUserSetting) obj;
4807                final int N = sus.packages.size();
4808                final String[] res = new String[N];
4809                for (int i = 0; i < N; i++) {
4810                    res[i] = sus.packages.valueAt(i).name;
4811                }
4812                return res;
4813            } else if (obj instanceof PackageSetting) {
4814                final PackageSetting ps = (PackageSetting) obj;
4815                return new String[] { ps.name };
4816            }
4817        }
4818        return null;
4819    }
4820
4821    @Override
4822    public String getNameForUid(int uid) {
4823        // reader
4824        synchronized (mPackages) {
4825            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4826            if (obj instanceof SharedUserSetting) {
4827                final SharedUserSetting sus = (SharedUserSetting) obj;
4828                return sus.name + ":" + sus.userId;
4829            } else if (obj instanceof PackageSetting) {
4830                final PackageSetting ps = (PackageSetting) obj;
4831                return ps.name;
4832            }
4833        }
4834        return null;
4835    }
4836
4837    @Override
4838    public int getUidForSharedUser(String sharedUserName) {
4839        if(sharedUserName == null) {
4840            return -1;
4841        }
4842        // reader
4843        synchronized (mPackages) {
4844            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4845            if (suid == null) {
4846                return -1;
4847            }
4848            return suid.userId;
4849        }
4850    }
4851
4852    @Override
4853    public int getFlagsForUid(int uid) {
4854        synchronized (mPackages) {
4855            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4856            if (obj instanceof SharedUserSetting) {
4857                final SharedUserSetting sus = (SharedUserSetting) obj;
4858                return sus.pkgFlags;
4859            } else if (obj instanceof PackageSetting) {
4860                final PackageSetting ps = (PackageSetting) obj;
4861                return ps.pkgFlags;
4862            }
4863        }
4864        return 0;
4865    }
4866
4867    @Override
4868    public int getPrivateFlagsForUid(int uid) {
4869        synchronized (mPackages) {
4870            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4871            if (obj instanceof SharedUserSetting) {
4872                final SharedUserSetting sus = (SharedUserSetting) obj;
4873                return sus.pkgPrivateFlags;
4874            } else if (obj instanceof PackageSetting) {
4875                final PackageSetting ps = (PackageSetting) obj;
4876                return ps.pkgPrivateFlags;
4877            }
4878        }
4879        return 0;
4880    }
4881
4882    @Override
4883    public boolean isUidPrivileged(int uid) {
4884        uid = UserHandle.getAppId(uid);
4885        // reader
4886        synchronized (mPackages) {
4887            Object obj = mSettings.getUserIdLPr(uid);
4888            if (obj instanceof SharedUserSetting) {
4889                final SharedUserSetting sus = (SharedUserSetting) obj;
4890                final Iterator<PackageSetting> it = sus.packages.iterator();
4891                while (it.hasNext()) {
4892                    if (it.next().isPrivileged()) {
4893                        return true;
4894                    }
4895                }
4896            } else if (obj instanceof PackageSetting) {
4897                final PackageSetting ps = (PackageSetting) obj;
4898                return ps.isPrivileged();
4899            }
4900        }
4901        return false;
4902    }
4903
4904    @Override
4905    public String[] getAppOpPermissionPackages(String permissionName) {
4906        synchronized (mPackages) {
4907            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4908            if (pkgs == null) {
4909                return null;
4910            }
4911            return pkgs.toArray(new String[pkgs.size()]);
4912        }
4913    }
4914
4915    @Override
4916    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4917            int flags, int userId) {
4918        try {
4919            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4920
4921            if (!sUserManager.exists(userId)) return null;
4922            flags = updateFlagsForResolve(flags, userId, intent);
4923            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4924                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4925
4926            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4927            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4928                    flags, userId);
4929            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4930
4931            final ResolveInfo bestChoice =
4932                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4933
4934            if (isEphemeralAllowed(intent, query, userId)) {
4935                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4936                final EphemeralResolveInfo ai =
4937                        getEphemeralResolveInfo(intent, resolvedType, userId);
4938                if (ai != null) {
4939                    if (DEBUG_EPHEMERAL) {
4940                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4941                    }
4942                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4943                    bestChoice.ephemeralResolveInfo = ai;
4944                }
4945                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4946            }
4947            return bestChoice;
4948        } finally {
4949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4950        }
4951    }
4952
4953    @Override
4954    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4955            IntentFilter filter, int match, ComponentName activity) {
4956        final int userId = UserHandle.getCallingUserId();
4957        if (DEBUG_PREFERRED) {
4958            Log.v(TAG, "setLastChosenActivity intent=" + intent
4959                + " resolvedType=" + resolvedType
4960                + " flags=" + flags
4961                + " filter=" + filter
4962                + " match=" + match
4963                + " activity=" + activity);
4964            filter.dump(new PrintStreamPrinter(System.out), "    ");
4965        }
4966        intent.setComponent(null);
4967        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4968                userId);
4969        // Find any earlier preferred or last chosen entries and nuke them
4970        findPreferredActivity(intent, resolvedType,
4971                flags, query, 0, false, true, false, userId);
4972        // Add the new activity as the last chosen for this filter
4973        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4974                "Setting last chosen");
4975    }
4976
4977    @Override
4978    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4979        final int userId = UserHandle.getCallingUserId();
4980        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4981        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4982                userId);
4983        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4984                false, false, false, userId);
4985    }
4986
4987
4988    private boolean isEphemeralAllowed(
4989            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4990        // Short circuit and return early if possible.
4991        if (DISABLE_EPHEMERAL_APPS) {
4992            return false;
4993        }
4994        final int callingUser = UserHandle.getCallingUserId();
4995        if (callingUser != UserHandle.USER_SYSTEM) {
4996            return false;
4997        }
4998        if (mEphemeralResolverConnection == null) {
4999            return false;
5000        }
5001        if (intent.getComponent() != null) {
5002            return false;
5003        }
5004        if (intent.getPackage() != null) {
5005            return false;
5006        }
5007        final boolean isWebUri = hasWebURI(intent);
5008        if (!isWebUri) {
5009            return false;
5010        }
5011        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5012        synchronized (mPackages) {
5013            final int count = resolvedActivites.size();
5014            for (int n = 0; n < count; n++) {
5015                ResolveInfo info = resolvedActivites.get(n);
5016                String packageName = info.activityInfo.packageName;
5017                PackageSetting ps = mSettings.mPackages.get(packageName);
5018                if (ps != null) {
5019                    // Try to get the status from User settings first
5020                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5021                    int status = (int) (packedStatus >> 32);
5022                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5023                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5024                        if (DEBUG_EPHEMERAL) {
5025                            Slog.v(TAG, "DENY ephemeral apps;"
5026                                + " pkg: " + packageName + ", status: " + status);
5027                        }
5028                        return false;
5029                    }
5030                }
5031            }
5032        }
5033        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5034        return true;
5035    }
5036
5037    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
5038            int userId) {
5039        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
5040                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
5041        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
5042                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
5043        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
5044                ephemeralPrefixCount);
5045        final int[] shaPrefix = digest.getDigestPrefix();
5046        final byte[][] digestBytes = digest.getDigestBytes();
5047        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5048                mEphemeralResolverConnection.getEphemeralResolveInfoList(
5049                        shaPrefix, ephemeralPrefixMask);
5050        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5051            // No hash prefix match; there are no ephemeral apps for this domain.
5052            return null;
5053        }
5054
5055        // Go in reverse order so we match the narrowest scope first.
5056        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
5057            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
5058                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
5059                    continue;
5060                }
5061                final List<IntentFilter> filters = ephemeralApplication.getFilters();
5062                // No filters; this should never happen.
5063                if (filters.isEmpty()) {
5064                    continue;
5065                }
5066                // We have a domain match; resolve the filters to see if anything matches.
5067                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5068                for (int j = filters.size() - 1; j >= 0; --j) {
5069                    final EphemeralResolveIntentInfo intentInfo =
5070                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5071                    ephemeralResolver.addFilter(intentInfo);
5072                }
5073                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5074                        intent, resolvedType, false /*defaultOnly*/, userId);
5075                if (!matchedResolveInfoList.isEmpty()) {
5076                    return matchedResolveInfoList.get(0);
5077                }
5078            }
5079        }
5080        // Hash or filter mis-match; no ephemeral apps for this domain.
5081        return null;
5082    }
5083
5084    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5085            int flags, List<ResolveInfo> query, int userId) {
5086        if (query != null) {
5087            final int N = query.size();
5088            if (N == 1) {
5089                return query.get(0);
5090            } else if (N > 1) {
5091                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5092                // If there is more than one activity with the same priority,
5093                // then let the user decide between them.
5094                ResolveInfo r0 = query.get(0);
5095                ResolveInfo r1 = query.get(1);
5096                if (DEBUG_INTENT_MATCHING || debug) {
5097                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5098                            + r1.activityInfo.name + "=" + r1.priority);
5099                }
5100                // If the first activity has a higher priority, or a different
5101                // default, then it is always desirable to pick it.
5102                if (r0.priority != r1.priority
5103                        || r0.preferredOrder != r1.preferredOrder
5104                        || r0.isDefault != r1.isDefault) {
5105                    return query.get(0);
5106                }
5107                // If we have saved a preference for a preferred activity for
5108                // this Intent, use that.
5109                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5110                        flags, query, r0.priority, true, false, debug, userId);
5111                if (ri != null) {
5112                    return ri;
5113                }
5114                ri = new ResolveInfo(mResolveInfo);
5115                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5116                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5117                // If all of the options come from the same package, show the application's
5118                // label and icon instead of the generic resolver's.
5119                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5120                // and then throw away the ResolveInfo itself, meaning that the caller loses
5121                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5122                // a fallback for this case; we only set the target package's resources on
5123                // the ResolveInfo, not the ActivityInfo.
5124                final String intentPackage = intent.getPackage();
5125                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5126                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5127                    ri.resolvePackageName = intentPackage;
5128                    if (userNeedsBadging(userId)) {
5129                        ri.noResourceId = true;
5130                    } else {
5131                        ri.icon = appi.icon;
5132                    }
5133                    ri.iconResourceId = appi.icon;
5134                    ri.labelRes = appi.labelRes;
5135                }
5136                ri.activityInfo.applicationInfo = new ApplicationInfo(
5137                        ri.activityInfo.applicationInfo);
5138                if (userId != 0) {
5139                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5140                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5141                }
5142                // Make sure that the resolver is displayable in car mode
5143                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5144                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5145                return ri;
5146            }
5147        }
5148        return null;
5149    }
5150
5151    /**
5152     * Return true if the given list is not empty and all of its contents have
5153     * an activityInfo with the given package name.
5154     */
5155    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5156        if (ArrayUtils.isEmpty(list)) {
5157            return false;
5158        }
5159        for (int i = 0, N = list.size(); i < N; i++) {
5160            final ResolveInfo ri = list.get(i);
5161            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5162            if (ai == null || !packageName.equals(ai.packageName)) {
5163                return false;
5164            }
5165        }
5166        return true;
5167    }
5168
5169    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5170            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5171        final int N = query.size();
5172        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5173                .get(userId);
5174        // Get the list of persistent preferred activities that handle the intent
5175        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5176        List<PersistentPreferredActivity> pprefs = ppir != null
5177                ? ppir.queryIntent(intent, resolvedType,
5178                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5179                : null;
5180        if (pprefs != null && pprefs.size() > 0) {
5181            final int M = pprefs.size();
5182            for (int i=0; i<M; i++) {
5183                final PersistentPreferredActivity ppa = pprefs.get(i);
5184                if (DEBUG_PREFERRED || debug) {
5185                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5186                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5187                            + "\n  component=" + ppa.mComponent);
5188                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5189                }
5190                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5191                        flags | MATCH_DISABLED_COMPONENTS, userId);
5192                if (DEBUG_PREFERRED || debug) {
5193                    Slog.v(TAG, "Found persistent preferred activity:");
5194                    if (ai != null) {
5195                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5196                    } else {
5197                        Slog.v(TAG, "  null");
5198                    }
5199                }
5200                if (ai == null) {
5201                    // This previously registered persistent preferred activity
5202                    // component is no longer known. Ignore it and do NOT remove it.
5203                    continue;
5204                }
5205                for (int j=0; j<N; j++) {
5206                    final ResolveInfo ri = query.get(j);
5207                    if (!ri.activityInfo.applicationInfo.packageName
5208                            .equals(ai.applicationInfo.packageName)) {
5209                        continue;
5210                    }
5211                    if (!ri.activityInfo.name.equals(ai.name)) {
5212                        continue;
5213                    }
5214                    //  Found a persistent preference that can handle the intent.
5215                    if (DEBUG_PREFERRED || debug) {
5216                        Slog.v(TAG, "Returning persistent preferred activity: " +
5217                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5218                    }
5219                    return ri;
5220                }
5221            }
5222        }
5223        return null;
5224    }
5225
5226    // TODO: handle preferred activities missing while user has amnesia
5227    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5228            List<ResolveInfo> query, int priority, boolean always,
5229            boolean removeMatches, boolean debug, int userId) {
5230        if (!sUserManager.exists(userId)) return null;
5231        flags = updateFlagsForResolve(flags, userId, intent);
5232        // writer
5233        synchronized (mPackages) {
5234            if (intent.getSelector() != null) {
5235                intent = intent.getSelector();
5236            }
5237            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5238
5239            // Try to find a matching persistent preferred activity.
5240            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5241                    debug, userId);
5242
5243            // If a persistent preferred activity matched, use it.
5244            if (pri != null) {
5245                return pri;
5246            }
5247
5248            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5249            // Get the list of preferred activities that handle the intent
5250            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5251            List<PreferredActivity> prefs = pir != null
5252                    ? pir.queryIntent(intent, resolvedType,
5253                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5254                    : null;
5255            if (prefs != null && prefs.size() > 0) {
5256                boolean changed = false;
5257                try {
5258                    // First figure out how good the original match set is.
5259                    // We will only allow preferred activities that came
5260                    // from the same match quality.
5261                    int match = 0;
5262
5263                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5264
5265                    final int N = query.size();
5266                    for (int j=0; j<N; j++) {
5267                        final ResolveInfo ri = query.get(j);
5268                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5269                                + ": 0x" + Integer.toHexString(match));
5270                        if (ri.match > match) {
5271                            match = ri.match;
5272                        }
5273                    }
5274
5275                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5276                            + Integer.toHexString(match));
5277
5278                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5279                    final int M = prefs.size();
5280                    for (int i=0; i<M; i++) {
5281                        final PreferredActivity pa = prefs.get(i);
5282                        if (DEBUG_PREFERRED || debug) {
5283                            Slog.v(TAG, "Checking PreferredActivity ds="
5284                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5285                                    + "\n  component=" + pa.mPref.mComponent);
5286                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5287                        }
5288                        if (pa.mPref.mMatch != match) {
5289                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5290                                    + Integer.toHexString(pa.mPref.mMatch));
5291                            continue;
5292                        }
5293                        // If it's not an "always" type preferred activity and that's what we're
5294                        // looking for, skip it.
5295                        if (always && !pa.mPref.mAlways) {
5296                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5297                            continue;
5298                        }
5299                        final ActivityInfo ai = getActivityInfo(
5300                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5301                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5302                                userId);
5303                        if (DEBUG_PREFERRED || debug) {
5304                            Slog.v(TAG, "Found preferred activity:");
5305                            if (ai != null) {
5306                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5307                            } else {
5308                                Slog.v(TAG, "  null");
5309                            }
5310                        }
5311                        if (ai == null) {
5312                            // This previously registered preferred activity
5313                            // component is no longer known.  Most likely an update
5314                            // to the app was installed and in the new version this
5315                            // component no longer exists.  Clean it up by removing
5316                            // it from the preferred activities list, and skip it.
5317                            Slog.w(TAG, "Removing dangling preferred activity: "
5318                                    + pa.mPref.mComponent);
5319                            pir.removeFilter(pa);
5320                            changed = true;
5321                            continue;
5322                        }
5323                        for (int j=0; j<N; j++) {
5324                            final ResolveInfo ri = query.get(j);
5325                            if (!ri.activityInfo.applicationInfo.packageName
5326                                    .equals(ai.applicationInfo.packageName)) {
5327                                continue;
5328                            }
5329                            if (!ri.activityInfo.name.equals(ai.name)) {
5330                                continue;
5331                            }
5332
5333                            if (removeMatches) {
5334                                pir.removeFilter(pa);
5335                                changed = true;
5336                                if (DEBUG_PREFERRED) {
5337                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5338                                }
5339                                break;
5340                            }
5341
5342                            // Okay we found a previously set preferred or last chosen app.
5343                            // If the result set is different from when this
5344                            // was created, we need to clear it and re-ask the
5345                            // user their preference, if we're looking for an "always" type entry.
5346                            if (always && !pa.mPref.sameSet(query)) {
5347                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5348                                        + intent + " type " + resolvedType);
5349                                if (DEBUG_PREFERRED) {
5350                                    Slog.v(TAG, "Removing preferred activity since set changed "
5351                                            + pa.mPref.mComponent);
5352                                }
5353                                pir.removeFilter(pa);
5354                                // Re-add the filter as a "last chosen" entry (!always)
5355                                PreferredActivity lastChosen = new PreferredActivity(
5356                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5357                                pir.addFilter(lastChosen);
5358                                changed = true;
5359                                return null;
5360                            }
5361
5362                            // Yay! Either the set matched or we're looking for the last chosen
5363                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5364                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5365                            return ri;
5366                        }
5367                    }
5368                } finally {
5369                    if (changed) {
5370                        if (DEBUG_PREFERRED) {
5371                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5372                        }
5373                        scheduleWritePackageRestrictionsLocked(userId);
5374                    }
5375                }
5376            }
5377        }
5378        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5379        return null;
5380    }
5381
5382    /*
5383     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5384     */
5385    @Override
5386    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5387            int targetUserId) {
5388        mContext.enforceCallingOrSelfPermission(
5389                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5390        List<CrossProfileIntentFilter> matches =
5391                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5392        if (matches != null) {
5393            int size = matches.size();
5394            for (int i = 0; i < size; i++) {
5395                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5396            }
5397        }
5398        if (hasWebURI(intent)) {
5399            // cross-profile app linking works only towards the parent.
5400            final UserInfo parent = getProfileParent(sourceUserId);
5401            synchronized(mPackages) {
5402                int flags = updateFlagsForResolve(0, parent.id, intent);
5403                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5404                        intent, resolvedType, flags, sourceUserId, parent.id);
5405                return xpDomainInfo != null;
5406            }
5407        }
5408        return false;
5409    }
5410
5411    private UserInfo getProfileParent(int userId) {
5412        final long identity = Binder.clearCallingIdentity();
5413        try {
5414            return sUserManager.getProfileParent(userId);
5415        } finally {
5416            Binder.restoreCallingIdentity(identity);
5417        }
5418    }
5419
5420    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5421            String resolvedType, int userId) {
5422        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5423        if (resolver != null) {
5424            return resolver.queryIntent(intent, resolvedType, false, userId);
5425        }
5426        return null;
5427    }
5428
5429    @Override
5430    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5431            String resolvedType, int flags, int userId) {
5432        try {
5433            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5434
5435            return new ParceledListSlice<>(
5436                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5437        } finally {
5438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5439        }
5440    }
5441
5442    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5443            String resolvedType, int flags, int userId) {
5444        if (!sUserManager.exists(userId)) return Collections.emptyList();
5445        flags = updateFlagsForResolve(flags, userId, intent);
5446        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5447                false /* requireFullPermission */, false /* checkShell */,
5448                "query intent activities");
5449        ComponentName comp = intent.getComponent();
5450        if (comp == null) {
5451            if (intent.getSelector() != null) {
5452                intent = intent.getSelector();
5453                comp = intent.getComponent();
5454            }
5455        }
5456
5457        if (comp != null) {
5458            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5459            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5460            if (ai != null) {
5461                final ResolveInfo ri = new ResolveInfo();
5462                ri.activityInfo = ai;
5463                list.add(ri);
5464            }
5465            return list;
5466        }
5467
5468        // reader
5469        synchronized (mPackages) {
5470            final String pkgName = intent.getPackage();
5471            if (pkgName == null) {
5472                List<CrossProfileIntentFilter> matchingFilters =
5473                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5474                // Check for results that need to skip the current profile.
5475                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5476                        resolvedType, flags, userId);
5477                if (xpResolveInfo != null) {
5478                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5479                    result.add(xpResolveInfo);
5480                    return filterIfNotSystemUser(result, userId);
5481                }
5482
5483                // Check for results in the current profile.
5484                List<ResolveInfo> result = mActivities.queryIntent(
5485                        intent, resolvedType, flags, userId);
5486                result = filterIfNotSystemUser(result, userId);
5487
5488                // Check for cross profile results.
5489                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5490                xpResolveInfo = queryCrossProfileIntents(
5491                        matchingFilters, intent, resolvedType, flags, userId,
5492                        hasNonNegativePriorityResult);
5493                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5494                    boolean isVisibleToUser = filterIfNotSystemUser(
5495                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5496                    if (isVisibleToUser) {
5497                        result.add(xpResolveInfo);
5498                        Collections.sort(result, mResolvePrioritySorter);
5499                    }
5500                }
5501                if (hasWebURI(intent)) {
5502                    CrossProfileDomainInfo xpDomainInfo = null;
5503                    final UserInfo parent = getProfileParent(userId);
5504                    if (parent != null) {
5505                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5506                                flags, userId, parent.id);
5507                    }
5508                    if (xpDomainInfo != null) {
5509                        if (xpResolveInfo != null) {
5510                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5511                            // in the result.
5512                            result.remove(xpResolveInfo);
5513                        }
5514                        if (result.size() == 0) {
5515                            result.add(xpDomainInfo.resolveInfo);
5516                            return result;
5517                        }
5518                    } else if (result.size() <= 1) {
5519                        return result;
5520                    }
5521                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5522                            xpDomainInfo, userId);
5523                    Collections.sort(result, mResolvePrioritySorter);
5524                }
5525                return result;
5526            }
5527            final PackageParser.Package pkg = mPackages.get(pkgName);
5528            if (pkg != null) {
5529                return filterIfNotSystemUser(
5530                        mActivities.queryIntentForPackage(
5531                                intent, resolvedType, flags, pkg.activities, userId),
5532                        userId);
5533            }
5534            return new ArrayList<ResolveInfo>();
5535        }
5536    }
5537
5538    private static class CrossProfileDomainInfo {
5539        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5540        ResolveInfo resolveInfo;
5541        /* Best domain verification status of the activities found in the other profile */
5542        int bestDomainVerificationStatus;
5543    }
5544
5545    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5546            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5547        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5548                sourceUserId)) {
5549            return null;
5550        }
5551        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5552                resolvedType, flags, parentUserId);
5553
5554        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5555            return null;
5556        }
5557        CrossProfileDomainInfo result = null;
5558        int size = resultTargetUser.size();
5559        for (int i = 0; i < size; i++) {
5560            ResolveInfo riTargetUser = resultTargetUser.get(i);
5561            // Intent filter verification is only for filters that specify a host. So don't return
5562            // those that handle all web uris.
5563            if (riTargetUser.handleAllWebDataURI) {
5564                continue;
5565            }
5566            String packageName = riTargetUser.activityInfo.packageName;
5567            PackageSetting ps = mSettings.mPackages.get(packageName);
5568            if (ps == null) {
5569                continue;
5570            }
5571            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5572            int status = (int)(verificationState >> 32);
5573            if (result == null) {
5574                result = new CrossProfileDomainInfo();
5575                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5576                        sourceUserId, parentUserId);
5577                result.bestDomainVerificationStatus = status;
5578            } else {
5579                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5580                        result.bestDomainVerificationStatus);
5581            }
5582        }
5583        // Don't consider matches with status NEVER across profiles.
5584        if (result != null && result.bestDomainVerificationStatus
5585                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5586            return null;
5587        }
5588        return result;
5589    }
5590
5591    /**
5592     * Verification statuses are ordered from the worse to the best, except for
5593     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5594     */
5595    private int bestDomainVerificationStatus(int status1, int status2) {
5596        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5597            return status2;
5598        }
5599        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5600            return status1;
5601        }
5602        return (int) MathUtils.max(status1, status2);
5603    }
5604
5605    private boolean isUserEnabled(int userId) {
5606        long callingId = Binder.clearCallingIdentity();
5607        try {
5608            UserInfo userInfo = sUserManager.getUserInfo(userId);
5609            return userInfo != null && userInfo.isEnabled();
5610        } finally {
5611            Binder.restoreCallingIdentity(callingId);
5612        }
5613    }
5614
5615    /**
5616     * Filter out activities with systemUserOnly flag set, when current user is not System.
5617     *
5618     * @return filtered list
5619     */
5620    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5621        if (userId == UserHandle.USER_SYSTEM) {
5622            return resolveInfos;
5623        }
5624        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5625            ResolveInfo info = resolveInfos.get(i);
5626            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5627                resolveInfos.remove(i);
5628            }
5629        }
5630        return resolveInfos;
5631    }
5632
5633    /**
5634     * @param resolveInfos list of resolve infos in descending priority order
5635     * @return if the list contains a resolve info with non-negative priority
5636     */
5637    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5638        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5639    }
5640
5641    private static boolean hasWebURI(Intent intent) {
5642        if (intent.getData() == null) {
5643            return false;
5644        }
5645        final String scheme = intent.getScheme();
5646        if (TextUtils.isEmpty(scheme)) {
5647            return false;
5648        }
5649        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5650    }
5651
5652    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5653            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5654            int userId) {
5655        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5656
5657        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5658            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5659                    candidates.size());
5660        }
5661
5662        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5663        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5664        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5665        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5666        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5667        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5668
5669        synchronized (mPackages) {
5670            final int count = candidates.size();
5671            // First, try to use linked apps. Partition the candidates into four lists:
5672            // one for the final results, one for the "do not use ever", one for "undefined status"
5673            // and finally one for "browser app type".
5674            for (int n=0; n<count; n++) {
5675                ResolveInfo info = candidates.get(n);
5676                String packageName = info.activityInfo.packageName;
5677                PackageSetting ps = mSettings.mPackages.get(packageName);
5678                if (ps != null) {
5679                    // Add to the special match all list (Browser use case)
5680                    if (info.handleAllWebDataURI) {
5681                        matchAllList.add(info);
5682                        continue;
5683                    }
5684                    // Try to get the status from User settings first
5685                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5686                    int status = (int)(packedStatus >> 32);
5687                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5688                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5689                        if (DEBUG_DOMAIN_VERIFICATION) {
5690                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5691                                    + " : linkgen=" + linkGeneration);
5692                        }
5693                        // Use link-enabled generation as preferredOrder, i.e.
5694                        // prefer newly-enabled over earlier-enabled.
5695                        info.preferredOrder = linkGeneration;
5696                        alwaysList.add(info);
5697                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5698                        if (DEBUG_DOMAIN_VERIFICATION) {
5699                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5700                        }
5701                        neverList.add(info);
5702                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5703                        if (DEBUG_DOMAIN_VERIFICATION) {
5704                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5705                        }
5706                        alwaysAskList.add(info);
5707                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5708                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5709                        if (DEBUG_DOMAIN_VERIFICATION) {
5710                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5711                        }
5712                        undefinedList.add(info);
5713                    }
5714                }
5715            }
5716
5717            // We'll want to include browser possibilities in a few cases
5718            boolean includeBrowser = false;
5719
5720            // First try to add the "always" resolution(s) for the current user, if any
5721            if (alwaysList.size() > 0) {
5722                result.addAll(alwaysList);
5723            } else {
5724                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5725                result.addAll(undefinedList);
5726                // Maybe add one for the other profile.
5727                if (xpDomainInfo != null && (
5728                        xpDomainInfo.bestDomainVerificationStatus
5729                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5730                    result.add(xpDomainInfo.resolveInfo);
5731                }
5732                includeBrowser = true;
5733            }
5734
5735            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5736            // If there were 'always' entries their preferred order has been set, so we also
5737            // back that off to make the alternatives equivalent
5738            if (alwaysAskList.size() > 0) {
5739                for (ResolveInfo i : result) {
5740                    i.preferredOrder = 0;
5741                }
5742                result.addAll(alwaysAskList);
5743                includeBrowser = true;
5744            }
5745
5746            if (includeBrowser) {
5747                // Also add browsers (all of them or only the default one)
5748                if (DEBUG_DOMAIN_VERIFICATION) {
5749                    Slog.v(TAG, "   ...including browsers in candidate set");
5750                }
5751                if ((matchFlags & MATCH_ALL) != 0) {
5752                    result.addAll(matchAllList);
5753                } else {
5754                    // Browser/generic handling case.  If there's a default browser, go straight
5755                    // to that (but only if there is no other higher-priority match).
5756                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5757                    int maxMatchPrio = 0;
5758                    ResolveInfo defaultBrowserMatch = null;
5759                    final int numCandidates = matchAllList.size();
5760                    for (int n = 0; n < numCandidates; n++) {
5761                        ResolveInfo info = matchAllList.get(n);
5762                        // track the highest overall match priority...
5763                        if (info.priority > maxMatchPrio) {
5764                            maxMatchPrio = info.priority;
5765                        }
5766                        // ...and the highest-priority default browser match
5767                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5768                            if (defaultBrowserMatch == null
5769                                    || (defaultBrowserMatch.priority < info.priority)) {
5770                                if (debug) {
5771                                    Slog.v(TAG, "Considering default browser match " + info);
5772                                }
5773                                defaultBrowserMatch = info;
5774                            }
5775                        }
5776                    }
5777                    if (defaultBrowserMatch != null
5778                            && defaultBrowserMatch.priority >= maxMatchPrio
5779                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5780                    {
5781                        if (debug) {
5782                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5783                        }
5784                        result.add(defaultBrowserMatch);
5785                    } else {
5786                        result.addAll(matchAllList);
5787                    }
5788                }
5789
5790                // If there is nothing selected, add all candidates and remove the ones that the user
5791                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5792                if (result.size() == 0) {
5793                    result.addAll(candidates);
5794                    result.removeAll(neverList);
5795                }
5796            }
5797        }
5798        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5799            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5800                    result.size());
5801            for (ResolveInfo info : result) {
5802                Slog.v(TAG, "  + " + info.activityInfo);
5803            }
5804        }
5805        return result;
5806    }
5807
5808    // Returns a packed value as a long:
5809    //
5810    // high 'int'-sized word: link status: undefined/ask/never/always.
5811    // low 'int'-sized word: relative priority among 'always' results.
5812    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5813        long result = ps.getDomainVerificationStatusForUser(userId);
5814        // if none available, get the master status
5815        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5816            if (ps.getIntentFilterVerificationInfo() != null) {
5817                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5818            }
5819        }
5820        return result;
5821    }
5822
5823    private ResolveInfo querySkipCurrentProfileIntents(
5824            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5825            int flags, int sourceUserId) {
5826        if (matchingFilters != null) {
5827            int size = matchingFilters.size();
5828            for (int i = 0; i < size; i ++) {
5829                CrossProfileIntentFilter filter = matchingFilters.get(i);
5830                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5831                    // Checking if there are activities in the target user that can handle the
5832                    // intent.
5833                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5834                            resolvedType, flags, sourceUserId);
5835                    if (resolveInfo != null) {
5836                        return resolveInfo;
5837                    }
5838                }
5839            }
5840        }
5841        return null;
5842    }
5843
5844    // Return matching ResolveInfo in target user if any.
5845    private ResolveInfo queryCrossProfileIntents(
5846            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5847            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5848        if (matchingFilters != null) {
5849            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5850            // match the same intent. For performance reasons, it is better not to
5851            // run queryIntent twice for the same userId
5852            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5853            int size = matchingFilters.size();
5854            for (int i = 0; i < size; i++) {
5855                CrossProfileIntentFilter filter = matchingFilters.get(i);
5856                int targetUserId = filter.getTargetUserId();
5857                boolean skipCurrentProfile =
5858                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5859                boolean skipCurrentProfileIfNoMatchFound =
5860                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5861                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5862                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5863                    // Checking if there are activities in the target user that can handle the
5864                    // intent.
5865                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5866                            resolvedType, flags, sourceUserId);
5867                    if (resolveInfo != null) return resolveInfo;
5868                    alreadyTriedUserIds.put(targetUserId, true);
5869                }
5870            }
5871        }
5872        return null;
5873    }
5874
5875    /**
5876     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5877     * will forward the intent to the filter's target user.
5878     * Otherwise, returns null.
5879     */
5880    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5881            String resolvedType, int flags, int sourceUserId) {
5882        int targetUserId = filter.getTargetUserId();
5883        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5884                resolvedType, flags, targetUserId);
5885        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5886            // If all the matches in the target profile are suspended, return null.
5887            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5888                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5889                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5890                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5891                            targetUserId);
5892                }
5893            }
5894        }
5895        return null;
5896    }
5897
5898    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5899            int sourceUserId, int targetUserId) {
5900        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5901        long ident = Binder.clearCallingIdentity();
5902        boolean targetIsProfile;
5903        try {
5904            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5905        } finally {
5906            Binder.restoreCallingIdentity(ident);
5907        }
5908        String className;
5909        if (targetIsProfile) {
5910            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5911        } else {
5912            className = FORWARD_INTENT_TO_PARENT;
5913        }
5914        ComponentName forwardingActivityComponentName = new ComponentName(
5915                mAndroidApplication.packageName, className);
5916        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5917                sourceUserId);
5918        if (!targetIsProfile) {
5919            forwardingActivityInfo.showUserIcon = targetUserId;
5920            forwardingResolveInfo.noResourceId = true;
5921        }
5922        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5923        forwardingResolveInfo.priority = 0;
5924        forwardingResolveInfo.preferredOrder = 0;
5925        forwardingResolveInfo.match = 0;
5926        forwardingResolveInfo.isDefault = true;
5927        forwardingResolveInfo.filter = filter;
5928        forwardingResolveInfo.targetUserId = targetUserId;
5929        return forwardingResolveInfo;
5930    }
5931
5932    @Override
5933    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5934            Intent[] specifics, String[] specificTypes, Intent intent,
5935            String resolvedType, int flags, int userId) {
5936        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5937                specificTypes, intent, resolvedType, flags, userId));
5938    }
5939
5940    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5941            Intent[] specifics, String[] specificTypes, Intent intent,
5942            String resolvedType, int flags, int userId) {
5943        if (!sUserManager.exists(userId)) return Collections.emptyList();
5944        flags = updateFlagsForResolve(flags, userId, intent);
5945        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5946                false /* requireFullPermission */, false /* checkShell */,
5947                "query intent activity options");
5948        final String resultsAction = intent.getAction();
5949
5950        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5951                | PackageManager.GET_RESOLVED_FILTER, userId);
5952
5953        if (DEBUG_INTENT_MATCHING) {
5954            Log.v(TAG, "Query " + intent + ": " + results);
5955        }
5956
5957        int specificsPos = 0;
5958        int N;
5959
5960        // todo: note that the algorithm used here is O(N^2).  This
5961        // isn't a problem in our current environment, but if we start running
5962        // into situations where we have more than 5 or 10 matches then this
5963        // should probably be changed to something smarter...
5964
5965        // First we go through and resolve each of the specific items
5966        // that were supplied, taking care of removing any corresponding
5967        // duplicate items in the generic resolve list.
5968        if (specifics != null) {
5969            for (int i=0; i<specifics.length; i++) {
5970                final Intent sintent = specifics[i];
5971                if (sintent == null) {
5972                    continue;
5973                }
5974
5975                if (DEBUG_INTENT_MATCHING) {
5976                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5977                }
5978
5979                String action = sintent.getAction();
5980                if (resultsAction != null && resultsAction.equals(action)) {
5981                    // If this action was explicitly requested, then don't
5982                    // remove things that have it.
5983                    action = null;
5984                }
5985
5986                ResolveInfo ri = null;
5987                ActivityInfo ai = null;
5988
5989                ComponentName comp = sintent.getComponent();
5990                if (comp == null) {
5991                    ri = resolveIntent(
5992                        sintent,
5993                        specificTypes != null ? specificTypes[i] : null,
5994                            flags, userId);
5995                    if (ri == null) {
5996                        continue;
5997                    }
5998                    if (ri == mResolveInfo) {
5999                        // ACK!  Must do something better with this.
6000                    }
6001                    ai = ri.activityInfo;
6002                    comp = new ComponentName(ai.applicationInfo.packageName,
6003                            ai.name);
6004                } else {
6005                    ai = getActivityInfo(comp, flags, userId);
6006                    if (ai == null) {
6007                        continue;
6008                    }
6009                }
6010
6011                // Look for any generic query activities that are duplicates
6012                // of this specific one, and remove them from the results.
6013                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6014                N = results.size();
6015                int j;
6016                for (j=specificsPos; j<N; j++) {
6017                    ResolveInfo sri = results.get(j);
6018                    if ((sri.activityInfo.name.equals(comp.getClassName())
6019                            && sri.activityInfo.applicationInfo.packageName.equals(
6020                                    comp.getPackageName()))
6021                        || (action != null && sri.filter.matchAction(action))) {
6022                        results.remove(j);
6023                        if (DEBUG_INTENT_MATCHING) Log.v(
6024                            TAG, "Removing duplicate item from " + j
6025                            + " due to specific " + specificsPos);
6026                        if (ri == null) {
6027                            ri = sri;
6028                        }
6029                        j--;
6030                        N--;
6031                    }
6032                }
6033
6034                // Add this specific item to its proper place.
6035                if (ri == null) {
6036                    ri = new ResolveInfo();
6037                    ri.activityInfo = ai;
6038                }
6039                results.add(specificsPos, ri);
6040                ri.specificIndex = i;
6041                specificsPos++;
6042            }
6043        }
6044
6045        // Now we go through the remaining generic results and remove any
6046        // duplicate actions that are found here.
6047        N = results.size();
6048        for (int i=specificsPos; i<N-1; i++) {
6049            final ResolveInfo rii = results.get(i);
6050            if (rii.filter == null) {
6051                continue;
6052            }
6053
6054            // Iterate over all of the actions of this result's intent
6055            // filter...  typically this should be just one.
6056            final Iterator<String> it = rii.filter.actionsIterator();
6057            if (it == null) {
6058                continue;
6059            }
6060            while (it.hasNext()) {
6061                final String action = it.next();
6062                if (resultsAction != null && resultsAction.equals(action)) {
6063                    // If this action was explicitly requested, then don't
6064                    // remove things that have it.
6065                    continue;
6066                }
6067                for (int j=i+1; j<N; j++) {
6068                    final ResolveInfo rij = results.get(j);
6069                    if (rij.filter != null && rij.filter.hasAction(action)) {
6070                        results.remove(j);
6071                        if (DEBUG_INTENT_MATCHING) Log.v(
6072                            TAG, "Removing duplicate item from " + j
6073                            + " due to action " + action + " at " + i);
6074                        j--;
6075                        N--;
6076                    }
6077                }
6078            }
6079
6080            // If the caller didn't request filter information, drop it now
6081            // so we don't have to marshall/unmarshall it.
6082            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6083                rii.filter = null;
6084            }
6085        }
6086
6087        // Filter out the caller activity if so requested.
6088        if (caller != null) {
6089            N = results.size();
6090            for (int i=0; i<N; i++) {
6091                ActivityInfo ainfo = results.get(i).activityInfo;
6092                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6093                        && caller.getClassName().equals(ainfo.name)) {
6094                    results.remove(i);
6095                    break;
6096                }
6097            }
6098        }
6099
6100        // If the caller didn't request filter information,
6101        // drop them now so we don't have to
6102        // marshall/unmarshall it.
6103        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6104            N = results.size();
6105            for (int i=0; i<N; i++) {
6106                results.get(i).filter = null;
6107            }
6108        }
6109
6110        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6111        return results;
6112    }
6113
6114    @Override
6115    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6116            String resolvedType, int flags, int userId) {
6117        return new ParceledListSlice<>(
6118                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6119    }
6120
6121    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6122            String resolvedType, int flags, int userId) {
6123        if (!sUserManager.exists(userId)) return Collections.emptyList();
6124        flags = updateFlagsForResolve(flags, userId, intent);
6125        ComponentName comp = intent.getComponent();
6126        if (comp == null) {
6127            if (intent.getSelector() != null) {
6128                intent = intent.getSelector();
6129                comp = intent.getComponent();
6130            }
6131        }
6132        if (comp != null) {
6133            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6134            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6135            if (ai != null) {
6136                ResolveInfo ri = new ResolveInfo();
6137                ri.activityInfo = ai;
6138                list.add(ri);
6139            }
6140            return list;
6141        }
6142
6143        // reader
6144        synchronized (mPackages) {
6145            String pkgName = intent.getPackage();
6146            if (pkgName == null) {
6147                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6148            }
6149            final PackageParser.Package pkg = mPackages.get(pkgName);
6150            if (pkg != null) {
6151                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6152                        userId);
6153            }
6154            return Collections.emptyList();
6155        }
6156    }
6157
6158    @Override
6159    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6160        if (!sUserManager.exists(userId)) return null;
6161        flags = updateFlagsForResolve(flags, userId, intent);
6162        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6163        if (query != null) {
6164            if (query.size() >= 1) {
6165                // If there is more than one service with the same priority,
6166                // just arbitrarily pick the first one.
6167                return query.get(0);
6168            }
6169        }
6170        return null;
6171    }
6172
6173    @Override
6174    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6175            String resolvedType, int flags, int userId) {
6176        return new ParceledListSlice<>(
6177                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6178    }
6179
6180    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6181            String resolvedType, int flags, int userId) {
6182        if (!sUserManager.exists(userId)) return Collections.emptyList();
6183        flags = updateFlagsForResolve(flags, userId, intent);
6184        ComponentName comp = intent.getComponent();
6185        if (comp == null) {
6186            if (intent.getSelector() != null) {
6187                intent = intent.getSelector();
6188                comp = intent.getComponent();
6189            }
6190        }
6191        if (comp != null) {
6192            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6193            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6194            if (si != null) {
6195                final ResolveInfo ri = new ResolveInfo();
6196                ri.serviceInfo = si;
6197                list.add(ri);
6198            }
6199            return list;
6200        }
6201
6202        // reader
6203        synchronized (mPackages) {
6204            String pkgName = intent.getPackage();
6205            if (pkgName == null) {
6206                return mServices.queryIntent(intent, resolvedType, flags, userId);
6207            }
6208            final PackageParser.Package pkg = mPackages.get(pkgName);
6209            if (pkg != null) {
6210                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6211                        userId);
6212            }
6213            return Collections.emptyList();
6214        }
6215    }
6216
6217    @Override
6218    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6219            String resolvedType, int flags, int userId) {
6220        return new ParceledListSlice<>(
6221                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6222    }
6223
6224    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6225            Intent intent, String resolvedType, int flags, int userId) {
6226        if (!sUserManager.exists(userId)) return Collections.emptyList();
6227        flags = updateFlagsForResolve(flags, userId, intent);
6228        ComponentName comp = intent.getComponent();
6229        if (comp == null) {
6230            if (intent.getSelector() != null) {
6231                intent = intent.getSelector();
6232                comp = intent.getComponent();
6233            }
6234        }
6235        if (comp != null) {
6236            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6237            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6238            if (pi != null) {
6239                final ResolveInfo ri = new ResolveInfo();
6240                ri.providerInfo = pi;
6241                list.add(ri);
6242            }
6243            return list;
6244        }
6245
6246        // reader
6247        synchronized (mPackages) {
6248            String pkgName = intent.getPackage();
6249            if (pkgName == null) {
6250                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6251            }
6252            final PackageParser.Package pkg = mPackages.get(pkgName);
6253            if (pkg != null) {
6254                return mProviders.queryIntentForPackage(
6255                        intent, resolvedType, flags, pkg.providers, userId);
6256            }
6257            return Collections.emptyList();
6258        }
6259    }
6260
6261    @Override
6262    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6263        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6264        flags = updateFlagsForPackage(flags, userId, null);
6265        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6267                true /* requireFullPermission */, false /* checkShell */,
6268                "get installed packages");
6269
6270        // writer
6271        synchronized (mPackages) {
6272            ArrayList<PackageInfo> list;
6273            if (listUninstalled) {
6274                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6275                for (PackageSetting ps : mSettings.mPackages.values()) {
6276                    final PackageInfo pi;
6277                    if (ps.pkg != null) {
6278                        pi = generatePackageInfo(ps, flags, userId);
6279                    } else {
6280                        pi = generatePackageInfo(ps, flags, userId);
6281                    }
6282                    if (pi != null) {
6283                        list.add(pi);
6284                    }
6285                }
6286            } else {
6287                list = new ArrayList<PackageInfo>(mPackages.size());
6288                for (PackageParser.Package p : mPackages.values()) {
6289                    final PackageInfo pi =
6290                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6291                    if (pi != null) {
6292                        list.add(pi);
6293                    }
6294                }
6295            }
6296
6297            return new ParceledListSlice<PackageInfo>(list);
6298        }
6299    }
6300
6301    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6302            String[] permissions, boolean[] tmp, int flags, int userId) {
6303        int numMatch = 0;
6304        final PermissionsState permissionsState = ps.getPermissionsState();
6305        for (int i=0; i<permissions.length; i++) {
6306            final String permission = permissions[i];
6307            if (permissionsState.hasPermission(permission, userId)) {
6308                tmp[i] = true;
6309                numMatch++;
6310            } else {
6311                tmp[i] = false;
6312            }
6313        }
6314        if (numMatch == 0) {
6315            return;
6316        }
6317        final PackageInfo pi;
6318        if (ps.pkg != null) {
6319            pi = generatePackageInfo(ps, flags, userId);
6320        } else {
6321            pi = generatePackageInfo(ps, flags, userId);
6322        }
6323        // The above might return null in cases of uninstalled apps or install-state
6324        // skew across users/profiles.
6325        if (pi != null) {
6326            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6327                if (numMatch == permissions.length) {
6328                    pi.requestedPermissions = permissions;
6329                } else {
6330                    pi.requestedPermissions = new String[numMatch];
6331                    numMatch = 0;
6332                    for (int i=0; i<permissions.length; i++) {
6333                        if (tmp[i]) {
6334                            pi.requestedPermissions[numMatch] = permissions[i];
6335                            numMatch++;
6336                        }
6337                    }
6338                }
6339            }
6340            list.add(pi);
6341        }
6342    }
6343
6344    @Override
6345    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6346            String[] permissions, int flags, int userId) {
6347        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6348        flags = updateFlagsForPackage(flags, userId, permissions);
6349        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6350
6351        // writer
6352        synchronized (mPackages) {
6353            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6354            boolean[] tmpBools = new boolean[permissions.length];
6355            if (listUninstalled) {
6356                for (PackageSetting ps : mSettings.mPackages.values()) {
6357                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6358                }
6359            } else {
6360                for (PackageParser.Package pkg : mPackages.values()) {
6361                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6362                    if (ps != null) {
6363                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6364                                userId);
6365                    }
6366                }
6367            }
6368
6369            return new ParceledListSlice<PackageInfo>(list);
6370        }
6371    }
6372
6373    @Override
6374    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6375        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6376        flags = updateFlagsForApplication(flags, userId, null);
6377        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6378
6379        // writer
6380        synchronized (mPackages) {
6381            ArrayList<ApplicationInfo> list;
6382            if (listUninstalled) {
6383                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6384                for (PackageSetting ps : mSettings.mPackages.values()) {
6385                    ApplicationInfo ai;
6386                    if (ps.pkg != null) {
6387                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6388                                ps.readUserState(userId), userId);
6389                    } else {
6390                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6391                    }
6392                    if (ai != null) {
6393                        list.add(ai);
6394                    }
6395                }
6396            } else {
6397                list = new ArrayList<ApplicationInfo>(mPackages.size());
6398                for (PackageParser.Package p : mPackages.values()) {
6399                    if (p.mExtras != null) {
6400                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6401                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6402                        if (ai != null) {
6403                            list.add(ai);
6404                        }
6405                    }
6406                }
6407            }
6408
6409            return new ParceledListSlice<ApplicationInfo>(list);
6410        }
6411    }
6412
6413    @Override
6414    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6415        if (DISABLE_EPHEMERAL_APPS) {
6416            return null;
6417        }
6418
6419        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6420                "getEphemeralApplications");
6421        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6422                true /* requireFullPermission */, false /* checkShell */,
6423                "getEphemeralApplications");
6424        synchronized (mPackages) {
6425            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6426                    .getEphemeralApplicationsLPw(userId);
6427            if (ephemeralApps != null) {
6428                return new ParceledListSlice<>(ephemeralApps);
6429            }
6430        }
6431        return null;
6432    }
6433
6434    @Override
6435    public boolean isEphemeralApplication(String packageName, int userId) {
6436        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6437                true /* requireFullPermission */, false /* checkShell */,
6438                "isEphemeral");
6439        if (DISABLE_EPHEMERAL_APPS) {
6440            return false;
6441        }
6442
6443        if (!isCallerSameApp(packageName)) {
6444            return false;
6445        }
6446        synchronized (mPackages) {
6447            PackageParser.Package pkg = mPackages.get(packageName);
6448            if (pkg != null) {
6449                return pkg.applicationInfo.isEphemeralApp();
6450            }
6451        }
6452        return false;
6453    }
6454
6455    @Override
6456    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6457        if (DISABLE_EPHEMERAL_APPS) {
6458            return null;
6459        }
6460
6461        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6462                true /* requireFullPermission */, false /* checkShell */,
6463                "getCookie");
6464        if (!isCallerSameApp(packageName)) {
6465            return null;
6466        }
6467        synchronized (mPackages) {
6468            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6469                    packageName, userId);
6470        }
6471    }
6472
6473    @Override
6474    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6475        if (DISABLE_EPHEMERAL_APPS) {
6476            return true;
6477        }
6478
6479        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6480                true /* requireFullPermission */, true /* checkShell */,
6481                "setCookie");
6482        if (!isCallerSameApp(packageName)) {
6483            return false;
6484        }
6485        synchronized (mPackages) {
6486            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6487                    packageName, cookie, userId);
6488        }
6489    }
6490
6491    @Override
6492    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6493        if (DISABLE_EPHEMERAL_APPS) {
6494            return null;
6495        }
6496
6497        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6498                "getEphemeralApplicationIcon");
6499        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6500                true /* requireFullPermission */, false /* checkShell */,
6501                "getEphemeralApplicationIcon");
6502        synchronized (mPackages) {
6503            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6504                    packageName, userId);
6505        }
6506    }
6507
6508    private boolean isCallerSameApp(String packageName) {
6509        PackageParser.Package pkg = mPackages.get(packageName);
6510        return pkg != null
6511                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6512    }
6513
6514    @Override
6515    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6516        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6517    }
6518
6519    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6520        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6521
6522        // reader
6523        synchronized (mPackages) {
6524            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6525            final int userId = UserHandle.getCallingUserId();
6526            while (i.hasNext()) {
6527                final PackageParser.Package p = i.next();
6528                if (p.applicationInfo == null) continue;
6529
6530                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6531                        && !p.applicationInfo.isDirectBootAware();
6532                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6533                        && p.applicationInfo.isDirectBootAware();
6534
6535                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6536                        && (!mSafeMode || isSystemApp(p))
6537                        && (matchesUnaware || matchesAware)) {
6538                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6539                    if (ps != null) {
6540                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6541                                ps.readUserState(userId), userId);
6542                        if (ai != null) {
6543                            finalList.add(ai);
6544                        }
6545                    }
6546                }
6547            }
6548        }
6549
6550        return finalList;
6551    }
6552
6553    @Override
6554    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6555        if (!sUserManager.exists(userId)) return null;
6556        flags = updateFlagsForComponent(flags, userId, name);
6557        // reader
6558        synchronized (mPackages) {
6559            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6560            PackageSetting ps = provider != null
6561                    ? mSettings.mPackages.get(provider.owner.packageName)
6562                    : null;
6563            return ps != null
6564                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6565                    ? PackageParser.generateProviderInfo(provider, flags,
6566                            ps.readUserState(userId), userId)
6567                    : null;
6568        }
6569    }
6570
6571    /**
6572     * @deprecated
6573     */
6574    @Deprecated
6575    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6576        // reader
6577        synchronized (mPackages) {
6578            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6579                    .entrySet().iterator();
6580            final int userId = UserHandle.getCallingUserId();
6581            while (i.hasNext()) {
6582                Map.Entry<String, PackageParser.Provider> entry = i.next();
6583                PackageParser.Provider p = entry.getValue();
6584                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6585
6586                if (ps != null && p.syncable
6587                        && (!mSafeMode || (p.info.applicationInfo.flags
6588                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6589                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6590                            ps.readUserState(userId), userId);
6591                    if (info != null) {
6592                        outNames.add(entry.getKey());
6593                        outInfo.add(info);
6594                    }
6595                }
6596            }
6597        }
6598    }
6599
6600    @Override
6601    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6602            int uid, int flags) {
6603        final int userId = processName != null ? UserHandle.getUserId(uid)
6604                : UserHandle.getCallingUserId();
6605        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6606        flags = updateFlagsForComponent(flags, userId, processName);
6607
6608        ArrayList<ProviderInfo> finalList = null;
6609        // reader
6610        synchronized (mPackages) {
6611            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6612            while (i.hasNext()) {
6613                final PackageParser.Provider p = i.next();
6614                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6615                if (ps != null && p.info.authority != null
6616                        && (processName == null
6617                                || (p.info.processName.equals(processName)
6618                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6619                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6620                    if (finalList == null) {
6621                        finalList = new ArrayList<ProviderInfo>(3);
6622                    }
6623                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6624                            ps.readUserState(userId), userId);
6625                    if (info != null) {
6626                        finalList.add(info);
6627                    }
6628                }
6629            }
6630        }
6631
6632        if (finalList != null) {
6633            Collections.sort(finalList, mProviderInitOrderSorter);
6634            return new ParceledListSlice<ProviderInfo>(finalList);
6635        }
6636
6637        return ParceledListSlice.emptyList();
6638    }
6639
6640    @Override
6641    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6642        // reader
6643        synchronized (mPackages) {
6644            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6645            return PackageParser.generateInstrumentationInfo(i, flags);
6646        }
6647    }
6648
6649    @Override
6650    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6651            String targetPackage, int flags) {
6652        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6653    }
6654
6655    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6656            int flags) {
6657        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6658
6659        // reader
6660        synchronized (mPackages) {
6661            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6662            while (i.hasNext()) {
6663                final PackageParser.Instrumentation p = i.next();
6664                if (targetPackage == null
6665                        || targetPackage.equals(p.info.targetPackage)) {
6666                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6667                            flags);
6668                    if (ii != null) {
6669                        finalList.add(ii);
6670                    }
6671                }
6672            }
6673        }
6674
6675        return finalList;
6676    }
6677
6678    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6679        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6680        if (overlays == null) {
6681            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6682            return;
6683        }
6684        for (PackageParser.Package opkg : overlays.values()) {
6685            // Not much to do if idmap fails: we already logged the error
6686            // and we certainly don't want to abort installation of pkg simply
6687            // because an overlay didn't fit properly. For these reasons,
6688            // ignore the return value of createIdmapForPackagePairLI.
6689            createIdmapForPackagePairLI(pkg, opkg);
6690        }
6691    }
6692
6693    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6694            PackageParser.Package opkg) {
6695        if (!opkg.mTrustedOverlay) {
6696            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6697                    opkg.baseCodePath + ": overlay not trusted");
6698            return false;
6699        }
6700        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6701        if (overlaySet == null) {
6702            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6703                    opkg.baseCodePath + " but target package has no known overlays");
6704            return false;
6705        }
6706        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6707        // TODO: generate idmap for split APKs
6708        try {
6709            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6710        } catch (InstallerException e) {
6711            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6712                    + opkg.baseCodePath);
6713            return false;
6714        }
6715        PackageParser.Package[] overlayArray =
6716            overlaySet.values().toArray(new PackageParser.Package[0]);
6717        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6718            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6719                return p1.mOverlayPriority - p2.mOverlayPriority;
6720            }
6721        };
6722        Arrays.sort(overlayArray, cmp);
6723
6724        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6725        int i = 0;
6726        for (PackageParser.Package p : overlayArray) {
6727            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6728        }
6729        return true;
6730    }
6731
6732    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6733        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6734        try {
6735            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6736        } finally {
6737            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6738        }
6739    }
6740
6741    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6742        final File[] files = dir.listFiles();
6743        if (ArrayUtils.isEmpty(files)) {
6744            Log.d(TAG, "No files in app dir " + dir);
6745            return;
6746        }
6747
6748        if (DEBUG_PACKAGE_SCANNING) {
6749            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6750                    + " flags=0x" + Integer.toHexString(parseFlags));
6751        }
6752
6753        for (File file : files) {
6754            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6755                    && !PackageInstallerService.isStageName(file.getName());
6756            if (!isPackage) {
6757                // Ignore entries which are not packages
6758                continue;
6759            }
6760            try {
6761                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6762                        scanFlags, currentTime, null);
6763            } catch (PackageManagerException e) {
6764                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6765
6766                // Delete invalid userdata apps
6767                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6768                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6769                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6770                    removeCodePathLI(file);
6771                }
6772            }
6773        }
6774    }
6775
6776    private static File getSettingsProblemFile() {
6777        File dataDir = Environment.getDataDirectory();
6778        File systemDir = new File(dataDir, "system");
6779        File fname = new File(systemDir, "uiderrors.txt");
6780        return fname;
6781    }
6782
6783    static void reportSettingsProblem(int priority, String msg) {
6784        logCriticalInfo(priority, msg);
6785    }
6786
6787    static void logCriticalInfo(int priority, String msg) {
6788        Slog.println(priority, TAG, msg);
6789        EventLogTags.writePmCriticalInfo(msg);
6790        try {
6791            File fname = getSettingsProblemFile();
6792            FileOutputStream out = new FileOutputStream(fname, true);
6793            PrintWriter pw = new FastPrintWriter(out);
6794            SimpleDateFormat formatter = new SimpleDateFormat();
6795            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6796            pw.println(dateString + ": " + msg);
6797            pw.close();
6798            FileUtils.setPermissions(
6799                    fname.toString(),
6800                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6801                    -1, -1);
6802        } catch (java.io.IOException e) {
6803        }
6804    }
6805
6806    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6807        if (srcFile.isDirectory()) {
6808            final File baseFile = new File(pkg.baseCodePath);
6809            long maxModifiedTime = baseFile.lastModified();
6810            if (pkg.splitCodePaths != null) {
6811                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6812                    final File splitFile = new File(pkg.splitCodePaths[i]);
6813                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6814                }
6815            }
6816            return maxModifiedTime;
6817        }
6818        return srcFile.lastModified();
6819    }
6820
6821    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6822            final int policyFlags) throws PackageManagerException {
6823        if (ps != null
6824                && ps.codePath.equals(srcFile)
6825                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6826                && !isCompatSignatureUpdateNeeded(pkg)
6827                && !isRecoverSignatureUpdateNeeded(pkg)) {
6828            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6829            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6830            ArraySet<PublicKey> signingKs;
6831            synchronized (mPackages) {
6832                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6833            }
6834            if (ps.signatures.mSignatures != null
6835                    && ps.signatures.mSignatures.length != 0
6836                    && signingKs != null) {
6837                // Optimization: reuse the existing cached certificates
6838                // if the package appears to be unchanged.
6839                pkg.mSignatures = ps.signatures.mSignatures;
6840                pkg.mSigningKeys = signingKs;
6841                return;
6842            }
6843
6844            Slog.w(TAG, "PackageSetting for " + ps.name
6845                    + " is missing signatures.  Collecting certs again to recover them.");
6846        } else {
6847            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6848        }
6849
6850        try {
6851            PackageParser.collectCertificates(pkg, policyFlags);
6852        } catch (PackageParserException e) {
6853            throw PackageManagerException.from(e);
6854        }
6855    }
6856
6857    /**
6858     *  Traces a package scan.
6859     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6860     */
6861    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6862            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6863        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6864        try {
6865            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6866        } finally {
6867            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6868        }
6869    }
6870
6871    /**
6872     *  Scans a package and returns the newly parsed package.
6873     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6874     */
6875    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6876            long currentTime, UserHandle user) throws PackageManagerException {
6877        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6878        PackageParser pp = new PackageParser();
6879        pp.setSeparateProcesses(mSeparateProcesses);
6880        pp.setOnlyCoreApps(mOnlyCore);
6881        pp.setDisplayMetrics(mMetrics);
6882
6883        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6884            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6885        }
6886
6887        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6888        final PackageParser.Package pkg;
6889        try {
6890            pkg = pp.parsePackage(scanFile, parseFlags);
6891        } catch (PackageParserException e) {
6892            throw PackageManagerException.from(e);
6893        } finally {
6894            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6895        }
6896
6897        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6898    }
6899
6900    /**
6901     *  Scans a package and returns the newly parsed package.
6902     *  @throws PackageManagerException on a parse error.
6903     */
6904    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6905            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6906            throws PackageManagerException {
6907        // If the package has children and this is the first dive in the function
6908        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6909        // packages (parent and children) would be successfully scanned before the
6910        // actual scan since scanning mutates internal state and we want to atomically
6911        // install the package and its children.
6912        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6913            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6914                scanFlags |= SCAN_CHECK_ONLY;
6915            }
6916        } else {
6917            scanFlags &= ~SCAN_CHECK_ONLY;
6918        }
6919
6920        // Scan the parent
6921        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6922                scanFlags, currentTime, user);
6923
6924        // Scan the children
6925        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6926        for (int i = 0; i < childCount; i++) {
6927            PackageParser.Package childPackage = pkg.childPackages.get(i);
6928            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6929                    currentTime, user);
6930        }
6931
6932
6933        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6934            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6935        }
6936
6937        return scannedPkg;
6938    }
6939
6940    /**
6941     *  Scans a package and returns the newly parsed package.
6942     *  @throws PackageManagerException on a parse error.
6943     */
6944    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6945            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6946            throws PackageManagerException {
6947        PackageSetting ps = null;
6948        PackageSetting updatedPkg;
6949        // reader
6950        synchronized (mPackages) {
6951            // Look to see if we already know about this package.
6952            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6953            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6954                // This package has been renamed to its original name.  Let's
6955                // use that.
6956                ps = mSettings.peekPackageLPr(oldName);
6957            }
6958            // If there was no original package, see one for the real package name.
6959            if (ps == null) {
6960                ps = mSettings.peekPackageLPr(pkg.packageName);
6961            }
6962            // Check to see if this package could be hiding/updating a system
6963            // package.  Must look for it either under the original or real
6964            // package name depending on our state.
6965            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6966            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6967
6968            // If this is a package we don't know about on the system partition, we
6969            // may need to remove disabled child packages on the system partition
6970            // or may need to not add child packages if the parent apk is updated
6971            // on the data partition and no longer defines this child package.
6972            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6973                // If this is a parent package for an updated system app and this system
6974                // app got an OTA update which no longer defines some of the child packages
6975                // we have to prune them from the disabled system packages.
6976                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6977                if (disabledPs != null) {
6978                    final int scannedChildCount = (pkg.childPackages != null)
6979                            ? pkg.childPackages.size() : 0;
6980                    final int disabledChildCount = disabledPs.childPackageNames != null
6981                            ? disabledPs.childPackageNames.size() : 0;
6982                    for (int i = 0; i < disabledChildCount; i++) {
6983                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6984                        boolean disabledPackageAvailable = false;
6985                        for (int j = 0; j < scannedChildCount; j++) {
6986                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6987                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6988                                disabledPackageAvailable = true;
6989                                break;
6990                            }
6991                         }
6992                         if (!disabledPackageAvailable) {
6993                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6994                         }
6995                    }
6996                }
6997            }
6998        }
6999
7000        boolean updatedPkgBetter = false;
7001        // First check if this is a system package that may involve an update
7002        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7003            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7004            // it needs to drop FLAG_PRIVILEGED.
7005            if (locationIsPrivileged(scanFile)) {
7006                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7007            } else {
7008                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7009            }
7010
7011            if (ps != null && !ps.codePath.equals(scanFile)) {
7012                // The path has changed from what was last scanned...  check the
7013                // version of the new path against what we have stored to determine
7014                // what to do.
7015                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7016                if (pkg.mVersionCode <= ps.versionCode) {
7017                    // The system package has been updated and the code path does not match
7018                    // Ignore entry. Skip it.
7019                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7020                            + " ignored: updated version " + ps.versionCode
7021                            + " better than this " + pkg.mVersionCode);
7022                    if (!updatedPkg.codePath.equals(scanFile)) {
7023                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7024                                + ps.name + " changing from " + updatedPkg.codePathString
7025                                + " to " + scanFile);
7026                        updatedPkg.codePath = scanFile;
7027                        updatedPkg.codePathString = scanFile.toString();
7028                        updatedPkg.resourcePath = scanFile;
7029                        updatedPkg.resourcePathString = scanFile.toString();
7030                    }
7031                    updatedPkg.pkg = pkg;
7032                    updatedPkg.versionCode = pkg.mVersionCode;
7033
7034                    // Update the disabled system child packages to point to the package too.
7035                    final int childCount = updatedPkg.childPackageNames != null
7036                            ? updatedPkg.childPackageNames.size() : 0;
7037                    for (int i = 0; i < childCount; i++) {
7038                        String childPackageName = updatedPkg.childPackageNames.get(i);
7039                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7040                                childPackageName);
7041                        if (updatedChildPkg != null) {
7042                            updatedChildPkg.pkg = pkg;
7043                            updatedChildPkg.versionCode = pkg.mVersionCode;
7044                        }
7045                    }
7046
7047                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7048                            + scanFile + " ignored: updated version " + ps.versionCode
7049                            + " better than this " + pkg.mVersionCode);
7050                } else {
7051                    // The current app on the system partition is better than
7052                    // what we have updated to on the data partition; switch
7053                    // back to the system partition version.
7054                    // At this point, its safely assumed that package installation for
7055                    // apps in system partition will go through. If not there won't be a working
7056                    // version of the app
7057                    // writer
7058                    synchronized (mPackages) {
7059                        // Just remove the loaded entries from package lists.
7060                        mPackages.remove(ps.name);
7061                    }
7062
7063                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7064                            + " reverting from " + ps.codePathString
7065                            + ": new version " + pkg.mVersionCode
7066                            + " better than installed " + ps.versionCode);
7067
7068                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7069                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7070                    synchronized (mInstallLock) {
7071                        args.cleanUpResourcesLI();
7072                    }
7073                    synchronized (mPackages) {
7074                        mSettings.enableSystemPackageLPw(ps.name);
7075                    }
7076                    updatedPkgBetter = true;
7077                }
7078            }
7079        }
7080
7081        if (updatedPkg != null) {
7082            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7083            // initially
7084            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7085
7086            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7087            // flag set initially
7088            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7089                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7090            }
7091        }
7092
7093        // Verify certificates against what was last scanned
7094        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7095
7096        /*
7097         * A new system app appeared, but we already had a non-system one of the
7098         * same name installed earlier.
7099         */
7100        boolean shouldHideSystemApp = false;
7101        if (updatedPkg == null && ps != null
7102                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7103            /*
7104             * Check to make sure the signatures match first. If they don't,
7105             * wipe the installed application and its data.
7106             */
7107            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7108                    != PackageManager.SIGNATURE_MATCH) {
7109                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7110                        + " signatures don't match existing userdata copy; removing");
7111                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7112                        "scanPackageInternalLI")) {
7113                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7114                }
7115                ps = null;
7116            } else {
7117                /*
7118                 * If the newly-added system app is an older version than the
7119                 * already installed version, hide it. It will be scanned later
7120                 * and re-added like an update.
7121                 */
7122                if (pkg.mVersionCode <= ps.versionCode) {
7123                    shouldHideSystemApp = true;
7124                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7125                            + " but new version " + pkg.mVersionCode + " better than installed "
7126                            + ps.versionCode + "; hiding system");
7127                } else {
7128                    /*
7129                     * The newly found system app is a newer version that the
7130                     * one previously installed. Simply remove the
7131                     * already-installed application and replace it with our own
7132                     * while keeping the application data.
7133                     */
7134                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7135                            + " reverting from " + ps.codePathString + ": new version "
7136                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7137                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7138                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7139                    synchronized (mInstallLock) {
7140                        args.cleanUpResourcesLI();
7141                    }
7142                }
7143            }
7144        }
7145
7146        // The apk is forward locked (not public) if its code and resources
7147        // are kept in different files. (except for app in either system or
7148        // vendor path).
7149        // TODO grab this value from PackageSettings
7150        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7151            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7152                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7153            }
7154        }
7155
7156        // TODO: extend to support forward-locked splits
7157        String resourcePath = null;
7158        String baseResourcePath = null;
7159        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7160            if (ps != null && ps.resourcePathString != null) {
7161                resourcePath = ps.resourcePathString;
7162                baseResourcePath = ps.resourcePathString;
7163            } else {
7164                // Should not happen at all. Just log an error.
7165                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7166            }
7167        } else {
7168            resourcePath = pkg.codePath;
7169            baseResourcePath = pkg.baseCodePath;
7170        }
7171
7172        // Set application objects path explicitly.
7173        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7174        pkg.setApplicationInfoCodePath(pkg.codePath);
7175        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7176        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7177        pkg.setApplicationInfoResourcePath(resourcePath);
7178        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7179        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7180
7181        // Note that we invoke the following method only if we are about to unpack an application
7182        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7183                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7184
7185        /*
7186         * If the system app should be overridden by a previously installed
7187         * data, hide the system app now and let the /data/app scan pick it up
7188         * again.
7189         */
7190        if (shouldHideSystemApp) {
7191            synchronized (mPackages) {
7192                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7193            }
7194        }
7195
7196        return scannedPkg;
7197    }
7198
7199    private static String fixProcessName(String defProcessName,
7200            String processName, int uid) {
7201        if (processName == null) {
7202            return defProcessName;
7203        }
7204        return processName;
7205    }
7206
7207    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7208            throws PackageManagerException {
7209        if (pkgSetting.signatures.mSignatures != null) {
7210            // Already existing package. Make sure signatures match
7211            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7212                    == PackageManager.SIGNATURE_MATCH;
7213            if (!match) {
7214                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7215                        == PackageManager.SIGNATURE_MATCH;
7216            }
7217            if (!match) {
7218                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7219                        == PackageManager.SIGNATURE_MATCH;
7220            }
7221            if (!match) {
7222                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7223                        + pkg.packageName + " signatures do not match the "
7224                        + "previously installed version; ignoring!");
7225            }
7226        }
7227
7228        // Check for shared user signatures
7229        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7230            // Already existing package. Make sure signatures match
7231            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7232                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7233            if (!match) {
7234                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7235                        == PackageManager.SIGNATURE_MATCH;
7236            }
7237            if (!match) {
7238                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7239                        == PackageManager.SIGNATURE_MATCH;
7240            }
7241            if (!match) {
7242                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7243                        "Package " + pkg.packageName
7244                        + " has no signatures that match those in shared user "
7245                        + pkgSetting.sharedUser.name + "; ignoring!");
7246            }
7247        }
7248    }
7249
7250    /**
7251     * Enforces that only the system UID or root's UID can call a method exposed
7252     * via Binder.
7253     *
7254     * @param message used as message if SecurityException is thrown
7255     * @throws SecurityException if the caller is not system or root
7256     */
7257    private static final void enforceSystemOrRoot(String message) {
7258        final int uid = Binder.getCallingUid();
7259        if (uid != Process.SYSTEM_UID && uid != 0) {
7260            throw new SecurityException(message);
7261        }
7262    }
7263
7264    @Override
7265    public void performFstrimIfNeeded() {
7266        enforceSystemOrRoot("Only the system can request fstrim");
7267
7268        // Before everything else, see whether we need to fstrim.
7269        try {
7270            IMountService ms = PackageHelper.getMountService();
7271            if (ms != null) {
7272                boolean doTrim = false;
7273                final long interval = android.provider.Settings.Global.getLong(
7274                        mContext.getContentResolver(),
7275                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7276                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7277                if (interval > 0) {
7278                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7279                    if (timeSinceLast > interval) {
7280                        doTrim = true;
7281                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7282                                + "; running immediately");
7283                    }
7284                }
7285                if (doTrim) {
7286                    if (!isFirstBoot()) {
7287                        try {
7288                            ActivityManagerNative.getDefault().showBootMessage(
7289                                    mContext.getResources().getString(
7290                                            R.string.android_upgrading_fstrim), true);
7291                        } catch (RemoteException e) {
7292                        }
7293                    }
7294                    ms.runMaintenance();
7295                }
7296            } else {
7297                Slog.e(TAG, "Mount service unavailable!");
7298            }
7299        } catch (RemoteException e) {
7300            // Can't happen; MountService is local
7301        }
7302    }
7303
7304    @Override
7305    public void updatePackagesIfNeeded() {
7306        enforceSystemOrRoot("Only the system can request package update");
7307
7308        // We need to re-extract after an OTA.
7309        boolean causeUpgrade = isUpgrade();
7310
7311        // First boot or factory reset.
7312        // Note: we also handle devices that are upgrading to N right now as if it is their
7313        //       first boot, as they do not have profile data.
7314        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7315
7316        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7317        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7318
7319        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7320            return;
7321        }
7322
7323        List<PackageParser.Package> pkgs;
7324        synchronized (mPackages) {
7325            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7326        }
7327
7328        final long startTime = System.nanoTime();
7329        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7330                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7331
7332        final int elapsedTimeSeconds =
7333                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7334
7335        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7336        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7337        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7338        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7339        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7340    }
7341
7342    /**
7343     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7344     * containing statistics about the invocation. The array consists of three elements,
7345     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7346     * and {@code numberOfPackagesFailed}.
7347     */
7348    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7349            String compilerFilter) {
7350
7351        int numberOfPackagesVisited = 0;
7352        int numberOfPackagesOptimized = 0;
7353        int numberOfPackagesSkipped = 0;
7354        int numberOfPackagesFailed = 0;
7355        final int numberOfPackagesToDexopt = pkgs.size();
7356
7357        for (PackageParser.Package pkg : pkgs) {
7358            numberOfPackagesVisited++;
7359
7360            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7361                if (DEBUG_DEXOPT) {
7362                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7363                }
7364                numberOfPackagesSkipped++;
7365                continue;
7366            }
7367
7368            if (DEBUG_DEXOPT) {
7369                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7370                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7371            }
7372
7373            if (showDialog) {
7374                try {
7375                    ActivityManagerNative.getDefault().showBootMessage(
7376                            mContext.getResources().getString(R.string.android_upgrading_apk,
7377                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7378                } catch (RemoteException e) {
7379                }
7380            }
7381
7382            // If the OTA updates a system app which was previously preopted to a non-preopted state
7383            // the app might end up being verified at runtime. That's because by default the apps
7384            // are verify-profile but for preopted apps there's no profile.
7385            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7386            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7387            // filter (by default interpret-only).
7388            // Note that at this stage unused apps are already filtered.
7389            if (isSystemApp(pkg) &&
7390                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7391                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7392                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7393            }
7394
7395            // checkProfiles is false to avoid merging profiles during boot which
7396            // might interfere with background compilation (b/28612421).
7397            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7398            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7399            // trade-off worth doing to save boot time work.
7400            int dexOptStatus = performDexOptTraced(pkg.packageName,
7401                    false /* checkProfiles */,
7402                    compilerFilter,
7403                    false /* force */);
7404            switch (dexOptStatus) {
7405                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7406                    numberOfPackagesOptimized++;
7407                    break;
7408                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7409                    numberOfPackagesSkipped++;
7410                    break;
7411                case PackageDexOptimizer.DEX_OPT_FAILED:
7412                    numberOfPackagesFailed++;
7413                    break;
7414                default:
7415                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7416                    break;
7417            }
7418        }
7419
7420        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7421                numberOfPackagesFailed };
7422    }
7423
7424    @Override
7425    public void notifyPackageUse(String packageName, int reason) {
7426        synchronized (mPackages) {
7427            PackageParser.Package p = mPackages.get(packageName);
7428            if (p == null) {
7429                return;
7430            }
7431            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7432        }
7433    }
7434
7435    // TODO: this is not used nor needed. Delete it.
7436    @Override
7437    public boolean performDexOptIfNeeded(String packageName) {
7438        int dexOptStatus = performDexOptTraced(packageName,
7439                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7440        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7441    }
7442
7443    @Override
7444    public boolean performDexOpt(String packageName,
7445            boolean checkProfiles, int compileReason, boolean force) {
7446        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7447                getCompilerFilterForReason(compileReason), force);
7448        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7449    }
7450
7451    @Override
7452    public boolean performDexOptMode(String packageName,
7453            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7454        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7455                targetCompilerFilter, force);
7456        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7457    }
7458
7459    private int performDexOptTraced(String packageName,
7460                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7461        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7462        try {
7463            return performDexOptInternal(packageName, checkProfiles,
7464                    targetCompilerFilter, force);
7465        } finally {
7466            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7467        }
7468    }
7469
7470    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7471    // if the package can now be considered up to date for the given filter.
7472    private int performDexOptInternal(String packageName,
7473                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7474        PackageParser.Package p;
7475        synchronized (mPackages) {
7476            p = mPackages.get(packageName);
7477            if (p == null) {
7478                // Package could not be found. Report failure.
7479                return PackageDexOptimizer.DEX_OPT_FAILED;
7480            }
7481            mPackageUsage.write(false);
7482        }
7483        long callingId = Binder.clearCallingIdentity();
7484        try {
7485            synchronized (mInstallLock) {
7486                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7487                        targetCompilerFilter, force);
7488            }
7489        } finally {
7490            Binder.restoreCallingIdentity(callingId);
7491        }
7492    }
7493
7494    public ArraySet<String> getOptimizablePackages() {
7495        ArraySet<String> pkgs = new ArraySet<String>();
7496        synchronized (mPackages) {
7497            for (PackageParser.Package p : mPackages.values()) {
7498                if (PackageDexOptimizer.canOptimizePackage(p)) {
7499                    pkgs.add(p.packageName);
7500                }
7501            }
7502        }
7503        return pkgs;
7504    }
7505
7506    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7507            boolean checkProfiles, String targetCompilerFilter,
7508            boolean force) {
7509        // Select the dex optimizer based on the force parameter.
7510        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7511        //       allocate an object here.
7512        PackageDexOptimizer pdo = force
7513                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7514                : mPackageDexOptimizer;
7515
7516        // Optimize all dependencies first. Note: we ignore the return value and march on
7517        // on errors.
7518        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7519        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7520        if (!deps.isEmpty()) {
7521            for (PackageParser.Package depPackage : deps) {
7522                // TODO: Analyze and investigate if we (should) profile libraries.
7523                // Currently this will do a full compilation of the library by default.
7524                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7525                        false /* checkProfiles */,
7526                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7527            }
7528        }
7529        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7530                targetCompilerFilter);
7531    }
7532
7533    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7534        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7535            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7536            Set<String> collectedNames = new HashSet<>();
7537            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7538
7539            retValue.remove(p);
7540
7541            return retValue;
7542        } else {
7543            return Collections.emptyList();
7544        }
7545    }
7546
7547    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7548            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7549        if (!collectedNames.contains(p.packageName)) {
7550            collectedNames.add(p.packageName);
7551            collected.add(p);
7552
7553            if (p.usesLibraries != null) {
7554                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7555            }
7556            if (p.usesOptionalLibraries != null) {
7557                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7558                        collectedNames);
7559            }
7560        }
7561    }
7562
7563    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7564            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7565        for (String libName : libs) {
7566            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7567            if (libPkg != null) {
7568                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7569            }
7570        }
7571    }
7572
7573    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7574        synchronized (mPackages) {
7575            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7576            if (lib != null && lib.apk != null) {
7577                return mPackages.get(lib.apk);
7578            }
7579        }
7580        return null;
7581    }
7582
7583    public void shutdown() {
7584        mPackageUsage.write(true);
7585    }
7586
7587    @Override
7588    public void dumpProfiles(String packageName) {
7589        PackageParser.Package pkg;
7590        synchronized (mPackages) {
7591            pkg = mPackages.get(packageName);
7592            if (pkg == null) {
7593                throw new IllegalArgumentException("Unknown package: " + packageName);
7594            }
7595        }
7596        /* Only the shell, root, or the app user should be able to dump profiles. */
7597        int callingUid = Binder.getCallingUid();
7598        if (callingUid != Process.SHELL_UID &&
7599            callingUid != Process.ROOT_UID &&
7600            callingUid != pkg.applicationInfo.uid) {
7601            throw new SecurityException("dumpProfiles");
7602        }
7603
7604        synchronized (mInstallLock) {
7605            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7606            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7607            try {
7608                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7609                String gid = Integer.toString(sharedGid);
7610                String codePaths = TextUtils.join(";", allCodePaths);
7611                mInstaller.dumpProfiles(gid, packageName, codePaths);
7612            } catch (InstallerException e) {
7613                Slog.w(TAG, "Failed to dump profiles", e);
7614            }
7615            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7616        }
7617    }
7618
7619    @Override
7620    public void forceDexOpt(String packageName) {
7621        enforceSystemOrRoot("forceDexOpt");
7622
7623        PackageParser.Package pkg;
7624        synchronized (mPackages) {
7625            pkg = mPackages.get(packageName);
7626            if (pkg == null) {
7627                throw new IllegalArgumentException("Unknown package: " + packageName);
7628            }
7629        }
7630
7631        synchronized (mInstallLock) {
7632            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7633
7634            // Whoever is calling forceDexOpt wants a fully compiled package.
7635            // Don't use profiles since that may cause compilation to be skipped.
7636            final int res = performDexOptInternalWithDependenciesLI(pkg,
7637                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7638                    true /* force */);
7639
7640            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7641            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7642                throw new IllegalStateException("Failed to dexopt: " + res);
7643            }
7644        }
7645    }
7646
7647    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7648        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7649            Slog.w(TAG, "Unable to update from " + oldPkg.name
7650                    + " to " + newPkg.packageName
7651                    + ": old package not in system partition");
7652            return false;
7653        } else if (mPackages.get(oldPkg.name) != null) {
7654            Slog.w(TAG, "Unable to update from " + oldPkg.name
7655                    + " to " + newPkg.packageName
7656                    + ": old package still exists");
7657            return false;
7658        }
7659        return true;
7660    }
7661
7662    void removeCodePathLI(File codePath) {
7663        if (codePath.isDirectory()) {
7664            try {
7665                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7666            } catch (InstallerException e) {
7667                Slog.w(TAG, "Failed to remove code path", e);
7668            }
7669        } else {
7670            codePath.delete();
7671        }
7672    }
7673
7674    private int[] resolveUserIds(int userId) {
7675        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7676    }
7677
7678    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7679        if (pkg == null) {
7680            Slog.wtf(TAG, "Package was null!", new Throwable());
7681            return;
7682        }
7683        clearAppDataLeafLIF(pkg, userId, flags);
7684        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7685        for (int i = 0; i < childCount; i++) {
7686            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7687        }
7688    }
7689
7690    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7691        final PackageSetting ps;
7692        synchronized (mPackages) {
7693            ps = mSettings.mPackages.get(pkg.packageName);
7694        }
7695        for (int realUserId : resolveUserIds(userId)) {
7696            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7697            try {
7698                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7699                        ceDataInode);
7700            } catch (InstallerException e) {
7701                Slog.w(TAG, String.valueOf(e));
7702            }
7703        }
7704    }
7705
7706    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7707        if (pkg == null) {
7708            Slog.wtf(TAG, "Package was null!", new Throwable());
7709            return;
7710        }
7711        destroyAppDataLeafLIF(pkg, userId, flags);
7712        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7713        for (int i = 0; i < childCount; i++) {
7714            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7715        }
7716    }
7717
7718    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7719        final PackageSetting ps;
7720        synchronized (mPackages) {
7721            ps = mSettings.mPackages.get(pkg.packageName);
7722        }
7723        for (int realUserId : resolveUserIds(userId)) {
7724            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7725            try {
7726                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7727                        ceDataInode);
7728            } catch (InstallerException e) {
7729                Slog.w(TAG, String.valueOf(e));
7730            }
7731        }
7732    }
7733
7734    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7735        if (pkg == null) {
7736            Slog.wtf(TAG, "Package was null!", new Throwable());
7737            return;
7738        }
7739        destroyAppProfilesLeafLIF(pkg);
7740        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7741        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7742        for (int i = 0; i < childCount; i++) {
7743            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7744            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7745                    true /* removeBaseMarker */);
7746        }
7747    }
7748
7749    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7750            boolean removeBaseMarker) {
7751        if (pkg.isForwardLocked()) {
7752            return;
7753        }
7754
7755        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7756            try {
7757                path = PackageManagerServiceUtils.realpath(new File(path));
7758            } catch (IOException e) {
7759                // TODO: Should we return early here ?
7760                Slog.w(TAG, "Failed to get canonical path", e);
7761                continue;
7762            }
7763
7764            final String useMarker = path.replace('/', '@');
7765            for (int realUserId : resolveUserIds(userId)) {
7766                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7767                if (removeBaseMarker) {
7768                    File foreignUseMark = new File(profileDir, useMarker);
7769                    if (foreignUseMark.exists()) {
7770                        if (!foreignUseMark.delete()) {
7771                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7772                                    + pkg.packageName);
7773                        }
7774                    }
7775                }
7776
7777                File[] markers = profileDir.listFiles();
7778                if (markers != null) {
7779                    final String searchString = "@" + pkg.packageName + "@";
7780                    // We also delete all markers that contain the package name we're
7781                    // uninstalling. These are associated with secondary dex-files belonging
7782                    // to the package. Reconstructing the path of these dex files is messy
7783                    // in general.
7784                    for (File marker : markers) {
7785                        if (marker.getName().indexOf(searchString) > 0) {
7786                            if (!marker.delete()) {
7787                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7788                                    + pkg.packageName);
7789                            }
7790                        }
7791                    }
7792                }
7793            }
7794        }
7795    }
7796
7797    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7798        try {
7799            mInstaller.destroyAppProfiles(pkg.packageName);
7800        } catch (InstallerException e) {
7801            Slog.w(TAG, String.valueOf(e));
7802        }
7803    }
7804
7805    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7806        if (pkg == null) {
7807            Slog.wtf(TAG, "Package was null!", new Throwable());
7808            return;
7809        }
7810        clearAppProfilesLeafLIF(pkg);
7811        // We don't remove the base foreign use marker when clearing profiles because
7812        // we will rename it when the app is updated. Unlike the actual profile contents,
7813        // the foreign use marker is good across installs.
7814        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7815        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7816        for (int i = 0; i < childCount; i++) {
7817            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7818        }
7819    }
7820
7821    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7822        try {
7823            mInstaller.clearAppProfiles(pkg.packageName);
7824        } catch (InstallerException e) {
7825            Slog.w(TAG, String.valueOf(e));
7826        }
7827    }
7828
7829    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7830            long lastUpdateTime) {
7831        // Set parent install/update time
7832        PackageSetting ps = (PackageSetting) pkg.mExtras;
7833        if (ps != null) {
7834            ps.firstInstallTime = firstInstallTime;
7835            ps.lastUpdateTime = lastUpdateTime;
7836        }
7837        // Set children install/update time
7838        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7839        for (int i = 0; i < childCount; i++) {
7840            PackageParser.Package childPkg = pkg.childPackages.get(i);
7841            ps = (PackageSetting) childPkg.mExtras;
7842            if (ps != null) {
7843                ps.firstInstallTime = firstInstallTime;
7844                ps.lastUpdateTime = lastUpdateTime;
7845            }
7846        }
7847    }
7848
7849    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7850            PackageParser.Package changingLib) {
7851        if (file.path != null) {
7852            usesLibraryFiles.add(file.path);
7853            return;
7854        }
7855        PackageParser.Package p = mPackages.get(file.apk);
7856        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7857            // If we are doing this while in the middle of updating a library apk,
7858            // then we need to make sure to use that new apk for determining the
7859            // dependencies here.  (We haven't yet finished committing the new apk
7860            // to the package manager state.)
7861            if (p == null || p.packageName.equals(changingLib.packageName)) {
7862                p = changingLib;
7863            }
7864        }
7865        if (p != null) {
7866            usesLibraryFiles.addAll(p.getAllCodePaths());
7867        }
7868    }
7869
7870    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7871            PackageParser.Package changingLib) throws PackageManagerException {
7872        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7873            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7874            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7875            for (int i=0; i<N; i++) {
7876                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7877                if (file == null) {
7878                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7879                            "Package " + pkg.packageName + " requires unavailable shared library "
7880                            + pkg.usesLibraries.get(i) + "; failing!");
7881                }
7882                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7883            }
7884            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7885            for (int i=0; i<N; i++) {
7886                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7887                if (file == null) {
7888                    Slog.w(TAG, "Package " + pkg.packageName
7889                            + " desires unavailable shared library "
7890                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7891                } else {
7892                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7893                }
7894            }
7895            N = usesLibraryFiles.size();
7896            if (N > 0) {
7897                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7898            } else {
7899                pkg.usesLibraryFiles = null;
7900            }
7901        }
7902    }
7903
7904    private static boolean hasString(List<String> list, List<String> which) {
7905        if (list == null) {
7906            return false;
7907        }
7908        for (int i=list.size()-1; i>=0; i--) {
7909            for (int j=which.size()-1; j>=0; j--) {
7910                if (which.get(j).equals(list.get(i))) {
7911                    return true;
7912                }
7913            }
7914        }
7915        return false;
7916    }
7917
7918    private void updateAllSharedLibrariesLPw() {
7919        for (PackageParser.Package pkg : mPackages.values()) {
7920            try {
7921                updateSharedLibrariesLPw(pkg, null);
7922            } catch (PackageManagerException e) {
7923                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7924            }
7925        }
7926    }
7927
7928    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7929            PackageParser.Package changingPkg) {
7930        ArrayList<PackageParser.Package> res = null;
7931        for (PackageParser.Package pkg : mPackages.values()) {
7932            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7933                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7934                if (res == null) {
7935                    res = new ArrayList<PackageParser.Package>();
7936                }
7937                res.add(pkg);
7938                try {
7939                    updateSharedLibrariesLPw(pkg, changingPkg);
7940                } catch (PackageManagerException e) {
7941                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7942                }
7943            }
7944        }
7945        return res;
7946    }
7947
7948    /**
7949     * Derive the value of the {@code cpuAbiOverride} based on the provided
7950     * value and an optional stored value from the package settings.
7951     */
7952    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7953        String cpuAbiOverride = null;
7954
7955        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7956            cpuAbiOverride = null;
7957        } else if (abiOverride != null) {
7958            cpuAbiOverride = abiOverride;
7959        } else if (settings != null) {
7960            cpuAbiOverride = settings.cpuAbiOverrideString;
7961        }
7962
7963        return cpuAbiOverride;
7964    }
7965
7966    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7967            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7968                    throws PackageManagerException {
7969        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7970        // If the package has children and this is the first dive in the function
7971        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7972        // whether all packages (parent and children) would be successfully scanned
7973        // before the actual scan since scanning mutates internal state and we want
7974        // to atomically install the package and its children.
7975        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7976            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7977                scanFlags |= SCAN_CHECK_ONLY;
7978            }
7979        } else {
7980            scanFlags &= ~SCAN_CHECK_ONLY;
7981        }
7982
7983        final PackageParser.Package scannedPkg;
7984        try {
7985            // Scan the parent
7986            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7987            // Scan the children
7988            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7989            for (int i = 0; i < childCount; i++) {
7990                PackageParser.Package childPkg = pkg.childPackages.get(i);
7991                scanPackageLI(childPkg, policyFlags,
7992                        scanFlags, currentTime, user);
7993            }
7994        } finally {
7995            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7996        }
7997
7998        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7999            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8000        }
8001
8002        return scannedPkg;
8003    }
8004
8005    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8006            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8007        boolean success = false;
8008        try {
8009            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8010                    currentTime, user);
8011            success = true;
8012            return res;
8013        } finally {
8014            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8015                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8016                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8017                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8018                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8019            }
8020        }
8021    }
8022
8023    /**
8024     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8025     */
8026    private static boolean apkHasCode(String fileName) {
8027        StrictJarFile jarFile = null;
8028        try {
8029            jarFile = new StrictJarFile(fileName,
8030                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8031            return jarFile.findEntry("classes.dex") != null;
8032        } catch (IOException ignore) {
8033        } finally {
8034            try {
8035                if (jarFile != null) {
8036                    jarFile.close();
8037                }
8038            } catch (IOException ignore) {}
8039        }
8040        return false;
8041    }
8042
8043    /**
8044     * Enforces code policy for the package. This ensures that if an APK has
8045     * declared hasCode="true" in its manifest that the APK actually contains
8046     * code.
8047     *
8048     * @throws PackageManagerException If bytecode could not be found when it should exist
8049     */
8050    private static void enforceCodePolicy(PackageParser.Package pkg)
8051            throws PackageManagerException {
8052        final boolean shouldHaveCode =
8053                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8054        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8055            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8056                    "Package " + pkg.baseCodePath + " code is missing");
8057        }
8058
8059        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8060            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8061                final boolean splitShouldHaveCode =
8062                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8063                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8064                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8065                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8066                }
8067            }
8068        }
8069    }
8070
8071    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8072            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8073            throws PackageManagerException {
8074        final File scanFile = new File(pkg.codePath);
8075        if (pkg.applicationInfo.getCodePath() == null ||
8076                pkg.applicationInfo.getResourcePath() == null) {
8077            // Bail out. The resource and code paths haven't been set.
8078            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8079                    "Code and resource paths haven't been set correctly");
8080        }
8081
8082        // Apply policy
8083        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8084            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8085            if (pkg.applicationInfo.isDirectBootAware()) {
8086                // we're direct boot aware; set for all components
8087                for (PackageParser.Service s : pkg.services) {
8088                    s.info.encryptionAware = s.info.directBootAware = true;
8089                }
8090                for (PackageParser.Provider p : pkg.providers) {
8091                    p.info.encryptionAware = p.info.directBootAware = true;
8092                }
8093                for (PackageParser.Activity a : pkg.activities) {
8094                    a.info.encryptionAware = a.info.directBootAware = true;
8095                }
8096                for (PackageParser.Activity r : pkg.receivers) {
8097                    r.info.encryptionAware = r.info.directBootAware = true;
8098                }
8099            }
8100        } else {
8101            // Only allow system apps to be flagged as core apps.
8102            pkg.coreApp = false;
8103            // clear flags not applicable to regular apps
8104            pkg.applicationInfo.privateFlags &=
8105                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8106            pkg.applicationInfo.privateFlags &=
8107                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8108        }
8109        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8110
8111        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8112            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8113        }
8114
8115        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8116            enforceCodePolicy(pkg);
8117        }
8118
8119        if (mCustomResolverComponentName != null &&
8120                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8121            setUpCustomResolverActivity(pkg);
8122        }
8123
8124        if (pkg.packageName.equals("android")) {
8125            synchronized (mPackages) {
8126                if (mAndroidApplication != null) {
8127                    Slog.w(TAG, "*************************************************");
8128                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8129                    Slog.w(TAG, " file=" + scanFile);
8130                    Slog.w(TAG, "*************************************************");
8131                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8132                            "Core android package being redefined.  Skipping.");
8133                }
8134
8135                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8136                    // Set up information for our fall-back user intent resolution activity.
8137                    mPlatformPackage = pkg;
8138                    pkg.mVersionCode = mSdkVersion;
8139                    mAndroidApplication = pkg.applicationInfo;
8140
8141                    if (!mResolverReplaced) {
8142                        mResolveActivity.applicationInfo = mAndroidApplication;
8143                        mResolveActivity.name = ResolverActivity.class.getName();
8144                        mResolveActivity.packageName = mAndroidApplication.packageName;
8145                        mResolveActivity.processName = "system:ui";
8146                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8147                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8148                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8149                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8150                        mResolveActivity.exported = true;
8151                        mResolveActivity.enabled = true;
8152                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8153                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8154                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8155                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8156                                | ActivityInfo.CONFIG_ORIENTATION
8157                                | ActivityInfo.CONFIG_KEYBOARD
8158                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8159                        mResolveInfo.activityInfo = mResolveActivity;
8160                        mResolveInfo.priority = 0;
8161                        mResolveInfo.preferredOrder = 0;
8162                        mResolveInfo.match = 0;
8163                        mResolveComponentName = new ComponentName(
8164                                mAndroidApplication.packageName, mResolveActivity.name);
8165                    }
8166                }
8167            }
8168        }
8169
8170        if (DEBUG_PACKAGE_SCANNING) {
8171            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8172                Log.d(TAG, "Scanning package " + pkg.packageName);
8173        }
8174
8175        synchronized (mPackages) {
8176            if (mPackages.containsKey(pkg.packageName)
8177                    || mSharedLibraries.containsKey(pkg.packageName)) {
8178                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8179                        "Application package " + pkg.packageName
8180                                + " already installed.  Skipping duplicate.");
8181            }
8182
8183            // If we're only installing presumed-existing packages, require that the
8184            // scanned APK is both already known and at the path previously established
8185            // for it.  Previously unknown packages we pick up normally, but if we have an
8186            // a priori expectation about this package's install presence, enforce it.
8187            // With a singular exception for new system packages. When an OTA contains
8188            // a new system package, we allow the codepath to change from a system location
8189            // to the user-installed location. If we don't allow this change, any newer,
8190            // user-installed version of the application will be ignored.
8191            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8192                if (mExpectingBetter.containsKey(pkg.packageName)) {
8193                    logCriticalInfo(Log.WARN,
8194                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8195                } else {
8196                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8197                    if (known != null) {
8198                        if (DEBUG_PACKAGE_SCANNING) {
8199                            Log.d(TAG, "Examining " + pkg.codePath
8200                                    + " and requiring known paths " + known.codePathString
8201                                    + " & " + known.resourcePathString);
8202                        }
8203                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8204                                || !pkg.applicationInfo.getResourcePath().equals(
8205                                known.resourcePathString)) {
8206                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8207                                    "Application package " + pkg.packageName
8208                                            + " found at " + pkg.applicationInfo.getCodePath()
8209                                            + " but expected at " + known.codePathString
8210                                            + "; ignoring.");
8211                        }
8212                    }
8213                }
8214            }
8215        }
8216
8217        // Initialize package source and resource directories
8218        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8219        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8220
8221        SharedUserSetting suid = null;
8222        PackageSetting pkgSetting = null;
8223
8224        if (!isSystemApp(pkg)) {
8225            // Only system apps can use these features.
8226            pkg.mOriginalPackages = null;
8227            pkg.mRealPackage = null;
8228            pkg.mAdoptPermissions = null;
8229        }
8230
8231        // Getting the package setting may have a side-effect, so if we
8232        // are only checking if scan would succeed, stash a copy of the
8233        // old setting to restore at the end.
8234        PackageSetting nonMutatedPs = null;
8235
8236        // writer
8237        synchronized (mPackages) {
8238            if (pkg.mSharedUserId != null) {
8239                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8240                if (suid == null) {
8241                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8242                            "Creating application package " + pkg.packageName
8243                            + " for shared user failed");
8244                }
8245                if (DEBUG_PACKAGE_SCANNING) {
8246                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8247                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8248                                + "): packages=" + suid.packages);
8249                }
8250            }
8251
8252            // Check if we are renaming from an original package name.
8253            PackageSetting origPackage = null;
8254            String realName = null;
8255            if (pkg.mOriginalPackages != null) {
8256                // This package may need to be renamed to a previously
8257                // installed name.  Let's check on that...
8258                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8259                if (pkg.mOriginalPackages.contains(renamed)) {
8260                    // This package had originally been installed as the
8261                    // original name, and we have already taken care of
8262                    // transitioning to the new one.  Just update the new
8263                    // one to continue using the old name.
8264                    realName = pkg.mRealPackage;
8265                    if (!pkg.packageName.equals(renamed)) {
8266                        // Callers into this function may have already taken
8267                        // care of renaming the package; only do it here if
8268                        // it is not already done.
8269                        pkg.setPackageName(renamed);
8270                    }
8271
8272                } else {
8273                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8274                        if ((origPackage = mSettings.peekPackageLPr(
8275                                pkg.mOriginalPackages.get(i))) != null) {
8276                            // We do have the package already installed under its
8277                            // original name...  should we use it?
8278                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8279                                // New package is not compatible with original.
8280                                origPackage = null;
8281                                continue;
8282                            } else if (origPackage.sharedUser != null) {
8283                                // Make sure uid is compatible between packages.
8284                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8285                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8286                                            + " to " + pkg.packageName + ": old uid "
8287                                            + origPackage.sharedUser.name
8288                                            + " differs from " + pkg.mSharedUserId);
8289                                    origPackage = null;
8290                                    continue;
8291                                }
8292                                // TODO: Add case when shared user id is added [b/28144775]
8293                            } else {
8294                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8295                                        + pkg.packageName + " to old name " + origPackage.name);
8296                            }
8297                            break;
8298                        }
8299                    }
8300                }
8301            }
8302
8303            if (mTransferedPackages.contains(pkg.packageName)) {
8304                Slog.w(TAG, "Package " + pkg.packageName
8305                        + " was transferred to another, but its .apk remains");
8306            }
8307
8308            // See comments in nonMutatedPs declaration
8309            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8310                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8311                if (foundPs != null) {
8312                    nonMutatedPs = new PackageSetting(foundPs);
8313                }
8314            }
8315
8316            // Just create the setting, don't add it yet. For already existing packages
8317            // the PkgSetting exists already and doesn't have to be created.
8318            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8319                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8320                    pkg.applicationInfo.primaryCpuAbi,
8321                    pkg.applicationInfo.secondaryCpuAbi,
8322                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8323                    user, false);
8324            if (pkgSetting == null) {
8325                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8326                        "Creating application package " + pkg.packageName + " failed");
8327            }
8328
8329            if (pkgSetting.origPackage != null) {
8330                // If we are first transitioning from an original package,
8331                // fix up the new package's name now.  We need to do this after
8332                // looking up the package under its new name, so getPackageLP
8333                // can take care of fiddling things correctly.
8334                pkg.setPackageName(origPackage.name);
8335
8336                // File a report about this.
8337                String msg = "New package " + pkgSetting.realName
8338                        + " renamed to replace old package " + pkgSetting.name;
8339                reportSettingsProblem(Log.WARN, msg);
8340
8341                // Make a note of it.
8342                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8343                    mTransferedPackages.add(origPackage.name);
8344                }
8345
8346                // No longer need to retain this.
8347                pkgSetting.origPackage = null;
8348            }
8349
8350            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8351                // Make a note of it.
8352                mTransferedPackages.add(pkg.packageName);
8353            }
8354
8355            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8356                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8357            }
8358
8359            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8360                // Check all shared libraries and map to their actual file path.
8361                // We only do this here for apps not on a system dir, because those
8362                // are the only ones that can fail an install due to this.  We
8363                // will take care of the system apps by updating all of their
8364                // library paths after the scan is done.
8365                updateSharedLibrariesLPw(pkg, null);
8366            }
8367
8368            if (mFoundPolicyFile) {
8369                SELinuxMMAC.assignSeinfoValue(pkg);
8370            }
8371
8372            pkg.applicationInfo.uid = pkgSetting.appId;
8373            pkg.mExtras = pkgSetting;
8374            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8375                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8376                    // We just determined the app is signed correctly, so bring
8377                    // over the latest parsed certs.
8378                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8379                } else {
8380                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8381                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8382                                "Package " + pkg.packageName + " upgrade keys do not match the "
8383                                + "previously installed version");
8384                    } else {
8385                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8386                        String msg = "System package " + pkg.packageName
8387                            + " signature changed; retaining data.";
8388                        reportSettingsProblem(Log.WARN, msg);
8389                    }
8390                }
8391            } else {
8392                try {
8393                    verifySignaturesLP(pkgSetting, pkg);
8394                    // We just determined the app is signed correctly, so bring
8395                    // over the latest parsed certs.
8396                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8397                } catch (PackageManagerException e) {
8398                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8399                        throw e;
8400                    }
8401                    // The signature has changed, but this package is in the system
8402                    // image...  let's recover!
8403                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8404                    // However...  if this package is part of a shared user, but it
8405                    // doesn't match the signature of the shared user, let's fail.
8406                    // What this means is that you can't change the signatures
8407                    // associated with an overall shared user, which doesn't seem all
8408                    // that unreasonable.
8409                    if (pkgSetting.sharedUser != null) {
8410                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8411                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8412                            throw new PackageManagerException(
8413                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8414                                            "Signature mismatch for shared user: "
8415                                            + pkgSetting.sharedUser);
8416                        }
8417                    }
8418                    // File a report about this.
8419                    String msg = "System package " + pkg.packageName
8420                        + " signature changed; retaining data.";
8421                    reportSettingsProblem(Log.WARN, msg);
8422                }
8423            }
8424            // Verify that this new package doesn't have any content providers
8425            // that conflict with existing packages.  Only do this if the
8426            // package isn't already installed, since we don't want to break
8427            // things that are installed.
8428            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8429                final int N = pkg.providers.size();
8430                int i;
8431                for (i=0; i<N; i++) {
8432                    PackageParser.Provider p = pkg.providers.get(i);
8433                    if (p.info.authority != null) {
8434                        String names[] = p.info.authority.split(";");
8435                        for (int j = 0; j < names.length; j++) {
8436                            if (mProvidersByAuthority.containsKey(names[j])) {
8437                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8438                                final String otherPackageName =
8439                                        ((other != null && other.getComponentName() != null) ?
8440                                                other.getComponentName().getPackageName() : "?");
8441                                throw new PackageManagerException(
8442                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8443                                                "Can't install because provider name " + names[j]
8444                                                + " (in package " + pkg.applicationInfo.packageName
8445                                                + ") is already used by " + otherPackageName);
8446                            }
8447                        }
8448                    }
8449                }
8450            }
8451
8452            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8453                // This package wants to adopt ownership of permissions from
8454                // another package.
8455                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8456                    final String origName = pkg.mAdoptPermissions.get(i);
8457                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8458                    if (orig != null) {
8459                        if (verifyPackageUpdateLPr(orig, pkg)) {
8460                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8461                                    + pkg.packageName);
8462                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8463                        }
8464                    }
8465                }
8466            }
8467        }
8468
8469        final String pkgName = pkg.packageName;
8470
8471        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8472        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8473        pkg.applicationInfo.processName = fixProcessName(
8474                pkg.applicationInfo.packageName,
8475                pkg.applicationInfo.processName,
8476                pkg.applicationInfo.uid);
8477
8478        if (pkg != mPlatformPackage) {
8479            // Get all of our default paths setup
8480            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8481        }
8482
8483        final String path = scanFile.getPath();
8484        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8485
8486        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8487            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8488
8489            // Some system apps still use directory structure for native libraries
8490            // in which case we might end up not detecting abi solely based on apk
8491            // structure. Try to detect abi based on directory structure.
8492            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8493                    pkg.applicationInfo.primaryCpuAbi == null) {
8494                setBundledAppAbisAndRoots(pkg, pkgSetting);
8495                setNativeLibraryPaths(pkg);
8496            }
8497
8498        } else {
8499            if ((scanFlags & SCAN_MOVE) != 0) {
8500                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8501                // but we already have this packages package info in the PackageSetting. We just
8502                // use that and derive the native library path based on the new codepath.
8503                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8504                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8505            }
8506
8507            // Set native library paths again. For moves, the path will be updated based on the
8508            // ABIs we've determined above. For non-moves, the path will be updated based on the
8509            // ABIs we determined during compilation, but the path will depend on the final
8510            // package path (after the rename away from the stage path).
8511            setNativeLibraryPaths(pkg);
8512        }
8513
8514        // This is a special case for the "system" package, where the ABI is
8515        // dictated by the zygote configuration (and init.rc). We should keep track
8516        // of this ABI so that we can deal with "normal" applications that run under
8517        // the same UID correctly.
8518        if (mPlatformPackage == pkg) {
8519            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8520                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8521        }
8522
8523        // If there's a mismatch between the abi-override in the package setting
8524        // and the abiOverride specified for the install. Warn about this because we
8525        // would've already compiled the app without taking the package setting into
8526        // account.
8527        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8528            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8529                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8530                        " for package " + pkg.packageName);
8531            }
8532        }
8533
8534        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8535        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8536        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8537
8538        // Copy the derived override back to the parsed package, so that we can
8539        // update the package settings accordingly.
8540        pkg.cpuAbiOverride = cpuAbiOverride;
8541
8542        if (DEBUG_ABI_SELECTION) {
8543            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8544                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8545                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8546        }
8547
8548        // Push the derived path down into PackageSettings so we know what to
8549        // clean up at uninstall time.
8550        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8551
8552        if (DEBUG_ABI_SELECTION) {
8553            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8554                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8555                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8556        }
8557
8558        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8559            // We don't do this here during boot because we can do it all
8560            // at once after scanning all existing packages.
8561            //
8562            // We also do this *before* we perform dexopt on this package, so that
8563            // we can avoid redundant dexopts, and also to make sure we've got the
8564            // code and package path correct.
8565            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8566                    pkg, true /* boot complete */);
8567        }
8568
8569        if (mFactoryTest && pkg.requestedPermissions.contains(
8570                android.Manifest.permission.FACTORY_TEST)) {
8571            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8572        }
8573
8574        ArrayList<PackageParser.Package> clientLibPkgs = null;
8575
8576        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8577            if (nonMutatedPs != null) {
8578                synchronized (mPackages) {
8579                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8580                }
8581            }
8582            return pkg;
8583        }
8584
8585        // Only privileged apps and updated privileged apps can add child packages.
8586        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8587            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8588                throw new PackageManagerException("Only privileged apps and updated "
8589                        + "privileged apps can add child packages. Ignoring package "
8590                        + pkg.packageName);
8591            }
8592            final int childCount = pkg.childPackages.size();
8593            for (int i = 0; i < childCount; i++) {
8594                PackageParser.Package childPkg = pkg.childPackages.get(i);
8595                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8596                        childPkg.packageName)) {
8597                    throw new PackageManagerException("Cannot override a child package of "
8598                            + "another disabled system app. Ignoring package " + pkg.packageName);
8599                }
8600            }
8601        }
8602
8603        // writer
8604        synchronized (mPackages) {
8605            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8606                // Only system apps can add new shared libraries.
8607                if (pkg.libraryNames != null) {
8608                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8609                        String name = pkg.libraryNames.get(i);
8610                        boolean allowed = false;
8611                        if (pkg.isUpdatedSystemApp()) {
8612                            // New library entries can only be added through the
8613                            // system image.  This is important to get rid of a lot
8614                            // of nasty edge cases: for example if we allowed a non-
8615                            // system update of the app to add a library, then uninstalling
8616                            // the update would make the library go away, and assumptions
8617                            // we made such as through app install filtering would now
8618                            // have allowed apps on the device which aren't compatible
8619                            // with it.  Better to just have the restriction here, be
8620                            // conservative, and create many fewer cases that can negatively
8621                            // impact the user experience.
8622                            final PackageSetting sysPs = mSettings
8623                                    .getDisabledSystemPkgLPr(pkg.packageName);
8624                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8625                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8626                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8627                                        allowed = true;
8628                                        break;
8629                                    }
8630                                }
8631                            }
8632                        } else {
8633                            allowed = true;
8634                        }
8635                        if (allowed) {
8636                            if (!mSharedLibraries.containsKey(name)) {
8637                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8638                            } else if (!name.equals(pkg.packageName)) {
8639                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8640                                        + name + " already exists; skipping");
8641                            }
8642                        } else {
8643                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8644                                    + name + " that is not declared on system image; skipping");
8645                        }
8646                    }
8647                    if ((scanFlags & SCAN_BOOTING) == 0) {
8648                        // If we are not booting, we need to update any applications
8649                        // that are clients of our shared library.  If we are booting,
8650                        // this will all be done once the scan is complete.
8651                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8652                    }
8653                }
8654            }
8655        }
8656
8657        if ((scanFlags & SCAN_BOOTING) != 0) {
8658            // No apps can run during boot scan, so they don't need to be frozen
8659        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8660            // Caller asked to not kill app, so it's probably not frozen
8661        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8662            // Caller asked us to ignore frozen check for some reason; they
8663            // probably didn't know the package name
8664        } else {
8665            // We're doing major surgery on this package, so it better be frozen
8666            // right now to keep it from launching
8667            checkPackageFrozen(pkgName);
8668        }
8669
8670        // Also need to kill any apps that are dependent on the library.
8671        if (clientLibPkgs != null) {
8672            for (int i=0; i<clientLibPkgs.size(); i++) {
8673                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8674                killApplication(clientPkg.applicationInfo.packageName,
8675                        clientPkg.applicationInfo.uid, "update lib");
8676            }
8677        }
8678
8679        // Make sure we're not adding any bogus keyset info
8680        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8681        ksms.assertScannedPackageValid(pkg);
8682
8683        // writer
8684        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8685
8686        boolean createIdmapFailed = false;
8687        synchronized (mPackages) {
8688            // We don't expect installation to fail beyond this point
8689
8690            if (pkgSetting.pkg != null) {
8691                // Note that |user| might be null during the initial boot scan. If a codePath
8692                // for an app has changed during a boot scan, it's due to an app update that's
8693                // part of the system partition and marker changes must be applied to all users.
8694                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8695                    (user != null) ? user : UserHandle.ALL);
8696            }
8697
8698            // Add the new setting to mSettings
8699            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8700            // Add the new setting to mPackages
8701            mPackages.put(pkg.applicationInfo.packageName, pkg);
8702            // Make sure we don't accidentally delete its data.
8703            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8704            while (iter.hasNext()) {
8705                PackageCleanItem item = iter.next();
8706                if (pkgName.equals(item.packageName)) {
8707                    iter.remove();
8708                }
8709            }
8710
8711            // Take care of first install / last update times.
8712            if (currentTime != 0) {
8713                if (pkgSetting.firstInstallTime == 0) {
8714                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8715                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8716                    pkgSetting.lastUpdateTime = currentTime;
8717                }
8718            } else if (pkgSetting.firstInstallTime == 0) {
8719                // We need *something*.  Take time time stamp of the file.
8720                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8721            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8722                if (scanFileTime != pkgSetting.timeStamp) {
8723                    // A package on the system image has changed; consider this
8724                    // to be an update.
8725                    pkgSetting.lastUpdateTime = scanFileTime;
8726                }
8727            }
8728
8729            // Add the package's KeySets to the global KeySetManagerService
8730            ksms.addScannedPackageLPw(pkg);
8731
8732            int N = pkg.providers.size();
8733            StringBuilder r = null;
8734            int i;
8735            for (i=0; i<N; i++) {
8736                PackageParser.Provider p = pkg.providers.get(i);
8737                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8738                        p.info.processName, pkg.applicationInfo.uid);
8739                mProviders.addProvider(p);
8740                p.syncable = p.info.isSyncable;
8741                if (p.info.authority != null) {
8742                    String names[] = p.info.authority.split(";");
8743                    p.info.authority = null;
8744                    for (int j = 0; j < names.length; j++) {
8745                        if (j == 1 && p.syncable) {
8746                            // We only want the first authority for a provider to possibly be
8747                            // syncable, so if we already added this provider using a different
8748                            // authority clear the syncable flag. We copy the provider before
8749                            // changing it because the mProviders object contains a reference
8750                            // to a provider that we don't want to change.
8751                            // Only do this for the second authority since the resulting provider
8752                            // object can be the same for all future authorities for this provider.
8753                            p = new PackageParser.Provider(p);
8754                            p.syncable = false;
8755                        }
8756                        if (!mProvidersByAuthority.containsKey(names[j])) {
8757                            mProvidersByAuthority.put(names[j], p);
8758                            if (p.info.authority == null) {
8759                                p.info.authority = names[j];
8760                            } else {
8761                                p.info.authority = p.info.authority + ";" + names[j];
8762                            }
8763                            if (DEBUG_PACKAGE_SCANNING) {
8764                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8765                                    Log.d(TAG, "Registered content provider: " + names[j]
8766                                            + ", className = " + p.info.name + ", isSyncable = "
8767                                            + p.info.isSyncable);
8768                            }
8769                        } else {
8770                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8771                            Slog.w(TAG, "Skipping provider name " + names[j] +
8772                                    " (in package " + pkg.applicationInfo.packageName +
8773                                    "): name already used by "
8774                                    + ((other != null && other.getComponentName() != null)
8775                                            ? other.getComponentName().getPackageName() : "?"));
8776                        }
8777                    }
8778                }
8779                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8780                    if (r == null) {
8781                        r = new StringBuilder(256);
8782                    } else {
8783                        r.append(' ');
8784                    }
8785                    r.append(p.info.name);
8786                }
8787            }
8788            if (r != null) {
8789                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8790            }
8791
8792            N = pkg.services.size();
8793            r = null;
8794            for (i=0; i<N; i++) {
8795                PackageParser.Service s = pkg.services.get(i);
8796                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8797                        s.info.processName, pkg.applicationInfo.uid);
8798                mServices.addService(s);
8799                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8800                    if (r == null) {
8801                        r = new StringBuilder(256);
8802                    } else {
8803                        r.append(' ');
8804                    }
8805                    r.append(s.info.name);
8806                }
8807            }
8808            if (r != null) {
8809                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8810            }
8811
8812            N = pkg.receivers.size();
8813            r = null;
8814            for (i=0; i<N; i++) {
8815                PackageParser.Activity a = pkg.receivers.get(i);
8816                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8817                        a.info.processName, pkg.applicationInfo.uid);
8818                mReceivers.addActivity(a, "receiver");
8819                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8820                    if (r == null) {
8821                        r = new StringBuilder(256);
8822                    } else {
8823                        r.append(' ');
8824                    }
8825                    r.append(a.info.name);
8826                }
8827            }
8828            if (r != null) {
8829                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8830            }
8831
8832            N = pkg.activities.size();
8833            r = null;
8834            for (i=0; i<N; i++) {
8835                PackageParser.Activity a = pkg.activities.get(i);
8836                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8837                        a.info.processName, pkg.applicationInfo.uid);
8838                mActivities.addActivity(a, "activity");
8839                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8840                    if (r == null) {
8841                        r = new StringBuilder(256);
8842                    } else {
8843                        r.append(' ');
8844                    }
8845                    r.append(a.info.name);
8846                }
8847            }
8848            if (r != null) {
8849                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8850            }
8851
8852            N = pkg.permissionGroups.size();
8853            r = null;
8854            for (i=0; i<N; i++) {
8855                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8856                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8857                if (cur == null) {
8858                    mPermissionGroups.put(pg.info.name, pg);
8859                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8860                        if (r == null) {
8861                            r = new StringBuilder(256);
8862                        } else {
8863                            r.append(' ');
8864                        }
8865                        r.append(pg.info.name);
8866                    }
8867                } else {
8868                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8869                            + pg.info.packageName + " ignored: original from "
8870                            + cur.info.packageName);
8871                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8872                        if (r == null) {
8873                            r = new StringBuilder(256);
8874                        } else {
8875                            r.append(' ');
8876                        }
8877                        r.append("DUP:");
8878                        r.append(pg.info.name);
8879                    }
8880                }
8881            }
8882            if (r != null) {
8883                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8884            }
8885
8886            N = pkg.permissions.size();
8887            r = null;
8888            for (i=0; i<N; i++) {
8889                PackageParser.Permission p = pkg.permissions.get(i);
8890
8891                // Assume by default that we did not install this permission into the system.
8892                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8893
8894                // Now that permission groups have a special meaning, we ignore permission
8895                // groups for legacy apps to prevent unexpected behavior. In particular,
8896                // permissions for one app being granted to someone just becase they happen
8897                // to be in a group defined by another app (before this had no implications).
8898                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8899                    p.group = mPermissionGroups.get(p.info.group);
8900                    // Warn for a permission in an unknown group.
8901                    if (p.info.group != null && p.group == null) {
8902                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8903                                + p.info.packageName + " in an unknown group " + p.info.group);
8904                    }
8905                }
8906
8907                ArrayMap<String, BasePermission> permissionMap =
8908                        p.tree ? mSettings.mPermissionTrees
8909                                : mSettings.mPermissions;
8910                BasePermission bp = permissionMap.get(p.info.name);
8911
8912                // Allow system apps to redefine non-system permissions
8913                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8914                    final boolean currentOwnerIsSystem = (bp.perm != null
8915                            && isSystemApp(bp.perm.owner));
8916                    if (isSystemApp(p.owner)) {
8917                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8918                            // It's a built-in permission and no owner, take ownership now
8919                            bp.packageSetting = pkgSetting;
8920                            bp.perm = p;
8921                            bp.uid = pkg.applicationInfo.uid;
8922                            bp.sourcePackage = p.info.packageName;
8923                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8924                        } else if (!currentOwnerIsSystem) {
8925                            String msg = "New decl " + p.owner + " of permission  "
8926                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8927                            reportSettingsProblem(Log.WARN, msg);
8928                            bp = null;
8929                        }
8930                    }
8931                }
8932
8933                if (bp == null) {
8934                    bp = new BasePermission(p.info.name, p.info.packageName,
8935                            BasePermission.TYPE_NORMAL);
8936                    permissionMap.put(p.info.name, bp);
8937                }
8938
8939                if (bp.perm == null) {
8940                    if (bp.sourcePackage == null
8941                            || bp.sourcePackage.equals(p.info.packageName)) {
8942                        BasePermission tree = findPermissionTreeLP(p.info.name);
8943                        if (tree == null
8944                                || tree.sourcePackage.equals(p.info.packageName)) {
8945                            bp.packageSetting = pkgSetting;
8946                            bp.perm = p;
8947                            bp.uid = pkg.applicationInfo.uid;
8948                            bp.sourcePackage = p.info.packageName;
8949                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8950                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8951                                if (r == null) {
8952                                    r = new StringBuilder(256);
8953                                } else {
8954                                    r.append(' ');
8955                                }
8956                                r.append(p.info.name);
8957                            }
8958                        } else {
8959                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8960                                    + p.info.packageName + " ignored: base tree "
8961                                    + tree.name + " is from package "
8962                                    + tree.sourcePackage);
8963                        }
8964                    } else {
8965                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8966                                + p.info.packageName + " ignored: original from "
8967                                + bp.sourcePackage);
8968                    }
8969                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8970                    if (r == null) {
8971                        r = new StringBuilder(256);
8972                    } else {
8973                        r.append(' ');
8974                    }
8975                    r.append("DUP:");
8976                    r.append(p.info.name);
8977                }
8978                if (bp.perm == p) {
8979                    bp.protectionLevel = p.info.protectionLevel;
8980                }
8981            }
8982
8983            if (r != null) {
8984                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8985            }
8986
8987            N = pkg.instrumentation.size();
8988            r = null;
8989            for (i=0; i<N; i++) {
8990                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8991                a.info.packageName = pkg.applicationInfo.packageName;
8992                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8993                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8994                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8995                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8996                a.info.dataDir = pkg.applicationInfo.dataDir;
8997                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8998                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8999
9000                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9001                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9002                mInstrumentation.put(a.getComponentName(), a);
9003                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9004                    if (r == null) {
9005                        r = new StringBuilder(256);
9006                    } else {
9007                        r.append(' ');
9008                    }
9009                    r.append(a.info.name);
9010                }
9011            }
9012            if (r != null) {
9013                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9014            }
9015
9016            if (pkg.protectedBroadcasts != null) {
9017                N = pkg.protectedBroadcasts.size();
9018                for (i=0; i<N; i++) {
9019                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9020                }
9021            }
9022
9023            pkgSetting.setTimeStamp(scanFileTime);
9024
9025            // Create idmap files for pairs of (packages, overlay packages).
9026            // Note: "android", ie framework-res.apk, is handled by native layers.
9027            if (pkg.mOverlayTarget != null) {
9028                // This is an overlay package.
9029                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9030                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9031                        mOverlays.put(pkg.mOverlayTarget,
9032                                new ArrayMap<String, PackageParser.Package>());
9033                    }
9034                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9035                    map.put(pkg.packageName, pkg);
9036                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9037                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9038                        createIdmapFailed = true;
9039                    }
9040                }
9041            } else if (mOverlays.containsKey(pkg.packageName) &&
9042                    !pkg.packageName.equals("android")) {
9043                // This is a regular package, with one or more known overlay packages.
9044                createIdmapsForPackageLI(pkg);
9045            }
9046        }
9047
9048        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9049
9050        if (createIdmapFailed) {
9051            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9052                    "scanPackageLI failed to createIdmap");
9053        }
9054        return pkg;
9055    }
9056
9057    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9058            PackageParser.Package update, UserHandle user) {
9059        if (existing.applicationInfo == null || update.applicationInfo == null) {
9060            // This isn't due to an app installation.
9061            return;
9062        }
9063
9064        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9065        final File newCodePath = new File(update.applicationInfo.getCodePath());
9066
9067        // The codePath hasn't changed, so there's nothing for us to do.
9068        if (Objects.equals(oldCodePath, newCodePath)) {
9069            return;
9070        }
9071
9072        File canonicalNewCodePath;
9073        try {
9074            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9075        } catch (IOException e) {
9076            Slog.w(TAG, "Failed to get canonical path.", e);
9077            return;
9078        }
9079
9080        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9081        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9082        // that the last component of the path (i.e, the name) doesn't need canonicalization
9083        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9084        // but may change in the future. Hopefully this function won't exist at that point.
9085        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9086                oldCodePath.getName());
9087
9088        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9089        // with "@".
9090        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9091        if (!oldMarkerPrefix.endsWith("@")) {
9092            oldMarkerPrefix += "@";
9093        }
9094        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9095        if (!newMarkerPrefix.endsWith("@")) {
9096            newMarkerPrefix += "@";
9097        }
9098
9099        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9100        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9101        for (String updatedPath : updatedPaths) {
9102            String updatedPathName = new File(updatedPath).getName();
9103            markerSuffixes.add(updatedPathName.replace('/', '@'));
9104        }
9105
9106        for (int userId : resolveUserIds(user.getIdentifier())) {
9107            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9108
9109            for (String markerSuffix : markerSuffixes) {
9110                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9111                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9112                if (oldForeignUseMark.exists()) {
9113                    try {
9114                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9115                                newForeignUseMark.getAbsolutePath());
9116                    } catch (ErrnoException e) {
9117                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9118                        oldForeignUseMark.delete();
9119                    }
9120                }
9121            }
9122        }
9123    }
9124
9125    /**
9126     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9127     * is derived purely on the basis of the contents of {@code scanFile} and
9128     * {@code cpuAbiOverride}.
9129     *
9130     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9131     */
9132    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9133                                 String cpuAbiOverride, boolean extractLibs)
9134            throws PackageManagerException {
9135        // TODO: We can probably be smarter about this stuff. For installed apps,
9136        // we can calculate this information at install time once and for all. For
9137        // system apps, we can probably assume that this information doesn't change
9138        // after the first boot scan. As things stand, we do lots of unnecessary work.
9139
9140        // Give ourselves some initial paths; we'll come back for another
9141        // pass once we've determined ABI below.
9142        setNativeLibraryPaths(pkg);
9143
9144        // We would never need to extract libs for forward-locked and external packages,
9145        // since the container service will do it for us. We shouldn't attempt to
9146        // extract libs from system app when it was not updated.
9147        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9148                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9149            extractLibs = false;
9150        }
9151
9152        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9153        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9154
9155        NativeLibraryHelper.Handle handle = null;
9156        try {
9157            handle = NativeLibraryHelper.Handle.create(pkg);
9158            // TODO(multiArch): This can be null for apps that didn't go through the
9159            // usual installation process. We can calculate it again, like we
9160            // do during install time.
9161            //
9162            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9163            // unnecessary.
9164            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9165
9166            // Null out the abis so that they can be recalculated.
9167            pkg.applicationInfo.primaryCpuAbi = null;
9168            pkg.applicationInfo.secondaryCpuAbi = null;
9169            if (isMultiArch(pkg.applicationInfo)) {
9170                // Warn if we've set an abiOverride for multi-lib packages..
9171                // By definition, we need to copy both 32 and 64 bit libraries for
9172                // such packages.
9173                if (pkg.cpuAbiOverride != null
9174                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9175                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9176                }
9177
9178                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9179                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9180                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9181                    if (extractLibs) {
9182                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9183                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9184                                useIsaSpecificSubdirs);
9185                    } else {
9186                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9187                    }
9188                }
9189
9190                maybeThrowExceptionForMultiArchCopy(
9191                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9192
9193                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9194                    if (extractLibs) {
9195                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9196                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9197                                useIsaSpecificSubdirs);
9198                    } else {
9199                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9200                    }
9201                }
9202
9203                maybeThrowExceptionForMultiArchCopy(
9204                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9205
9206                if (abi64 >= 0) {
9207                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9208                }
9209
9210                if (abi32 >= 0) {
9211                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9212                    if (abi64 >= 0) {
9213                        if (pkg.use32bitAbi) {
9214                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9215                            pkg.applicationInfo.primaryCpuAbi = abi;
9216                        } else {
9217                            pkg.applicationInfo.secondaryCpuAbi = abi;
9218                        }
9219                    } else {
9220                        pkg.applicationInfo.primaryCpuAbi = abi;
9221                    }
9222                }
9223
9224            } else {
9225                String[] abiList = (cpuAbiOverride != null) ?
9226                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9227
9228                // Enable gross and lame hacks for apps that are built with old
9229                // SDK tools. We must scan their APKs for renderscript bitcode and
9230                // not launch them if it's present. Don't bother checking on devices
9231                // that don't have 64 bit support.
9232                boolean needsRenderScriptOverride = false;
9233                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9234                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9235                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9236                    needsRenderScriptOverride = true;
9237                }
9238
9239                final int copyRet;
9240                if (extractLibs) {
9241                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9242                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9243                } else {
9244                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9245                }
9246
9247                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9248                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9249                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9250                }
9251
9252                if (copyRet >= 0) {
9253                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9254                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9255                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9256                } else if (needsRenderScriptOverride) {
9257                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9258                }
9259            }
9260        } catch (IOException ioe) {
9261            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9262        } finally {
9263            IoUtils.closeQuietly(handle);
9264        }
9265
9266        // Now that we've calculated the ABIs and determined if it's an internal app,
9267        // we will go ahead and populate the nativeLibraryPath.
9268        setNativeLibraryPaths(pkg);
9269    }
9270
9271    /**
9272     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9273     * i.e, so that all packages can be run inside a single process if required.
9274     *
9275     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9276     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9277     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9278     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9279     * updating a package that belongs to a shared user.
9280     *
9281     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9282     * adds unnecessary complexity.
9283     */
9284    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9285            PackageParser.Package scannedPackage, boolean bootComplete) {
9286        String requiredInstructionSet = null;
9287        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9288            requiredInstructionSet = VMRuntime.getInstructionSet(
9289                     scannedPackage.applicationInfo.primaryCpuAbi);
9290        }
9291
9292        PackageSetting requirer = null;
9293        for (PackageSetting ps : packagesForUser) {
9294            // If packagesForUser contains scannedPackage, we skip it. This will happen
9295            // when scannedPackage is an update of an existing package. Without this check,
9296            // we will never be able to change the ABI of any package belonging to a shared
9297            // user, even if it's compatible with other packages.
9298            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9299                if (ps.primaryCpuAbiString == null) {
9300                    continue;
9301                }
9302
9303                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9304                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9305                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9306                    // this but there's not much we can do.
9307                    String errorMessage = "Instruction set mismatch, "
9308                            + ((requirer == null) ? "[caller]" : requirer)
9309                            + " requires " + requiredInstructionSet + " whereas " + ps
9310                            + " requires " + instructionSet;
9311                    Slog.w(TAG, errorMessage);
9312                }
9313
9314                if (requiredInstructionSet == null) {
9315                    requiredInstructionSet = instructionSet;
9316                    requirer = ps;
9317                }
9318            }
9319        }
9320
9321        if (requiredInstructionSet != null) {
9322            String adjustedAbi;
9323            if (requirer != null) {
9324                // requirer != null implies that either scannedPackage was null or that scannedPackage
9325                // did not require an ABI, in which case we have to adjust scannedPackage to match
9326                // the ABI of the set (which is the same as requirer's ABI)
9327                adjustedAbi = requirer.primaryCpuAbiString;
9328                if (scannedPackage != null) {
9329                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9330                }
9331            } else {
9332                // requirer == null implies that we're updating all ABIs in the set to
9333                // match scannedPackage.
9334                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9335            }
9336
9337            for (PackageSetting ps : packagesForUser) {
9338                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9339                    if (ps.primaryCpuAbiString != null) {
9340                        continue;
9341                    }
9342
9343                    ps.primaryCpuAbiString = adjustedAbi;
9344                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9345                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9346                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9347                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9348                                + " (requirer="
9349                                + (requirer == null ? "null" : requirer.pkg.packageName)
9350                                + ", scannedPackage="
9351                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9352                                + ")");
9353                        try {
9354                            mInstaller.rmdex(ps.codePathString,
9355                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9356                        } catch (InstallerException ignored) {
9357                        }
9358                    }
9359                }
9360            }
9361        }
9362    }
9363
9364    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9365        synchronized (mPackages) {
9366            mResolverReplaced = true;
9367            // Set up information for custom user intent resolution activity.
9368            mResolveActivity.applicationInfo = pkg.applicationInfo;
9369            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9370            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9371            mResolveActivity.processName = pkg.applicationInfo.packageName;
9372            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9373            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9374                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9375            mResolveActivity.theme = 0;
9376            mResolveActivity.exported = true;
9377            mResolveActivity.enabled = true;
9378            mResolveInfo.activityInfo = mResolveActivity;
9379            mResolveInfo.priority = 0;
9380            mResolveInfo.preferredOrder = 0;
9381            mResolveInfo.match = 0;
9382            mResolveComponentName = mCustomResolverComponentName;
9383            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9384                    mResolveComponentName);
9385        }
9386    }
9387
9388    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9389        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9390
9391        // Set up information for ephemeral installer activity
9392        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9393        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9394        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9395        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9396        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9397        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9398                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9399        mEphemeralInstallerActivity.theme = 0;
9400        mEphemeralInstallerActivity.exported = true;
9401        mEphemeralInstallerActivity.enabled = true;
9402        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9403        mEphemeralInstallerInfo.priority = 0;
9404        mEphemeralInstallerInfo.preferredOrder = 0;
9405        mEphemeralInstallerInfo.match = 0;
9406
9407        if (DEBUG_EPHEMERAL) {
9408            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9409        }
9410    }
9411
9412    private static String calculateBundledApkRoot(final String codePathString) {
9413        final File codePath = new File(codePathString);
9414        final File codeRoot;
9415        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9416            codeRoot = Environment.getRootDirectory();
9417        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9418            codeRoot = Environment.getOemDirectory();
9419        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9420            codeRoot = Environment.getVendorDirectory();
9421        } else {
9422            // Unrecognized code path; take its top real segment as the apk root:
9423            // e.g. /something/app/blah.apk => /something
9424            try {
9425                File f = codePath.getCanonicalFile();
9426                File parent = f.getParentFile();    // non-null because codePath is a file
9427                File tmp;
9428                while ((tmp = parent.getParentFile()) != null) {
9429                    f = parent;
9430                    parent = tmp;
9431                }
9432                codeRoot = f;
9433                Slog.w(TAG, "Unrecognized code path "
9434                        + codePath + " - using " + codeRoot);
9435            } catch (IOException e) {
9436                // Can't canonicalize the code path -- shenanigans?
9437                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9438                return Environment.getRootDirectory().getPath();
9439            }
9440        }
9441        return codeRoot.getPath();
9442    }
9443
9444    /**
9445     * Derive and set the location of native libraries for the given package,
9446     * which varies depending on where and how the package was installed.
9447     */
9448    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9449        final ApplicationInfo info = pkg.applicationInfo;
9450        final String codePath = pkg.codePath;
9451        final File codeFile = new File(codePath);
9452        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9453        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9454
9455        info.nativeLibraryRootDir = null;
9456        info.nativeLibraryRootRequiresIsa = false;
9457        info.nativeLibraryDir = null;
9458        info.secondaryNativeLibraryDir = null;
9459
9460        if (isApkFile(codeFile)) {
9461            // Monolithic install
9462            if (bundledApp) {
9463                // If "/system/lib64/apkname" exists, assume that is the per-package
9464                // native library directory to use; otherwise use "/system/lib/apkname".
9465                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9466                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9467                        getPrimaryInstructionSet(info));
9468
9469                // This is a bundled system app so choose the path based on the ABI.
9470                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9471                // is just the default path.
9472                final String apkName = deriveCodePathName(codePath);
9473                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9474                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9475                        apkName).getAbsolutePath();
9476
9477                if (info.secondaryCpuAbi != null) {
9478                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9479                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9480                            secondaryLibDir, apkName).getAbsolutePath();
9481                }
9482            } else if (asecApp) {
9483                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9484                        .getAbsolutePath();
9485            } else {
9486                final String apkName = deriveCodePathName(codePath);
9487                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9488                        .getAbsolutePath();
9489            }
9490
9491            info.nativeLibraryRootRequiresIsa = false;
9492            info.nativeLibraryDir = info.nativeLibraryRootDir;
9493        } else {
9494            // Cluster install
9495            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9496            info.nativeLibraryRootRequiresIsa = true;
9497
9498            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9499                    getPrimaryInstructionSet(info)).getAbsolutePath();
9500
9501            if (info.secondaryCpuAbi != null) {
9502                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9503                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9504            }
9505        }
9506    }
9507
9508    /**
9509     * Calculate the abis and roots for a bundled app. These can uniquely
9510     * be determined from the contents of the system partition, i.e whether
9511     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9512     * of this information, and instead assume that the system was built
9513     * sensibly.
9514     */
9515    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9516                                           PackageSetting pkgSetting) {
9517        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9518
9519        // If "/system/lib64/apkname" exists, assume that is the per-package
9520        // native library directory to use; otherwise use "/system/lib/apkname".
9521        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9522        setBundledAppAbi(pkg, apkRoot, apkName);
9523        // pkgSetting might be null during rescan following uninstall of updates
9524        // to a bundled app, so accommodate that possibility.  The settings in
9525        // that case will be established later from the parsed package.
9526        //
9527        // If the settings aren't null, sync them up with what we've just derived.
9528        // note that apkRoot isn't stored in the package settings.
9529        if (pkgSetting != null) {
9530            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9531            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9532        }
9533    }
9534
9535    /**
9536     * Deduces the ABI of a bundled app and sets the relevant fields on the
9537     * parsed pkg object.
9538     *
9539     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9540     *        under which system libraries are installed.
9541     * @param apkName the name of the installed package.
9542     */
9543    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9544        final File codeFile = new File(pkg.codePath);
9545
9546        final boolean has64BitLibs;
9547        final boolean has32BitLibs;
9548        if (isApkFile(codeFile)) {
9549            // Monolithic install
9550            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9551            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9552        } else {
9553            // Cluster install
9554            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9555            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9556                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9557                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9558                has64BitLibs = (new File(rootDir, isa)).exists();
9559            } else {
9560                has64BitLibs = false;
9561            }
9562            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9563                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9564                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9565                has32BitLibs = (new File(rootDir, isa)).exists();
9566            } else {
9567                has32BitLibs = false;
9568            }
9569        }
9570
9571        if (has64BitLibs && !has32BitLibs) {
9572            // The package has 64 bit libs, but not 32 bit libs. Its primary
9573            // ABI should be 64 bit. We can safely assume here that the bundled
9574            // native libraries correspond to the most preferred ABI in the list.
9575
9576            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9577            pkg.applicationInfo.secondaryCpuAbi = null;
9578        } else if (has32BitLibs && !has64BitLibs) {
9579            // The package has 32 bit libs but not 64 bit libs. Its primary
9580            // ABI should be 32 bit.
9581
9582            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9583            pkg.applicationInfo.secondaryCpuAbi = null;
9584        } else if (has32BitLibs && has64BitLibs) {
9585            // The application has both 64 and 32 bit bundled libraries. We check
9586            // here that the app declares multiArch support, and warn if it doesn't.
9587            //
9588            // We will be lenient here and record both ABIs. The primary will be the
9589            // ABI that's higher on the list, i.e, a device that's configured to prefer
9590            // 64 bit apps will see a 64 bit primary ABI,
9591
9592            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9593                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9594            }
9595
9596            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9597                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9598                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9599            } else {
9600                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9601                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9602            }
9603        } else {
9604            pkg.applicationInfo.primaryCpuAbi = null;
9605            pkg.applicationInfo.secondaryCpuAbi = null;
9606        }
9607    }
9608
9609    private void killApplication(String pkgName, int appId, String reason) {
9610        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9611    }
9612
9613    private void killApplication(String pkgName, int appId, int userId, String reason) {
9614        // Request the ActivityManager to kill the process(only for existing packages)
9615        // so that we do not end up in a confused state while the user is still using the older
9616        // version of the application while the new one gets installed.
9617        final long token = Binder.clearCallingIdentity();
9618        try {
9619            IActivityManager am = ActivityManagerNative.getDefault();
9620            if (am != null) {
9621                try {
9622                    am.killApplication(pkgName, appId, userId, reason);
9623                } catch (RemoteException e) {
9624                }
9625            }
9626        } finally {
9627            Binder.restoreCallingIdentity(token);
9628        }
9629    }
9630
9631    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9632        // Remove the parent package setting
9633        PackageSetting ps = (PackageSetting) pkg.mExtras;
9634        if (ps != null) {
9635            removePackageLI(ps, chatty);
9636        }
9637        // Remove the child package setting
9638        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9639        for (int i = 0; i < childCount; i++) {
9640            PackageParser.Package childPkg = pkg.childPackages.get(i);
9641            ps = (PackageSetting) childPkg.mExtras;
9642            if (ps != null) {
9643                removePackageLI(ps, chatty);
9644            }
9645        }
9646    }
9647
9648    void removePackageLI(PackageSetting ps, boolean chatty) {
9649        if (DEBUG_INSTALL) {
9650            if (chatty)
9651                Log.d(TAG, "Removing package " + ps.name);
9652        }
9653
9654        // writer
9655        synchronized (mPackages) {
9656            mPackages.remove(ps.name);
9657            final PackageParser.Package pkg = ps.pkg;
9658            if (pkg != null) {
9659                cleanPackageDataStructuresLILPw(pkg, chatty);
9660            }
9661        }
9662    }
9663
9664    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9665        if (DEBUG_INSTALL) {
9666            if (chatty)
9667                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9668        }
9669
9670        // writer
9671        synchronized (mPackages) {
9672            // Remove the parent package
9673            mPackages.remove(pkg.applicationInfo.packageName);
9674            cleanPackageDataStructuresLILPw(pkg, chatty);
9675
9676            // Remove the child packages
9677            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9678            for (int i = 0; i < childCount; i++) {
9679                PackageParser.Package childPkg = pkg.childPackages.get(i);
9680                mPackages.remove(childPkg.applicationInfo.packageName);
9681                cleanPackageDataStructuresLILPw(childPkg, chatty);
9682            }
9683        }
9684    }
9685
9686    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9687        int N = pkg.providers.size();
9688        StringBuilder r = null;
9689        int i;
9690        for (i=0; i<N; i++) {
9691            PackageParser.Provider p = pkg.providers.get(i);
9692            mProviders.removeProvider(p);
9693            if (p.info.authority == null) {
9694
9695                /* There was another ContentProvider with this authority when
9696                 * this app was installed so this authority is null,
9697                 * Ignore it as we don't have to unregister the provider.
9698                 */
9699                continue;
9700            }
9701            String names[] = p.info.authority.split(";");
9702            for (int j = 0; j < names.length; j++) {
9703                if (mProvidersByAuthority.get(names[j]) == p) {
9704                    mProvidersByAuthority.remove(names[j]);
9705                    if (DEBUG_REMOVE) {
9706                        if (chatty)
9707                            Log.d(TAG, "Unregistered content provider: " + names[j]
9708                                    + ", className = " + p.info.name + ", isSyncable = "
9709                                    + p.info.isSyncable);
9710                    }
9711                }
9712            }
9713            if (DEBUG_REMOVE && chatty) {
9714                if (r == null) {
9715                    r = new StringBuilder(256);
9716                } else {
9717                    r.append(' ');
9718                }
9719                r.append(p.info.name);
9720            }
9721        }
9722        if (r != null) {
9723            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9724        }
9725
9726        N = pkg.services.size();
9727        r = null;
9728        for (i=0; i<N; i++) {
9729            PackageParser.Service s = pkg.services.get(i);
9730            mServices.removeService(s);
9731            if (chatty) {
9732                if (r == null) {
9733                    r = new StringBuilder(256);
9734                } else {
9735                    r.append(' ');
9736                }
9737                r.append(s.info.name);
9738            }
9739        }
9740        if (r != null) {
9741            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9742        }
9743
9744        N = pkg.receivers.size();
9745        r = null;
9746        for (i=0; i<N; i++) {
9747            PackageParser.Activity a = pkg.receivers.get(i);
9748            mReceivers.removeActivity(a, "receiver");
9749            if (DEBUG_REMOVE && chatty) {
9750                if (r == null) {
9751                    r = new StringBuilder(256);
9752                } else {
9753                    r.append(' ');
9754                }
9755                r.append(a.info.name);
9756            }
9757        }
9758        if (r != null) {
9759            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9760        }
9761
9762        N = pkg.activities.size();
9763        r = null;
9764        for (i=0; i<N; i++) {
9765            PackageParser.Activity a = pkg.activities.get(i);
9766            mActivities.removeActivity(a, "activity");
9767            if (DEBUG_REMOVE && chatty) {
9768                if (r == null) {
9769                    r = new StringBuilder(256);
9770                } else {
9771                    r.append(' ');
9772                }
9773                r.append(a.info.name);
9774            }
9775        }
9776        if (r != null) {
9777            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9778        }
9779
9780        N = pkg.permissions.size();
9781        r = null;
9782        for (i=0; i<N; i++) {
9783            PackageParser.Permission p = pkg.permissions.get(i);
9784            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9785            if (bp == null) {
9786                bp = mSettings.mPermissionTrees.get(p.info.name);
9787            }
9788            if (bp != null && bp.perm == p) {
9789                bp.perm = null;
9790                if (DEBUG_REMOVE && chatty) {
9791                    if (r == null) {
9792                        r = new StringBuilder(256);
9793                    } else {
9794                        r.append(' ');
9795                    }
9796                    r.append(p.info.name);
9797                }
9798            }
9799            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9800                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9801                if (appOpPkgs != null) {
9802                    appOpPkgs.remove(pkg.packageName);
9803                }
9804            }
9805        }
9806        if (r != null) {
9807            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9808        }
9809
9810        N = pkg.requestedPermissions.size();
9811        r = null;
9812        for (i=0; i<N; i++) {
9813            String perm = pkg.requestedPermissions.get(i);
9814            BasePermission bp = mSettings.mPermissions.get(perm);
9815            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9816                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9817                if (appOpPkgs != null) {
9818                    appOpPkgs.remove(pkg.packageName);
9819                    if (appOpPkgs.isEmpty()) {
9820                        mAppOpPermissionPackages.remove(perm);
9821                    }
9822                }
9823            }
9824        }
9825        if (r != null) {
9826            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9827        }
9828
9829        N = pkg.instrumentation.size();
9830        r = null;
9831        for (i=0; i<N; i++) {
9832            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9833            mInstrumentation.remove(a.getComponentName());
9834            if (DEBUG_REMOVE && chatty) {
9835                if (r == null) {
9836                    r = new StringBuilder(256);
9837                } else {
9838                    r.append(' ');
9839                }
9840                r.append(a.info.name);
9841            }
9842        }
9843        if (r != null) {
9844            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9845        }
9846
9847        r = null;
9848        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9849            // Only system apps can hold shared libraries.
9850            if (pkg.libraryNames != null) {
9851                for (i=0; i<pkg.libraryNames.size(); i++) {
9852                    String name = pkg.libraryNames.get(i);
9853                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9854                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9855                        mSharedLibraries.remove(name);
9856                        if (DEBUG_REMOVE && chatty) {
9857                            if (r == null) {
9858                                r = new StringBuilder(256);
9859                            } else {
9860                                r.append(' ');
9861                            }
9862                            r.append(name);
9863                        }
9864                    }
9865                }
9866            }
9867        }
9868        if (r != null) {
9869            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9870        }
9871    }
9872
9873    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9874        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9875            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9876                return true;
9877            }
9878        }
9879        return false;
9880    }
9881
9882    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9883    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9884    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9885
9886    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9887        // Update the parent permissions
9888        updatePermissionsLPw(pkg.packageName, pkg, flags);
9889        // Update the child permissions
9890        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9891        for (int i = 0; i < childCount; i++) {
9892            PackageParser.Package childPkg = pkg.childPackages.get(i);
9893            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9894        }
9895    }
9896
9897    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9898            int flags) {
9899        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9900        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9901    }
9902
9903    private void updatePermissionsLPw(String changingPkg,
9904            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9905        // Make sure there are no dangling permission trees.
9906        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9907        while (it.hasNext()) {
9908            final BasePermission bp = it.next();
9909            if (bp.packageSetting == null) {
9910                // We may not yet have parsed the package, so just see if
9911                // we still know about its settings.
9912                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9913            }
9914            if (bp.packageSetting == null) {
9915                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9916                        + " from package " + bp.sourcePackage);
9917                it.remove();
9918            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9919                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9920                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9921                            + " from package " + bp.sourcePackage);
9922                    flags |= UPDATE_PERMISSIONS_ALL;
9923                    it.remove();
9924                }
9925            }
9926        }
9927
9928        // Make sure all dynamic permissions have been assigned to a package,
9929        // and make sure there are no dangling permissions.
9930        it = mSettings.mPermissions.values().iterator();
9931        while (it.hasNext()) {
9932            final BasePermission bp = it.next();
9933            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9934                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9935                        + bp.name + " pkg=" + bp.sourcePackage
9936                        + " info=" + bp.pendingInfo);
9937                if (bp.packageSetting == null && bp.pendingInfo != null) {
9938                    final BasePermission tree = findPermissionTreeLP(bp.name);
9939                    if (tree != null && tree.perm != null) {
9940                        bp.packageSetting = tree.packageSetting;
9941                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9942                                new PermissionInfo(bp.pendingInfo));
9943                        bp.perm.info.packageName = tree.perm.info.packageName;
9944                        bp.perm.info.name = bp.name;
9945                        bp.uid = tree.uid;
9946                    }
9947                }
9948            }
9949            if (bp.packageSetting == null) {
9950                // We may not yet have parsed the package, so just see if
9951                // we still know about its settings.
9952                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9953            }
9954            if (bp.packageSetting == null) {
9955                Slog.w(TAG, "Removing dangling permission: " + bp.name
9956                        + " from package " + bp.sourcePackage);
9957                it.remove();
9958            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9959                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9960                    Slog.i(TAG, "Removing old permission: " + bp.name
9961                            + " from package " + bp.sourcePackage);
9962                    flags |= UPDATE_PERMISSIONS_ALL;
9963                    it.remove();
9964                }
9965            }
9966        }
9967
9968        // Now update the permissions for all packages, in particular
9969        // replace the granted permissions of the system packages.
9970        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9971            for (PackageParser.Package pkg : mPackages.values()) {
9972                if (pkg != pkgInfo) {
9973                    // Only replace for packages on requested volume
9974                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9975                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9976                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9977                    grantPermissionsLPw(pkg, replace, changingPkg);
9978                }
9979            }
9980        }
9981
9982        if (pkgInfo != null) {
9983            // Only replace for packages on requested volume
9984            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9985            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9986                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9987            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9988        }
9989    }
9990
9991    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9992            String packageOfInterest) {
9993        // IMPORTANT: There are two types of permissions: install and runtime.
9994        // Install time permissions are granted when the app is installed to
9995        // all device users and users added in the future. Runtime permissions
9996        // are granted at runtime explicitly to specific users. Normal and signature
9997        // protected permissions are install time permissions. Dangerous permissions
9998        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9999        // otherwise they are runtime permissions. This function does not manage
10000        // runtime permissions except for the case an app targeting Lollipop MR1
10001        // being upgraded to target a newer SDK, in which case dangerous permissions
10002        // are transformed from install time to runtime ones.
10003
10004        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10005        if (ps == null) {
10006            return;
10007        }
10008
10009        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10010
10011        PermissionsState permissionsState = ps.getPermissionsState();
10012        PermissionsState origPermissions = permissionsState;
10013
10014        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10015
10016        boolean runtimePermissionsRevoked = false;
10017        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10018
10019        boolean changedInstallPermission = false;
10020
10021        if (replace) {
10022            ps.installPermissionsFixed = false;
10023            if (!ps.isSharedUser()) {
10024                origPermissions = new PermissionsState(permissionsState);
10025                permissionsState.reset();
10026            } else {
10027                // We need to know only about runtime permission changes since the
10028                // calling code always writes the install permissions state but
10029                // the runtime ones are written only if changed. The only cases of
10030                // changed runtime permissions here are promotion of an install to
10031                // runtime and revocation of a runtime from a shared user.
10032                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10033                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10034                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10035                    runtimePermissionsRevoked = true;
10036                }
10037            }
10038        }
10039
10040        permissionsState.setGlobalGids(mGlobalGids);
10041
10042        final int N = pkg.requestedPermissions.size();
10043        for (int i=0; i<N; i++) {
10044            final String name = pkg.requestedPermissions.get(i);
10045            final BasePermission bp = mSettings.mPermissions.get(name);
10046
10047            if (DEBUG_INSTALL) {
10048                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10049            }
10050
10051            if (bp == null || bp.packageSetting == null) {
10052                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10053                    Slog.w(TAG, "Unknown permission " + name
10054                            + " in package " + pkg.packageName);
10055                }
10056                continue;
10057            }
10058
10059            final String perm = bp.name;
10060            boolean allowedSig = false;
10061            int grant = GRANT_DENIED;
10062
10063            // Keep track of app op permissions.
10064            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10065                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10066                if (pkgs == null) {
10067                    pkgs = new ArraySet<>();
10068                    mAppOpPermissionPackages.put(bp.name, pkgs);
10069                }
10070                pkgs.add(pkg.packageName);
10071            }
10072
10073            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10074            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10075                    >= Build.VERSION_CODES.M;
10076            switch (level) {
10077                case PermissionInfo.PROTECTION_NORMAL: {
10078                    // For all apps normal permissions are install time ones.
10079                    grant = GRANT_INSTALL;
10080                } break;
10081
10082                case PermissionInfo.PROTECTION_DANGEROUS: {
10083                    // If a permission review is required for legacy apps we represent
10084                    // their permissions as always granted runtime ones since we need
10085                    // to keep the review required permission flag per user while an
10086                    // install permission's state is shared across all users.
10087                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10088                        // For legacy apps dangerous permissions are install time ones.
10089                        grant = GRANT_INSTALL;
10090                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10091                        // For legacy apps that became modern, install becomes runtime.
10092                        grant = GRANT_UPGRADE;
10093                    } else if (mPromoteSystemApps
10094                            && isSystemApp(ps)
10095                            && mExistingSystemPackages.contains(ps.name)) {
10096                        // For legacy system apps, install becomes runtime.
10097                        // We cannot check hasInstallPermission() for system apps since those
10098                        // permissions were granted implicitly and not persisted pre-M.
10099                        grant = GRANT_UPGRADE;
10100                    } else {
10101                        // For modern apps keep runtime permissions unchanged.
10102                        grant = GRANT_RUNTIME;
10103                    }
10104                } break;
10105
10106                case PermissionInfo.PROTECTION_SIGNATURE: {
10107                    // For all apps signature permissions are install time ones.
10108                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10109                    if (allowedSig) {
10110                        grant = GRANT_INSTALL;
10111                    }
10112                } break;
10113            }
10114
10115            if (DEBUG_INSTALL) {
10116                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10117            }
10118
10119            if (grant != GRANT_DENIED) {
10120                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10121                    // If this is an existing, non-system package, then
10122                    // we can't add any new permissions to it.
10123                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10124                        // Except...  if this is a permission that was added
10125                        // to the platform (note: need to only do this when
10126                        // updating the platform).
10127                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10128                            grant = GRANT_DENIED;
10129                        }
10130                    }
10131                }
10132
10133                switch (grant) {
10134                    case GRANT_INSTALL: {
10135                        // Revoke this as runtime permission to handle the case of
10136                        // a runtime permission being downgraded to an install one.
10137                        // Also in permission review mode we keep dangerous permissions
10138                        // for legacy apps
10139                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10140                            if (origPermissions.getRuntimePermissionState(
10141                                    bp.name, userId) != null) {
10142                                // Revoke the runtime permission and clear the flags.
10143                                origPermissions.revokeRuntimePermission(bp, userId);
10144                                origPermissions.updatePermissionFlags(bp, userId,
10145                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10146                                // If we revoked a permission permission, we have to write.
10147                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10148                                        changedRuntimePermissionUserIds, userId);
10149                            }
10150                        }
10151                        // Grant an install permission.
10152                        if (permissionsState.grantInstallPermission(bp) !=
10153                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10154                            changedInstallPermission = true;
10155                        }
10156                    } break;
10157
10158                    case GRANT_RUNTIME: {
10159                        // Grant previously granted runtime permissions.
10160                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10161                            PermissionState permissionState = origPermissions
10162                                    .getRuntimePermissionState(bp.name, userId);
10163                            int flags = permissionState != null
10164                                    ? permissionState.getFlags() : 0;
10165                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10166                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10167                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10168                                    // If we cannot put the permission as it was, we have to write.
10169                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10170                                            changedRuntimePermissionUserIds, userId);
10171                                }
10172                                // If the app supports runtime permissions no need for a review.
10173                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10174                                        && appSupportsRuntimePermissions
10175                                        && (flags & PackageManager
10176                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10177                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10178                                    // Since we changed the flags, we have to write.
10179                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10180                                            changedRuntimePermissionUserIds, userId);
10181                                }
10182                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10183                                    && !appSupportsRuntimePermissions) {
10184                                // For legacy apps that need a permission review, every new
10185                                // runtime permission is granted but it is pending a review.
10186                                // We also need to review only platform defined runtime
10187                                // permissions as these are the only ones the platform knows
10188                                // how to disable the API to simulate revocation as legacy
10189                                // apps don't expect to run with revoked permissions.
10190                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10191                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10192                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10193                                        // We changed the flags, hence have to write.
10194                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10195                                                changedRuntimePermissionUserIds, userId);
10196                                    }
10197                                }
10198                                if (permissionsState.grantRuntimePermission(bp, userId)
10199                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10200                                    // We changed the permission, hence have to write.
10201                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10202                                            changedRuntimePermissionUserIds, userId);
10203                                }
10204                            }
10205                            // Propagate the permission flags.
10206                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10207                        }
10208                    } break;
10209
10210                    case GRANT_UPGRADE: {
10211                        // Grant runtime permissions for a previously held install permission.
10212                        PermissionState permissionState = origPermissions
10213                                .getInstallPermissionState(bp.name);
10214                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10215
10216                        if (origPermissions.revokeInstallPermission(bp)
10217                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10218                            // We will be transferring the permission flags, so clear them.
10219                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10220                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10221                            changedInstallPermission = true;
10222                        }
10223
10224                        // If the permission is not to be promoted to runtime we ignore it and
10225                        // also its other flags as they are not applicable to install permissions.
10226                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10227                            for (int userId : currentUserIds) {
10228                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10229                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10230                                    // Transfer the permission flags.
10231                                    permissionsState.updatePermissionFlags(bp, userId,
10232                                            flags, flags);
10233                                    // If we granted the permission, we have to write.
10234                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10235                                            changedRuntimePermissionUserIds, userId);
10236                                }
10237                            }
10238                        }
10239                    } break;
10240
10241                    default: {
10242                        if (packageOfInterest == null
10243                                || packageOfInterest.equals(pkg.packageName)) {
10244                            Slog.w(TAG, "Not granting permission " + perm
10245                                    + " to package " + pkg.packageName
10246                                    + " because it was previously installed without");
10247                        }
10248                    } break;
10249                }
10250            } else {
10251                if (permissionsState.revokeInstallPermission(bp) !=
10252                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10253                    // Also drop the permission flags.
10254                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10255                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10256                    changedInstallPermission = true;
10257                    Slog.i(TAG, "Un-granting permission " + perm
10258                            + " from package " + pkg.packageName
10259                            + " (protectionLevel=" + bp.protectionLevel
10260                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10261                            + ")");
10262                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10263                    // Don't print warning for app op permissions, since it is fine for them
10264                    // not to be granted, there is a UI for the user to decide.
10265                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10266                        Slog.w(TAG, "Not granting permission " + perm
10267                                + " to package " + pkg.packageName
10268                                + " (protectionLevel=" + bp.protectionLevel
10269                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10270                                + ")");
10271                    }
10272                }
10273            }
10274        }
10275
10276        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10277                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10278            // This is the first that we have heard about this package, so the
10279            // permissions we have now selected are fixed until explicitly
10280            // changed.
10281            ps.installPermissionsFixed = true;
10282        }
10283
10284        // Persist the runtime permissions state for users with changes. If permissions
10285        // were revoked because no app in the shared user declares them we have to
10286        // write synchronously to avoid losing runtime permissions state.
10287        for (int userId : changedRuntimePermissionUserIds) {
10288            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10289        }
10290
10291        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10292    }
10293
10294    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10295        boolean allowed = false;
10296        final int NP = PackageParser.NEW_PERMISSIONS.length;
10297        for (int ip=0; ip<NP; ip++) {
10298            final PackageParser.NewPermissionInfo npi
10299                    = PackageParser.NEW_PERMISSIONS[ip];
10300            if (npi.name.equals(perm)
10301                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10302                allowed = true;
10303                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10304                        + pkg.packageName);
10305                break;
10306            }
10307        }
10308        return allowed;
10309    }
10310
10311    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10312            BasePermission bp, PermissionsState origPermissions) {
10313        boolean allowed;
10314        allowed = (compareSignatures(
10315                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10316                        == PackageManager.SIGNATURE_MATCH)
10317                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10318                        == PackageManager.SIGNATURE_MATCH);
10319        if (!allowed && (bp.protectionLevel
10320                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10321            if (isSystemApp(pkg)) {
10322                // For updated system applications, a system permission
10323                // is granted only if it had been defined by the original application.
10324                if (pkg.isUpdatedSystemApp()) {
10325                    final PackageSetting sysPs = mSettings
10326                            .getDisabledSystemPkgLPr(pkg.packageName);
10327                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10328                        // If the original was granted this permission, we take
10329                        // that grant decision as read and propagate it to the
10330                        // update.
10331                        if (sysPs.isPrivileged()) {
10332                            allowed = true;
10333                        }
10334                    } else {
10335                        // The system apk may have been updated with an older
10336                        // version of the one on the data partition, but which
10337                        // granted a new system permission that it didn't have
10338                        // before.  In this case we do want to allow the app to
10339                        // now get the new permission if the ancestral apk is
10340                        // privileged to get it.
10341                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10342                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10343                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10344                                    allowed = true;
10345                                    break;
10346                                }
10347                            }
10348                        }
10349                        // Also if a privileged parent package on the system image or any of
10350                        // its children requested a privileged permission, the updated child
10351                        // packages can also get the permission.
10352                        if (pkg.parentPackage != null) {
10353                            final PackageSetting disabledSysParentPs = mSettings
10354                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10355                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10356                                    && disabledSysParentPs.isPrivileged()) {
10357                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10358                                    allowed = true;
10359                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10360                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10361                                    for (int i = 0; i < count; i++) {
10362                                        PackageParser.Package disabledSysChildPkg =
10363                                                disabledSysParentPs.pkg.childPackages.get(i);
10364                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10365                                                perm)) {
10366                                            allowed = true;
10367                                            break;
10368                                        }
10369                                    }
10370                                }
10371                            }
10372                        }
10373                    }
10374                } else {
10375                    allowed = isPrivilegedApp(pkg);
10376                }
10377            }
10378        }
10379        if (!allowed) {
10380            if (!allowed && (bp.protectionLevel
10381                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10382                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10383                // If this was a previously normal/dangerous permission that got moved
10384                // to a system permission as part of the runtime permission redesign, then
10385                // we still want to blindly grant it to old apps.
10386                allowed = true;
10387            }
10388            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10389                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10390                // If this permission is to be granted to the system installer and
10391                // this app is an installer, then it gets the permission.
10392                allowed = true;
10393            }
10394            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10395                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10396                // If this permission is to be granted to the system verifier and
10397                // this app is a verifier, then it gets the permission.
10398                allowed = true;
10399            }
10400            if (!allowed && (bp.protectionLevel
10401                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10402                    && isSystemApp(pkg)) {
10403                // Any pre-installed system app is allowed to get this permission.
10404                allowed = true;
10405            }
10406            if (!allowed && (bp.protectionLevel
10407                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10408                // For development permissions, a development permission
10409                // is granted only if it was already granted.
10410                allowed = origPermissions.hasInstallPermission(perm);
10411            }
10412            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10413                    && pkg.packageName.equals(mSetupWizardPackage)) {
10414                // If this permission is to be granted to the system setup wizard and
10415                // this app is a setup wizard, then it gets the permission.
10416                allowed = true;
10417            }
10418        }
10419        return allowed;
10420    }
10421
10422    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10423        final int permCount = pkg.requestedPermissions.size();
10424        for (int j = 0; j < permCount; j++) {
10425            String requestedPermission = pkg.requestedPermissions.get(j);
10426            if (permission.equals(requestedPermission)) {
10427                return true;
10428            }
10429        }
10430        return false;
10431    }
10432
10433    final class ActivityIntentResolver
10434            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10435        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10436                boolean defaultOnly, int userId) {
10437            if (!sUserManager.exists(userId)) return null;
10438            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10439            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10440        }
10441
10442        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10443                int userId) {
10444            if (!sUserManager.exists(userId)) return null;
10445            mFlags = flags;
10446            return super.queryIntent(intent, resolvedType,
10447                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10448        }
10449
10450        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10451                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10452            if (!sUserManager.exists(userId)) return null;
10453            if (packageActivities == null) {
10454                return null;
10455            }
10456            mFlags = flags;
10457            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10458            final int N = packageActivities.size();
10459            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10460                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10461
10462            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10463            for (int i = 0; i < N; ++i) {
10464                intentFilters = packageActivities.get(i).intents;
10465                if (intentFilters != null && intentFilters.size() > 0) {
10466                    PackageParser.ActivityIntentInfo[] array =
10467                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10468                    intentFilters.toArray(array);
10469                    listCut.add(array);
10470                }
10471            }
10472            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10473        }
10474
10475        /**
10476         * Finds a privileged activity that matches the specified activity names.
10477         */
10478        private PackageParser.Activity findMatchingActivity(
10479                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10480            for (PackageParser.Activity sysActivity : activityList) {
10481                if (sysActivity.info.name.equals(activityInfo.name)) {
10482                    return sysActivity;
10483                }
10484                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10485                    return sysActivity;
10486                }
10487                if (sysActivity.info.targetActivity != null) {
10488                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10489                        return sysActivity;
10490                    }
10491                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10492                        return sysActivity;
10493                    }
10494                }
10495            }
10496            return null;
10497        }
10498
10499        public class IterGenerator<E> {
10500            public Iterator<E> generate(ActivityIntentInfo info) {
10501                return null;
10502            }
10503        }
10504
10505        public class ActionIterGenerator extends IterGenerator<String> {
10506            @Override
10507            public Iterator<String> generate(ActivityIntentInfo info) {
10508                return info.actionsIterator();
10509            }
10510        }
10511
10512        public class CategoriesIterGenerator extends IterGenerator<String> {
10513            @Override
10514            public Iterator<String> generate(ActivityIntentInfo info) {
10515                return info.categoriesIterator();
10516            }
10517        }
10518
10519        public class SchemesIterGenerator extends IterGenerator<String> {
10520            @Override
10521            public Iterator<String> generate(ActivityIntentInfo info) {
10522                return info.schemesIterator();
10523            }
10524        }
10525
10526        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10527            @Override
10528            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10529                return info.authoritiesIterator();
10530            }
10531        }
10532
10533        /**
10534         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10535         * MODIFIED. Do not pass in a list that should not be changed.
10536         */
10537        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10538                IterGenerator<T> generator, Iterator<T> searchIterator) {
10539            // loop through the set of actions; every one must be found in the intent filter
10540            while (searchIterator.hasNext()) {
10541                // we must have at least one filter in the list to consider a match
10542                if (intentList.size() == 0) {
10543                    break;
10544                }
10545
10546                final T searchAction = searchIterator.next();
10547
10548                // loop through the set of intent filters
10549                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10550                while (intentIter.hasNext()) {
10551                    final ActivityIntentInfo intentInfo = intentIter.next();
10552                    boolean selectionFound = false;
10553
10554                    // loop through the intent filter's selection criteria; at least one
10555                    // of them must match the searched criteria
10556                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10557                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10558                        final T intentSelection = intentSelectionIter.next();
10559                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10560                            selectionFound = true;
10561                            break;
10562                        }
10563                    }
10564
10565                    // the selection criteria wasn't found in this filter's set; this filter
10566                    // is not a potential match
10567                    if (!selectionFound) {
10568                        intentIter.remove();
10569                    }
10570                }
10571            }
10572        }
10573
10574        private boolean isProtectedAction(ActivityIntentInfo filter) {
10575            final Iterator<String> actionsIter = filter.actionsIterator();
10576            while (actionsIter != null && actionsIter.hasNext()) {
10577                final String filterAction = actionsIter.next();
10578                if (PROTECTED_ACTIONS.contains(filterAction)) {
10579                    return true;
10580                }
10581            }
10582            return false;
10583        }
10584
10585        /**
10586         * Adjusts the priority of the given intent filter according to policy.
10587         * <p>
10588         * <ul>
10589         * <li>The priority for non privileged applications is capped to '0'</li>
10590         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10591         * <li>The priority for unbundled updates to privileged applications is capped to the
10592         *      priority defined on the system partition</li>
10593         * </ul>
10594         * <p>
10595         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10596         * allowed to obtain any priority on any action.
10597         */
10598        private void adjustPriority(
10599                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10600            // nothing to do; priority is fine as-is
10601            if (intent.getPriority() <= 0) {
10602                return;
10603            }
10604
10605            final ActivityInfo activityInfo = intent.activity.info;
10606            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10607
10608            final boolean privilegedApp =
10609                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10610            if (!privilegedApp) {
10611                // non-privileged applications can never define a priority >0
10612                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10613                        + " package: " + applicationInfo.packageName
10614                        + " activity: " + intent.activity.className
10615                        + " origPrio: " + intent.getPriority());
10616                intent.setPriority(0);
10617                return;
10618            }
10619
10620            if (systemActivities == null) {
10621                // the system package is not disabled; we're parsing the system partition
10622                if (isProtectedAction(intent)) {
10623                    if (mDeferProtectedFilters) {
10624                        // We can't deal with these just yet. No component should ever obtain a
10625                        // >0 priority for a protected actions, with ONE exception -- the setup
10626                        // wizard. The setup wizard, however, cannot be known until we're able to
10627                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10628                        // until all intent filters have been processed. Chicken, meet egg.
10629                        // Let the filter temporarily have a high priority and rectify the
10630                        // priorities after all system packages have been scanned.
10631                        mProtectedFilters.add(intent);
10632                        if (DEBUG_FILTERS) {
10633                            Slog.i(TAG, "Protected action; save for later;"
10634                                    + " package: " + applicationInfo.packageName
10635                                    + " activity: " + intent.activity.className
10636                                    + " origPrio: " + intent.getPriority());
10637                        }
10638                        return;
10639                    } else {
10640                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10641                            Slog.i(TAG, "No setup wizard;"
10642                                + " All protected intents capped to priority 0");
10643                        }
10644                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10645                            if (DEBUG_FILTERS) {
10646                                Slog.i(TAG, "Found setup wizard;"
10647                                    + " allow priority " + intent.getPriority() + ";"
10648                                    + " package: " + intent.activity.info.packageName
10649                                    + " activity: " + intent.activity.className
10650                                    + " priority: " + intent.getPriority());
10651                            }
10652                            // setup wizard gets whatever it wants
10653                            return;
10654                        }
10655                        Slog.w(TAG, "Protected action; cap priority to 0;"
10656                                + " package: " + intent.activity.info.packageName
10657                                + " activity: " + intent.activity.className
10658                                + " origPrio: " + intent.getPriority());
10659                        intent.setPriority(0);
10660                        return;
10661                    }
10662                }
10663                // privileged apps on the system image get whatever priority they request
10664                return;
10665            }
10666
10667            // privileged app unbundled update ... try to find the same activity
10668            final PackageParser.Activity foundActivity =
10669                    findMatchingActivity(systemActivities, activityInfo);
10670            if (foundActivity == null) {
10671                // this is a new activity; it cannot obtain >0 priority
10672                if (DEBUG_FILTERS) {
10673                    Slog.i(TAG, "New activity; cap priority to 0;"
10674                            + " package: " + applicationInfo.packageName
10675                            + " activity: " + intent.activity.className
10676                            + " origPrio: " + intent.getPriority());
10677                }
10678                intent.setPriority(0);
10679                return;
10680            }
10681
10682            // found activity, now check for filter equivalence
10683
10684            // a shallow copy is enough; we modify the list, not its contents
10685            final List<ActivityIntentInfo> intentListCopy =
10686                    new ArrayList<>(foundActivity.intents);
10687            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10688
10689            // find matching action subsets
10690            final Iterator<String> actionsIterator = intent.actionsIterator();
10691            if (actionsIterator != null) {
10692                getIntentListSubset(
10693                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10694                if (intentListCopy.size() == 0) {
10695                    // no more intents to match; we're not equivalent
10696                    if (DEBUG_FILTERS) {
10697                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10698                                + " package: " + applicationInfo.packageName
10699                                + " activity: " + intent.activity.className
10700                                + " origPrio: " + intent.getPriority());
10701                    }
10702                    intent.setPriority(0);
10703                    return;
10704                }
10705            }
10706
10707            // find matching category subsets
10708            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10709            if (categoriesIterator != null) {
10710                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10711                        categoriesIterator);
10712                if (intentListCopy.size() == 0) {
10713                    // no more intents to match; we're not equivalent
10714                    if (DEBUG_FILTERS) {
10715                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10716                                + " package: " + applicationInfo.packageName
10717                                + " activity: " + intent.activity.className
10718                                + " origPrio: " + intent.getPriority());
10719                    }
10720                    intent.setPriority(0);
10721                    return;
10722                }
10723            }
10724
10725            // find matching schemes subsets
10726            final Iterator<String> schemesIterator = intent.schemesIterator();
10727            if (schemesIterator != null) {
10728                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10729                        schemesIterator);
10730                if (intentListCopy.size() == 0) {
10731                    // no more intents to match; we're not equivalent
10732                    if (DEBUG_FILTERS) {
10733                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10734                                + " package: " + applicationInfo.packageName
10735                                + " activity: " + intent.activity.className
10736                                + " origPrio: " + intent.getPriority());
10737                    }
10738                    intent.setPriority(0);
10739                    return;
10740                }
10741            }
10742
10743            // find matching authorities subsets
10744            final Iterator<IntentFilter.AuthorityEntry>
10745                    authoritiesIterator = intent.authoritiesIterator();
10746            if (authoritiesIterator != null) {
10747                getIntentListSubset(intentListCopy,
10748                        new AuthoritiesIterGenerator(),
10749                        authoritiesIterator);
10750                if (intentListCopy.size() == 0) {
10751                    // no more intents to match; we're not equivalent
10752                    if (DEBUG_FILTERS) {
10753                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10754                                + " package: " + applicationInfo.packageName
10755                                + " activity: " + intent.activity.className
10756                                + " origPrio: " + intent.getPriority());
10757                    }
10758                    intent.setPriority(0);
10759                    return;
10760                }
10761            }
10762
10763            // we found matching filter(s); app gets the max priority of all intents
10764            int cappedPriority = 0;
10765            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10766                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10767            }
10768            if (intent.getPriority() > cappedPriority) {
10769                if (DEBUG_FILTERS) {
10770                    Slog.i(TAG, "Found matching filter(s);"
10771                            + " cap priority to " + cappedPriority + ";"
10772                            + " package: " + applicationInfo.packageName
10773                            + " activity: " + intent.activity.className
10774                            + " origPrio: " + intent.getPriority());
10775                }
10776                intent.setPriority(cappedPriority);
10777                return;
10778            }
10779            // all this for nothing; the requested priority was <= what was on the system
10780        }
10781
10782        public final void addActivity(PackageParser.Activity a, String type) {
10783            mActivities.put(a.getComponentName(), a);
10784            if (DEBUG_SHOW_INFO)
10785                Log.v(
10786                TAG, "  " + type + " " +
10787                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10788            if (DEBUG_SHOW_INFO)
10789                Log.v(TAG, "    Class=" + a.info.name);
10790            final int NI = a.intents.size();
10791            for (int j=0; j<NI; j++) {
10792                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10793                if ("activity".equals(type)) {
10794                    final PackageSetting ps =
10795                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10796                    final List<PackageParser.Activity> systemActivities =
10797                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10798                    adjustPriority(systemActivities, intent);
10799                }
10800                if (DEBUG_SHOW_INFO) {
10801                    Log.v(TAG, "    IntentFilter:");
10802                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10803                }
10804                if (!intent.debugCheck()) {
10805                    Log.w(TAG, "==> For Activity " + a.info.name);
10806                }
10807                addFilter(intent);
10808            }
10809        }
10810
10811        public final void removeActivity(PackageParser.Activity a, String type) {
10812            mActivities.remove(a.getComponentName());
10813            if (DEBUG_SHOW_INFO) {
10814                Log.v(TAG, "  " + type + " "
10815                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10816                                : a.info.name) + ":");
10817                Log.v(TAG, "    Class=" + a.info.name);
10818            }
10819            final int NI = a.intents.size();
10820            for (int j=0; j<NI; j++) {
10821                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10822                if (DEBUG_SHOW_INFO) {
10823                    Log.v(TAG, "    IntentFilter:");
10824                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10825                }
10826                removeFilter(intent);
10827            }
10828        }
10829
10830        @Override
10831        protected boolean allowFilterResult(
10832                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10833            ActivityInfo filterAi = filter.activity.info;
10834            for (int i=dest.size()-1; i>=0; i--) {
10835                ActivityInfo destAi = dest.get(i).activityInfo;
10836                if (destAi.name == filterAi.name
10837                        && destAi.packageName == filterAi.packageName) {
10838                    return false;
10839                }
10840            }
10841            return true;
10842        }
10843
10844        @Override
10845        protected ActivityIntentInfo[] newArray(int size) {
10846            return new ActivityIntentInfo[size];
10847        }
10848
10849        @Override
10850        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10851            if (!sUserManager.exists(userId)) return true;
10852            PackageParser.Package p = filter.activity.owner;
10853            if (p != null) {
10854                PackageSetting ps = (PackageSetting)p.mExtras;
10855                if (ps != null) {
10856                    // System apps are never considered stopped for purposes of
10857                    // filtering, because there may be no way for the user to
10858                    // actually re-launch them.
10859                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10860                            && ps.getStopped(userId);
10861                }
10862            }
10863            return false;
10864        }
10865
10866        @Override
10867        protected boolean isPackageForFilter(String packageName,
10868                PackageParser.ActivityIntentInfo info) {
10869            return packageName.equals(info.activity.owner.packageName);
10870        }
10871
10872        @Override
10873        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10874                int match, int userId) {
10875            if (!sUserManager.exists(userId)) return null;
10876            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10877                return null;
10878            }
10879            final PackageParser.Activity activity = info.activity;
10880            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10881            if (ps == null) {
10882                return null;
10883            }
10884            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10885                    ps.readUserState(userId), userId);
10886            if (ai == null) {
10887                return null;
10888            }
10889            final ResolveInfo res = new ResolveInfo();
10890            res.activityInfo = ai;
10891            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10892                res.filter = info;
10893            }
10894            if (info != null) {
10895                res.handleAllWebDataURI = info.handleAllWebDataURI();
10896            }
10897            res.priority = info.getPriority();
10898            res.preferredOrder = activity.owner.mPreferredOrder;
10899            //System.out.println("Result: " + res.activityInfo.className +
10900            //                   " = " + res.priority);
10901            res.match = match;
10902            res.isDefault = info.hasDefault;
10903            res.labelRes = info.labelRes;
10904            res.nonLocalizedLabel = info.nonLocalizedLabel;
10905            if (userNeedsBadging(userId)) {
10906                res.noResourceId = true;
10907            } else {
10908                res.icon = info.icon;
10909            }
10910            res.iconResourceId = info.icon;
10911            res.system = res.activityInfo.applicationInfo.isSystemApp();
10912            return res;
10913        }
10914
10915        @Override
10916        protected void sortResults(List<ResolveInfo> results) {
10917            Collections.sort(results, mResolvePrioritySorter);
10918        }
10919
10920        @Override
10921        protected void dumpFilter(PrintWriter out, String prefix,
10922                PackageParser.ActivityIntentInfo filter) {
10923            out.print(prefix); out.print(
10924                    Integer.toHexString(System.identityHashCode(filter.activity)));
10925                    out.print(' ');
10926                    filter.activity.printComponentShortName(out);
10927                    out.print(" filter ");
10928                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10929        }
10930
10931        @Override
10932        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10933            return filter.activity;
10934        }
10935
10936        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10937            PackageParser.Activity activity = (PackageParser.Activity)label;
10938            out.print(prefix); out.print(
10939                    Integer.toHexString(System.identityHashCode(activity)));
10940                    out.print(' ');
10941                    activity.printComponentShortName(out);
10942            if (count > 1) {
10943                out.print(" ("); out.print(count); out.print(" filters)");
10944            }
10945            out.println();
10946        }
10947
10948        // Keys are String (activity class name), values are Activity.
10949        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10950                = new ArrayMap<ComponentName, PackageParser.Activity>();
10951        private int mFlags;
10952    }
10953
10954    private final class ServiceIntentResolver
10955            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10956        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10957                boolean defaultOnly, int userId) {
10958            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10959            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10960        }
10961
10962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10963                int userId) {
10964            if (!sUserManager.exists(userId)) return null;
10965            mFlags = flags;
10966            return super.queryIntent(intent, resolvedType,
10967                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10968        }
10969
10970        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10971                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10972            if (!sUserManager.exists(userId)) return null;
10973            if (packageServices == null) {
10974                return null;
10975            }
10976            mFlags = flags;
10977            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10978            final int N = packageServices.size();
10979            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10980                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10981
10982            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10983            for (int i = 0; i < N; ++i) {
10984                intentFilters = packageServices.get(i).intents;
10985                if (intentFilters != null && intentFilters.size() > 0) {
10986                    PackageParser.ServiceIntentInfo[] array =
10987                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10988                    intentFilters.toArray(array);
10989                    listCut.add(array);
10990                }
10991            }
10992            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10993        }
10994
10995        public final void addService(PackageParser.Service s) {
10996            mServices.put(s.getComponentName(), s);
10997            if (DEBUG_SHOW_INFO) {
10998                Log.v(TAG, "  "
10999                        + (s.info.nonLocalizedLabel != null
11000                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11001                Log.v(TAG, "    Class=" + s.info.name);
11002            }
11003            final int NI = s.intents.size();
11004            int j;
11005            for (j=0; j<NI; j++) {
11006                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11007                if (DEBUG_SHOW_INFO) {
11008                    Log.v(TAG, "    IntentFilter:");
11009                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11010                }
11011                if (!intent.debugCheck()) {
11012                    Log.w(TAG, "==> For Service " + s.info.name);
11013                }
11014                addFilter(intent);
11015            }
11016        }
11017
11018        public final void removeService(PackageParser.Service s) {
11019            mServices.remove(s.getComponentName());
11020            if (DEBUG_SHOW_INFO) {
11021                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11022                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11023                Log.v(TAG, "    Class=" + s.info.name);
11024            }
11025            final int NI = s.intents.size();
11026            int j;
11027            for (j=0; j<NI; j++) {
11028                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11029                if (DEBUG_SHOW_INFO) {
11030                    Log.v(TAG, "    IntentFilter:");
11031                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11032                }
11033                removeFilter(intent);
11034            }
11035        }
11036
11037        @Override
11038        protected boolean allowFilterResult(
11039                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11040            ServiceInfo filterSi = filter.service.info;
11041            for (int i=dest.size()-1; i>=0; i--) {
11042                ServiceInfo destAi = dest.get(i).serviceInfo;
11043                if (destAi.name == filterSi.name
11044                        && destAi.packageName == filterSi.packageName) {
11045                    return false;
11046                }
11047            }
11048            return true;
11049        }
11050
11051        @Override
11052        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11053            return new PackageParser.ServiceIntentInfo[size];
11054        }
11055
11056        @Override
11057        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11058            if (!sUserManager.exists(userId)) return true;
11059            PackageParser.Package p = filter.service.owner;
11060            if (p != null) {
11061                PackageSetting ps = (PackageSetting)p.mExtras;
11062                if (ps != null) {
11063                    // System apps are never considered stopped for purposes of
11064                    // filtering, because there may be no way for the user to
11065                    // actually re-launch them.
11066                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11067                            && ps.getStopped(userId);
11068                }
11069            }
11070            return false;
11071        }
11072
11073        @Override
11074        protected boolean isPackageForFilter(String packageName,
11075                PackageParser.ServiceIntentInfo info) {
11076            return packageName.equals(info.service.owner.packageName);
11077        }
11078
11079        @Override
11080        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11081                int match, int userId) {
11082            if (!sUserManager.exists(userId)) return null;
11083            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11084            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11085                return null;
11086            }
11087            final PackageParser.Service service = info.service;
11088            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11089            if (ps == null) {
11090                return null;
11091            }
11092            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11093                    ps.readUserState(userId), userId);
11094            if (si == null) {
11095                return null;
11096            }
11097            final ResolveInfo res = new ResolveInfo();
11098            res.serviceInfo = si;
11099            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11100                res.filter = filter;
11101            }
11102            res.priority = info.getPriority();
11103            res.preferredOrder = service.owner.mPreferredOrder;
11104            res.match = match;
11105            res.isDefault = info.hasDefault;
11106            res.labelRes = info.labelRes;
11107            res.nonLocalizedLabel = info.nonLocalizedLabel;
11108            res.icon = info.icon;
11109            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11110            return res;
11111        }
11112
11113        @Override
11114        protected void sortResults(List<ResolveInfo> results) {
11115            Collections.sort(results, mResolvePrioritySorter);
11116        }
11117
11118        @Override
11119        protected void dumpFilter(PrintWriter out, String prefix,
11120                PackageParser.ServiceIntentInfo filter) {
11121            out.print(prefix); out.print(
11122                    Integer.toHexString(System.identityHashCode(filter.service)));
11123                    out.print(' ');
11124                    filter.service.printComponentShortName(out);
11125                    out.print(" filter ");
11126                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11127        }
11128
11129        @Override
11130        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11131            return filter.service;
11132        }
11133
11134        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11135            PackageParser.Service service = (PackageParser.Service)label;
11136            out.print(prefix); out.print(
11137                    Integer.toHexString(System.identityHashCode(service)));
11138                    out.print(' ');
11139                    service.printComponentShortName(out);
11140            if (count > 1) {
11141                out.print(" ("); out.print(count); out.print(" filters)");
11142            }
11143            out.println();
11144        }
11145
11146//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11147//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11148//            final List<ResolveInfo> retList = Lists.newArrayList();
11149//            while (i.hasNext()) {
11150//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11151//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11152//                    retList.add(resolveInfo);
11153//                }
11154//            }
11155//            return retList;
11156//        }
11157
11158        // Keys are String (activity class name), values are Activity.
11159        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11160                = new ArrayMap<ComponentName, PackageParser.Service>();
11161        private int mFlags;
11162    };
11163
11164    private final class ProviderIntentResolver
11165            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11166        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11167                boolean defaultOnly, int userId) {
11168            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11169            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11170        }
11171
11172        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11173                int userId) {
11174            if (!sUserManager.exists(userId))
11175                return null;
11176            mFlags = flags;
11177            return super.queryIntent(intent, resolvedType,
11178                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11179        }
11180
11181        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11182                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11183            if (!sUserManager.exists(userId))
11184                return null;
11185            if (packageProviders == null) {
11186                return null;
11187            }
11188            mFlags = flags;
11189            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11190            final int N = packageProviders.size();
11191            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11192                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11193
11194            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11195            for (int i = 0; i < N; ++i) {
11196                intentFilters = packageProviders.get(i).intents;
11197                if (intentFilters != null && intentFilters.size() > 0) {
11198                    PackageParser.ProviderIntentInfo[] array =
11199                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11200                    intentFilters.toArray(array);
11201                    listCut.add(array);
11202                }
11203            }
11204            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11205        }
11206
11207        public final void addProvider(PackageParser.Provider p) {
11208            if (mProviders.containsKey(p.getComponentName())) {
11209                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11210                return;
11211            }
11212
11213            mProviders.put(p.getComponentName(), p);
11214            if (DEBUG_SHOW_INFO) {
11215                Log.v(TAG, "  "
11216                        + (p.info.nonLocalizedLabel != null
11217                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11218                Log.v(TAG, "    Class=" + p.info.name);
11219            }
11220            final int NI = p.intents.size();
11221            int j;
11222            for (j = 0; j < NI; j++) {
11223                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11224                if (DEBUG_SHOW_INFO) {
11225                    Log.v(TAG, "    IntentFilter:");
11226                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11227                }
11228                if (!intent.debugCheck()) {
11229                    Log.w(TAG, "==> For Provider " + p.info.name);
11230                }
11231                addFilter(intent);
11232            }
11233        }
11234
11235        public final void removeProvider(PackageParser.Provider p) {
11236            mProviders.remove(p.getComponentName());
11237            if (DEBUG_SHOW_INFO) {
11238                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11239                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11240                Log.v(TAG, "    Class=" + p.info.name);
11241            }
11242            final int NI = p.intents.size();
11243            int j;
11244            for (j = 0; j < NI; j++) {
11245                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11246                if (DEBUG_SHOW_INFO) {
11247                    Log.v(TAG, "    IntentFilter:");
11248                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11249                }
11250                removeFilter(intent);
11251            }
11252        }
11253
11254        @Override
11255        protected boolean allowFilterResult(
11256                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11257            ProviderInfo filterPi = filter.provider.info;
11258            for (int i = dest.size() - 1; i >= 0; i--) {
11259                ProviderInfo destPi = dest.get(i).providerInfo;
11260                if (destPi.name == filterPi.name
11261                        && destPi.packageName == filterPi.packageName) {
11262                    return false;
11263                }
11264            }
11265            return true;
11266        }
11267
11268        @Override
11269        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11270            return new PackageParser.ProviderIntentInfo[size];
11271        }
11272
11273        @Override
11274        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11275            if (!sUserManager.exists(userId))
11276                return true;
11277            PackageParser.Package p = filter.provider.owner;
11278            if (p != null) {
11279                PackageSetting ps = (PackageSetting) p.mExtras;
11280                if (ps != null) {
11281                    // System apps are never considered stopped for purposes of
11282                    // filtering, because there may be no way for the user to
11283                    // actually re-launch them.
11284                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11285                            && ps.getStopped(userId);
11286                }
11287            }
11288            return false;
11289        }
11290
11291        @Override
11292        protected boolean isPackageForFilter(String packageName,
11293                PackageParser.ProviderIntentInfo info) {
11294            return packageName.equals(info.provider.owner.packageName);
11295        }
11296
11297        @Override
11298        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11299                int match, int userId) {
11300            if (!sUserManager.exists(userId))
11301                return null;
11302            final PackageParser.ProviderIntentInfo info = filter;
11303            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11304                return null;
11305            }
11306            final PackageParser.Provider provider = info.provider;
11307            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11308            if (ps == null) {
11309                return null;
11310            }
11311            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11312                    ps.readUserState(userId), userId);
11313            if (pi == null) {
11314                return null;
11315            }
11316            final ResolveInfo res = new ResolveInfo();
11317            res.providerInfo = pi;
11318            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11319                res.filter = filter;
11320            }
11321            res.priority = info.getPriority();
11322            res.preferredOrder = provider.owner.mPreferredOrder;
11323            res.match = match;
11324            res.isDefault = info.hasDefault;
11325            res.labelRes = info.labelRes;
11326            res.nonLocalizedLabel = info.nonLocalizedLabel;
11327            res.icon = info.icon;
11328            res.system = res.providerInfo.applicationInfo.isSystemApp();
11329            return res;
11330        }
11331
11332        @Override
11333        protected void sortResults(List<ResolveInfo> results) {
11334            Collections.sort(results, mResolvePrioritySorter);
11335        }
11336
11337        @Override
11338        protected void dumpFilter(PrintWriter out, String prefix,
11339                PackageParser.ProviderIntentInfo filter) {
11340            out.print(prefix);
11341            out.print(
11342                    Integer.toHexString(System.identityHashCode(filter.provider)));
11343            out.print(' ');
11344            filter.provider.printComponentShortName(out);
11345            out.print(" filter ");
11346            out.println(Integer.toHexString(System.identityHashCode(filter)));
11347        }
11348
11349        @Override
11350        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11351            return filter.provider;
11352        }
11353
11354        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11355            PackageParser.Provider provider = (PackageParser.Provider)label;
11356            out.print(prefix); out.print(
11357                    Integer.toHexString(System.identityHashCode(provider)));
11358                    out.print(' ');
11359                    provider.printComponentShortName(out);
11360            if (count > 1) {
11361                out.print(" ("); out.print(count); out.print(" filters)");
11362            }
11363            out.println();
11364        }
11365
11366        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11367                = new ArrayMap<ComponentName, PackageParser.Provider>();
11368        private int mFlags;
11369    }
11370
11371    private static final class EphemeralIntentResolver
11372            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11373        @Override
11374        protected EphemeralResolveIntentInfo[] newArray(int size) {
11375            return new EphemeralResolveIntentInfo[size];
11376        }
11377
11378        @Override
11379        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11380            return true;
11381        }
11382
11383        @Override
11384        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11385                int userId) {
11386            if (!sUserManager.exists(userId)) {
11387                return null;
11388            }
11389            return info.getEphemeralResolveInfo();
11390        }
11391    }
11392
11393    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11394            new Comparator<ResolveInfo>() {
11395        public int compare(ResolveInfo r1, ResolveInfo r2) {
11396            int v1 = r1.priority;
11397            int v2 = r2.priority;
11398            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11399            if (v1 != v2) {
11400                return (v1 > v2) ? -1 : 1;
11401            }
11402            v1 = r1.preferredOrder;
11403            v2 = r2.preferredOrder;
11404            if (v1 != v2) {
11405                return (v1 > v2) ? -1 : 1;
11406            }
11407            if (r1.isDefault != r2.isDefault) {
11408                return r1.isDefault ? -1 : 1;
11409            }
11410            v1 = r1.match;
11411            v2 = r2.match;
11412            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11413            if (v1 != v2) {
11414                return (v1 > v2) ? -1 : 1;
11415            }
11416            if (r1.system != r2.system) {
11417                return r1.system ? -1 : 1;
11418            }
11419            if (r1.activityInfo != null) {
11420                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11421            }
11422            if (r1.serviceInfo != null) {
11423                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11424            }
11425            if (r1.providerInfo != null) {
11426                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11427            }
11428            return 0;
11429        }
11430    };
11431
11432    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11433            new Comparator<ProviderInfo>() {
11434        public int compare(ProviderInfo p1, ProviderInfo p2) {
11435            final int v1 = p1.initOrder;
11436            final int v2 = p2.initOrder;
11437            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11438        }
11439    };
11440
11441    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11442            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11443            final int[] userIds) {
11444        mHandler.post(new Runnable() {
11445            @Override
11446            public void run() {
11447                try {
11448                    final IActivityManager am = ActivityManagerNative.getDefault();
11449                    if (am == null) return;
11450                    final int[] resolvedUserIds;
11451                    if (userIds == null) {
11452                        resolvedUserIds = am.getRunningUserIds();
11453                    } else {
11454                        resolvedUserIds = userIds;
11455                    }
11456                    final ShortcutServiceInternal shortcutService =
11457                            LocalServices.getService(ShortcutServiceInternal.class);
11458
11459                    for (int id : resolvedUserIds) {
11460                        final Intent intent = new Intent(action,
11461                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11462                        if (extras != null) {
11463                            intent.putExtras(extras);
11464                        }
11465                        if (targetPkg != null) {
11466                            intent.setPackage(targetPkg);
11467                        }
11468                        // Modify the UID when posting to other users
11469                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11470                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11471                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11472                            intent.putExtra(Intent.EXTRA_UID, uid);
11473                        }
11474                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11475                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11476                        if (DEBUG_BROADCASTS) {
11477                            RuntimeException here = new RuntimeException("here");
11478                            here.fillInStackTrace();
11479                            Slog.d(TAG, "Sending to user " + id + ": "
11480                                    + intent.toShortString(false, true, false, false)
11481                                    + " " + intent.getExtras(), here);
11482                        }
11483                        // TODO b/29385425 Consider making lifecycle callbacks for this.
11484                        if (shortcutService != null) {
11485                            shortcutService.onPackageBroadcast(intent);
11486                        }
11487                        am.broadcastIntent(null, intent, null, finishedReceiver,
11488                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11489                                null, finishedReceiver != null, false, id);
11490                    }
11491                } catch (RemoteException ex) {
11492                }
11493            }
11494        });
11495    }
11496
11497    /**
11498     * Check if the external storage media is available. This is true if there
11499     * is a mounted external storage medium or if the external storage is
11500     * emulated.
11501     */
11502    private boolean isExternalMediaAvailable() {
11503        return mMediaMounted || Environment.isExternalStorageEmulated();
11504    }
11505
11506    @Override
11507    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11508        // writer
11509        synchronized (mPackages) {
11510            if (!isExternalMediaAvailable()) {
11511                // If the external storage is no longer mounted at this point,
11512                // the caller may not have been able to delete all of this
11513                // packages files and can not delete any more.  Bail.
11514                return null;
11515            }
11516            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11517            if (lastPackage != null) {
11518                pkgs.remove(lastPackage);
11519            }
11520            if (pkgs.size() > 0) {
11521                return pkgs.get(0);
11522            }
11523        }
11524        return null;
11525    }
11526
11527    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11528        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11529                userId, andCode ? 1 : 0, packageName);
11530        if (mSystemReady) {
11531            msg.sendToTarget();
11532        } else {
11533            if (mPostSystemReadyMessages == null) {
11534                mPostSystemReadyMessages = new ArrayList<>();
11535            }
11536            mPostSystemReadyMessages.add(msg);
11537        }
11538    }
11539
11540    void startCleaningPackages() {
11541        // reader
11542        if (!isExternalMediaAvailable()) {
11543            return;
11544        }
11545        synchronized (mPackages) {
11546            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11547                return;
11548            }
11549        }
11550        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11551        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11552        IActivityManager am = ActivityManagerNative.getDefault();
11553        if (am != null) {
11554            try {
11555                am.startService(null, intent, null, mContext.getOpPackageName(),
11556                        UserHandle.USER_SYSTEM);
11557            } catch (RemoteException e) {
11558            }
11559        }
11560    }
11561
11562    @Override
11563    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11564            int installFlags, String installerPackageName, int userId) {
11565        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11566
11567        final int callingUid = Binder.getCallingUid();
11568        enforceCrossUserPermission(callingUid, userId,
11569                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11570
11571        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11572            try {
11573                if (observer != null) {
11574                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11575                }
11576            } catch (RemoteException re) {
11577            }
11578            return;
11579        }
11580
11581        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11582            installFlags |= PackageManager.INSTALL_FROM_ADB;
11583
11584        } else {
11585            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11586            // about installerPackageName.
11587
11588            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11589            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11590        }
11591
11592        UserHandle user;
11593        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11594            user = UserHandle.ALL;
11595        } else {
11596            user = new UserHandle(userId);
11597        }
11598
11599        // Only system components can circumvent runtime permissions when installing.
11600        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11601                && mContext.checkCallingOrSelfPermission(Manifest.permission
11602                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11603            throw new SecurityException("You need the "
11604                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11605                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11606        }
11607
11608        final File originFile = new File(originPath);
11609        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11610
11611        final Message msg = mHandler.obtainMessage(INIT_COPY);
11612        final VerificationInfo verificationInfo = new VerificationInfo(
11613                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11614        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11615                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11616                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11617                null /*certificates*/);
11618        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11619        msg.obj = params;
11620
11621        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11622                System.identityHashCode(msg.obj));
11623        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11624                System.identityHashCode(msg.obj));
11625
11626        mHandler.sendMessage(msg);
11627    }
11628
11629    void installStage(String packageName, File stagedDir, String stagedCid,
11630            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11631            String installerPackageName, int installerUid, UserHandle user,
11632            Certificate[][] certificates) {
11633        if (DEBUG_EPHEMERAL) {
11634            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11635                Slog.d(TAG, "Ephemeral install of " + packageName);
11636            }
11637        }
11638        final VerificationInfo verificationInfo = new VerificationInfo(
11639                sessionParams.originatingUri, sessionParams.referrerUri,
11640                sessionParams.originatingUid, installerUid);
11641
11642        final OriginInfo origin;
11643        if (stagedDir != null) {
11644            origin = OriginInfo.fromStagedFile(stagedDir);
11645        } else {
11646            origin = OriginInfo.fromStagedContainer(stagedCid);
11647        }
11648
11649        final Message msg = mHandler.obtainMessage(INIT_COPY);
11650        final InstallParams params = new InstallParams(origin, null, observer,
11651                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11652                verificationInfo, user, sessionParams.abiOverride,
11653                sessionParams.grantedRuntimePermissions, certificates);
11654        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11655        msg.obj = params;
11656
11657        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11658                System.identityHashCode(msg.obj));
11659        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11660                System.identityHashCode(msg.obj));
11661
11662        mHandler.sendMessage(msg);
11663    }
11664
11665    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11666            int userId) {
11667        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11668        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11669    }
11670
11671    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11672            int appId, int userId) {
11673        Bundle extras = new Bundle(1);
11674        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11675
11676        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11677                packageName, extras, 0, null, null, new int[] {userId});
11678        try {
11679            IActivityManager am = ActivityManagerNative.getDefault();
11680            if (isSystem && am.isUserRunning(userId, 0)) {
11681                // The just-installed/enabled app is bundled on the system, so presumed
11682                // to be able to run automatically without needing an explicit launch.
11683                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11684                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11685                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11686                        .setPackage(packageName);
11687                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11688                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11689            }
11690        } catch (RemoteException e) {
11691            // shouldn't happen
11692            Slog.w(TAG, "Unable to bootstrap installed package", e);
11693        }
11694    }
11695
11696    @Override
11697    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11698            int userId) {
11699        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11700        PackageSetting pkgSetting;
11701        final int uid = Binder.getCallingUid();
11702        enforceCrossUserPermission(uid, userId,
11703                true /* requireFullPermission */, true /* checkShell */,
11704                "setApplicationHiddenSetting for user " + userId);
11705
11706        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11707            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11708            return false;
11709        }
11710
11711        long callingId = Binder.clearCallingIdentity();
11712        try {
11713            boolean sendAdded = false;
11714            boolean sendRemoved = false;
11715            // writer
11716            synchronized (mPackages) {
11717                pkgSetting = mSettings.mPackages.get(packageName);
11718                if (pkgSetting == null) {
11719                    return false;
11720                }
11721                // Only allow protected packages to hide themselves.
11722                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11723                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11724                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11725                    return false;
11726                }
11727                if (pkgSetting.getHidden(userId) != hidden) {
11728                    pkgSetting.setHidden(hidden, userId);
11729                    mSettings.writePackageRestrictionsLPr(userId);
11730                    if (hidden) {
11731                        sendRemoved = true;
11732                    } else {
11733                        sendAdded = true;
11734                    }
11735                }
11736            }
11737            if (sendAdded) {
11738                sendPackageAddedForUser(packageName, pkgSetting, userId);
11739                return true;
11740            }
11741            if (sendRemoved) {
11742                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11743                        "hiding pkg");
11744                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11745                return true;
11746            }
11747        } finally {
11748            Binder.restoreCallingIdentity(callingId);
11749        }
11750        return false;
11751    }
11752
11753    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11754            int userId) {
11755        final PackageRemovedInfo info = new PackageRemovedInfo();
11756        info.removedPackage = packageName;
11757        info.removedUsers = new int[] {userId};
11758        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11759        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11760    }
11761
11762    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11763        if (pkgList.length > 0) {
11764            Bundle extras = new Bundle(1);
11765            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11766
11767            sendPackageBroadcast(
11768                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11769                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11770                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11771                    new int[] {userId});
11772        }
11773    }
11774
11775    /**
11776     * Returns true if application is not found or there was an error. Otherwise it returns
11777     * the hidden state of the package for the given user.
11778     */
11779    @Override
11780    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11781        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11782        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11783                true /* requireFullPermission */, false /* checkShell */,
11784                "getApplicationHidden for user " + userId);
11785        PackageSetting pkgSetting;
11786        long callingId = Binder.clearCallingIdentity();
11787        try {
11788            // writer
11789            synchronized (mPackages) {
11790                pkgSetting = mSettings.mPackages.get(packageName);
11791                if (pkgSetting == null) {
11792                    return true;
11793                }
11794                return pkgSetting.getHidden(userId);
11795            }
11796        } finally {
11797            Binder.restoreCallingIdentity(callingId);
11798        }
11799    }
11800
11801    /**
11802     * @hide
11803     */
11804    @Override
11805    public int installExistingPackageAsUser(String packageName, int userId) {
11806        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11807                null);
11808        PackageSetting pkgSetting;
11809        final int uid = Binder.getCallingUid();
11810        enforceCrossUserPermission(uid, userId,
11811                true /* requireFullPermission */, true /* checkShell */,
11812                "installExistingPackage for user " + userId);
11813        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11814            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11815        }
11816
11817        long callingId = Binder.clearCallingIdentity();
11818        try {
11819            boolean installed = false;
11820
11821            // writer
11822            synchronized (mPackages) {
11823                pkgSetting = mSettings.mPackages.get(packageName);
11824                if (pkgSetting == null) {
11825                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11826                }
11827                if (!pkgSetting.getInstalled(userId)) {
11828                    pkgSetting.setInstalled(true, userId);
11829                    pkgSetting.setHidden(false, userId);
11830                    mSettings.writePackageRestrictionsLPr(userId);
11831                    installed = true;
11832                }
11833            }
11834
11835            if (installed) {
11836                if (pkgSetting.pkg != null) {
11837                    synchronized (mInstallLock) {
11838                        // We don't need to freeze for a brand new install
11839                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11840                    }
11841                }
11842                sendPackageAddedForUser(packageName, pkgSetting, userId);
11843            }
11844        } finally {
11845            Binder.restoreCallingIdentity(callingId);
11846        }
11847
11848        return PackageManager.INSTALL_SUCCEEDED;
11849    }
11850
11851    boolean isUserRestricted(int userId, String restrictionKey) {
11852        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11853        if (restrictions.getBoolean(restrictionKey, false)) {
11854            Log.w(TAG, "User is restricted: " + restrictionKey);
11855            return true;
11856        }
11857        return false;
11858    }
11859
11860    @Override
11861    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11862            int userId) {
11863        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11864        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11865                true /* requireFullPermission */, true /* checkShell */,
11866                "setPackagesSuspended for user " + userId);
11867
11868        if (ArrayUtils.isEmpty(packageNames)) {
11869            return packageNames;
11870        }
11871
11872        // List of package names for whom the suspended state has changed.
11873        List<String> changedPackages = new ArrayList<>(packageNames.length);
11874        // List of package names for whom the suspended state is not set as requested in this
11875        // method.
11876        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11877        long callingId = Binder.clearCallingIdentity();
11878        try {
11879            for (int i = 0; i < packageNames.length; i++) {
11880                String packageName = packageNames[i];
11881                boolean changed = false;
11882                final int appId;
11883                synchronized (mPackages) {
11884                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11885                    if (pkgSetting == null) {
11886                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11887                                + "\". Skipping suspending/un-suspending.");
11888                        unactionedPackages.add(packageName);
11889                        continue;
11890                    }
11891                    appId = pkgSetting.appId;
11892                    if (pkgSetting.getSuspended(userId) != suspended) {
11893                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11894                            unactionedPackages.add(packageName);
11895                            continue;
11896                        }
11897                        pkgSetting.setSuspended(suspended, userId);
11898                        mSettings.writePackageRestrictionsLPr(userId);
11899                        changed = true;
11900                        changedPackages.add(packageName);
11901                    }
11902                }
11903
11904                if (changed && suspended) {
11905                    killApplication(packageName, UserHandle.getUid(userId, appId),
11906                            "suspending package");
11907                }
11908            }
11909        } finally {
11910            Binder.restoreCallingIdentity(callingId);
11911        }
11912
11913        if (!changedPackages.isEmpty()) {
11914            sendPackagesSuspendedForUser(changedPackages.toArray(
11915                    new String[changedPackages.size()]), userId, suspended);
11916        }
11917
11918        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11919    }
11920
11921    @Override
11922    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11923        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11924                true /* requireFullPermission */, false /* checkShell */,
11925                "isPackageSuspendedForUser for user " + userId);
11926        synchronized (mPackages) {
11927            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11928            if (pkgSetting == null) {
11929                throw new IllegalArgumentException("Unknown target package: " + packageName);
11930            }
11931            return pkgSetting.getSuspended(userId);
11932        }
11933    }
11934
11935    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11936        if (isPackageDeviceAdmin(packageName, userId)) {
11937            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11938                    + "\": has an active device admin");
11939            return false;
11940        }
11941
11942        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11943        if (packageName.equals(activeLauncherPackageName)) {
11944            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11945                    + "\": contains the active launcher");
11946            return false;
11947        }
11948
11949        if (packageName.equals(mRequiredInstallerPackage)) {
11950            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11951                    + "\": required for package installation");
11952            return false;
11953        }
11954
11955        if (packageName.equals(mRequiredVerifierPackage)) {
11956            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11957                    + "\": required for package verification");
11958            return false;
11959        }
11960
11961        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11962            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11963                    + "\": is the default dialer");
11964            return false;
11965        }
11966
11967        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11968            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11969                    + "\": protected package");
11970            return false;
11971        }
11972
11973        return true;
11974    }
11975
11976    private String getActiveLauncherPackageName(int userId) {
11977        Intent intent = new Intent(Intent.ACTION_MAIN);
11978        intent.addCategory(Intent.CATEGORY_HOME);
11979        ResolveInfo resolveInfo = resolveIntent(
11980                intent,
11981                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11982                PackageManager.MATCH_DEFAULT_ONLY,
11983                userId);
11984
11985        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11986    }
11987
11988    private String getDefaultDialerPackageName(int userId) {
11989        synchronized (mPackages) {
11990            return mSettings.getDefaultDialerPackageNameLPw(userId);
11991        }
11992    }
11993
11994    @Override
11995    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11996        mContext.enforceCallingOrSelfPermission(
11997                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11998                "Only package verification agents can verify applications");
11999
12000        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12001        final PackageVerificationResponse response = new PackageVerificationResponse(
12002                verificationCode, Binder.getCallingUid());
12003        msg.arg1 = id;
12004        msg.obj = response;
12005        mHandler.sendMessage(msg);
12006    }
12007
12008    @Override
12009    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12010            long millisecondsToDelay) {
12011        mContext.enforceCallingOrSelfPermission(
12012                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12013                "Only package verification agents can extend verification timeouts");
12014
12015        final PackageVerificationState state = mPendingVerification.get(id);
12016        final PackageVerificationResponse response = new PackageVerificationResponse(
12017                verificationCodeAtTimeout, Binder.getCallingUid());
12018
12019        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12020            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12021        }
12022        if (millisecondsToDelay < 0) {
12023            millisecondsToDelay = 0;
12024        }
12025        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12026                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12027            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12028        }
12029
12030        if ((state != null) && !state.timeoutExtended()) {
12031            state.extendTimeout();
12032
12033            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12034            msg.arg1 = id;
12035            msg.obj = response;
12036            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12037        }
12038    }
12039
12040    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12041            int verificationCode, UserHandle user) {
12042        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12043        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12044        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12045        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12046        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12047
12048        mContext.sendBroadcastAsUser(intent, user,
12049                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12050    }
12051
12052    private ComponentName matchComponentForVerifier(String packageName,
12053            List<ResolveInfo> receivers) {
12054        ActivityInfo targetReceiver = null;
12055
12056        final int NR = receivers.size();
12057        for (int i = 0; i < NR; i++) {
12058            final ResolveInfo info = receivers.get(i);
12059            if (info.activityInfo == null) {
12060                continue;
12061            }
12062
12063            if (packageName.equals(info.activityInfo.packageName)) {
12064                targetReceiver = info.activityInfo;
12065                break;
12066            }
12067        }
12068
12069        if (targetReceiver == null) {
12070            return null;
12071        }
12072
12073        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12074    }
12075
12076    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12077            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12078        if (pkgInfo.verifiers.length == 0) {
12079            return null;
12080        }
12081
12082        final int N = pkgInfo.verifiers.length;
12083        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12084        for (int i = 0; i < N; i++) {
12085            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12086
12087            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12088                    receivers);
12089            if (comp == null) {
12090                continue;
12091            }
12092
12093            final int verifierUid = getUidForVerifier(verifierInfo);
12094            if (verifierUid == -1) {
12095                continue;
12096            }
12097
12098            if (DEBUG_VERIFY) {
12099                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12100                        + " with the correct signature");
12101            }
12102            sufficientVerifiers.add(comp);
12103            verificationState.addSufficientVerifier(verifierUid);
12104        }
12105
12106        return sufficientVerifiers;
12107    }
12108
12109    private int getUidForVerifier(VerifierInfo verifierInfo) {
12110        synchronized (mPackages) {
12111            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12112            if (pkg == null) {
12113                return -1;
12114            } else if (pkg.mSignatures.length != 1) {
12115                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12116                        + " has more than one signature; ignoring");
12117                return -1;
12118            }
12119
12120            /*
12121             * If the public key of the package's signature does not match
12122             * our expected public key, then this is a different package and
12123             * we should skip.
12124             */
12125
12126            final byte[] expectedPublicKey;
12127            try {
12128                final Signature verifierSig = pkg.mSignatures[0];
12129                final PublicKey publicKey = verifierSig.getPublicKey();
12130                expectedPublicKey = publicKey.getEncoded();
12131            } catch (CertificateException e) {
12132                return -1;
12133            }
12134
12135            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12136
12137            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12138                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12139                        + " does not have the expected public key; ignoring");
12140                return -1;
12141            }
12142
12143            return pkg.applicationInfo.uid;
12144        }
12145    }
12146
12147    @Override
12148    public void finishPackageInstall(int token, boolean didLaunch) {
12149        enforceSystemOrRoot("Only the system is allowed to finish installs");
12150
12151        if (DEBUG_INSTALL) {
12152            Slog.v(TAG, "BM finishing package install for " + token);
12153        }
12154        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12155
12156        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12157        mHandler.sendMessage(msg);
12158    }
12159
12160    /**
12161     * Get the verification agent timeout.
12162     *
12163     * @return verification timeout in milliseconds
12164     */
12165    private long getVerificationTimeout() {
12166        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12167                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12168                DEFAULT_VERIFICATION_TIMEOUT);
12169    }
12170
12171    /**
12172     * Get the default verification agent response code.
12173     *
12174     * @return default verification response code
12175     */
12176    private int getDefaultVerificationResponse() {
12177        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12178                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12179                DEFAULT_VERIFICATION_RESPONSE);
12180    }
12181
12182    /**
12183     * Check whether or not package verification has been enabled.
12184     *
12185     * @return true if verification should be performed
12186     */
12187    private boolean isVerificationEnabled(int userId, int installFlags) {
12188        if (!DEFAULT_VERIFY_ENABLE) {
12189            return false;
12190        }
12191        // Ephemeral apps don't get the full verification treatment
12192        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12193            if (DEBUG_EPHEMERAL) {
12194                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12195            }
12196            return false;
12197        }
12198
12199        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12200
12201        // Check if installing from ADB
12202        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12203            // Do not run verification in a test harness environment
12204            if (ActivityManager.isRunningInTestHarness()) {
12205                return false;
12206            }
12207            if (ensureVerifyAppsEnabled) {
12208                return true;
12209            }
12210            // Check if the developer does not want package verification for ADB installs
12211            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12212                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12213                return false;
12214            }
12215        }
12216
12217        if (ensureVerifyAppsEnabled) {
12218            return true;
12219        }
12220
12221        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12222                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12223    }
12224
12225    @Override
12226    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12227            throws RemoteException {
12228        mContext.enforceCallingOrSelfPermission(
12229                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12230                "Only intentfilter verification agents can verify applications");
12231
12232        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12233        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12234                Binder.getCallingUid(), verificationCode, failedDomains);
12235        msg.arg1 = id;
12236        msg.obj = response;
12237        mHandler.sendMessage(msg);
12238    }
12239
12240    @Override
12241    public int getIntentVerificationStatus(String packageName, int userId) {
12242        synchronized (mPackages) {
12243            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12244        }
12245    }
12246
12247    @Override
12248    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12249        mContext.enforceCallingOrSelfPermission(
12250                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12251
12252        boolean result = false;
12253        synchronized (mPackages) {
12254            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12255        }
12256        if (result) {
12257            scheduleWritePackageRestrictionsLocked(userId);
12258        }
12259        return result;
12260    }
12261
12262    @Override
12263    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12264            String packageName) {
12265        synchronized (mPackages) {
12266            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12267        }
12268    }
12269
12270    @Override
12271    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12272        if (TextUtils.isEmpty(packageName)) {
12273            return ParceledListSlice.emptyList();
12274        }
12275        synchronized (mPackages) {
12276            PackageParser.Package pkg = mPackages.get(packageName);
12277            if (pkg == null || pkg.activities == null) {
12278                return ParceledListSlice.emptyList();
12279            }
12280            final int count = pkg.activities.size();
12281            ArrayList<IntentFilter> result = new ArrayList<>();
12282            for (int n=0; n<count; n++) {
12283                PackageParser.Activity activity = pkg.activities.get(n);
12284                if (activity.intents != null && activity.intents.size() > 0) {
12285                    result.addAll(activity.intents);
12286                }
12287            }
12288            return new ParceledListSlice<>(result);
12289        }
12290    }
12291
12292    @Override
12293    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12294        mContext.enforceCallingOrSelfPermission(
12295                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12296
12297        synchronized (mPackages) {
12298            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12299            if (packageName != null) {
12300                result |= updateIntentVerificationStatus(packageName,
12301                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12302                        userId);
12303                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12304                        packageName, userId);
12305            }
12306            return result;
12307        }
12308    }
12309
12310    @Override
12311    public String getDefaultBrowserPackageName(int userId) {
12312        synchronized (mPackages) {
12313            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12314        }
12315    }
12316
12317    /**
12318     * Get the "allow unknown sources" setting.
12319     *
12320     * @return the current "allow unknown sources" setting
12321     */
12322    private int getUnknownSourcesSettings() {
12323        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12324                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12325                -1);
12326    }
12327
12328    @Override
12329    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12330        final int uid = Binder.getCallingUid();
12331        // writer
12332        synchronized (mPackages) {
12333            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12334            if (targetPackageSetting == null) {
12335                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12336            }
12337
12338            PackageSetting installerPackageSetting;
12339            if (installerPackageName != null) {
12340                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12341                if (installerPackageSetting == null) {
12342                    throw new IllegalArgumentException("Unknown installer package: "
12343                            + installerPackageName);
12344                }
12345            } else {
12346                installerPackageSetting = null;
12347            }
12348
12349            Signature[] callerSignature;
12350            Object obj = mSettings.getUserIdLPr(uid);
12351            if (obj != null) {
12352                if (obj instanceof SharedUserSetting) {
12353                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12354                } else if (obj instanceof PackageSetting) {
12355                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12356                } else {
12357                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12358                }
12359            } else {
12360                throw new SecurityException("Unknown calling UID: " + uid);
12361            }
12362
12363            // Verify: can't set installerPackageName to a package that is
12364            // not signed with the same cert as the caller.
12365            if (installerPackageSetting != null) {
12366                if (compareSignatures(callerSignature,
12367                        installerPackageSetting.signatures.mSignatures)
12368                        != PackageManager.SIGNATURE_MATCH) {
12369                    throw new SecurityException(
12370                            "Caller does not have same cert as new installer package "
12371                            + installerPackageName);
12372                }
12373            }
12374
12375            // Verify: if target already has an installer package, it must
12376            // be signed with the same cert as the caller.
12377            if (targetPackageSetting.installerPackageName != null) {
12378                PackageSetting setting = mSettings.mPackages.get(
12379                        targetPackageSetting.installerPackageName);
12380                // If the currently set package isn't valid, then it's always
12381                // okay to change it.
12382                if (setting != null) {
12383                    if (compareSignatures(callerSignature,
12384                            setting.signatures.mSignatures)
12385                            != PackageManager.SIGNATURE_MATCH) {
12386                        throw new SecurityException(
12387                                "Caller does not have same cert as old installer package "
12388                                + targetPackageSetting.installerPackageName);
12389                    }
12390                }
12391            }
12392
12393            // Okay!
12394            targetPackageSetting.installerPackageName = installerPackageName;
12395            if (installerPackageName != null) {
12396                mSettings.mInstallerPackages.add(installerPackageName);
12397            }
12398            scheduleWriteSettingsLocked();
12399        }
12400    }
12401
12402    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12403        // Queue up an async operation since the package installation may take a little while.
12404        mHandler.post(new Runnable() {
12405            public void run() {
12406                mHandler.removeCallbacks(this);
12407                 // Result object to be returned
12408                PackageInstalledInfo res = new PackageInstalledInfo();
12409                res.setReturnCode(currentStatus);
12410                res.uid = -1;
12411                res.pkg = null;
12412                res.removedInfo = null;
12413                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12414                    args.doPreInstall(res.returnCode);
12415                    synchronized (mInstallLock) {
12416                        installPackageTracedLI(args, res);
12417                    }
12418                    args.doPostInstall(res.returnCode, res.uid);
12419                }
12420
12421                // A restore should be performed at this point if (a) the install
12422                // succeeded, (b) the operation is not an update, and (c) the new
12423                // package has not opted out of backup participation.
12424                final boolean update = res.removedInfo != null
12425                        && res.removedInfo.removedPackage != null;
12426                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12427                boolean doRestore = !update
12428                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12429
12430                // Set up the post-install work request bookkeeping.  This will be used
12431                // and cleaned up by the post-install event handling regardless of whether
12432                // there's a restore pass performed.  Token values are >= 1.
12433                int token;
12434                if (mNextInstallToken < 0) mNextInstallToken = 1;
12435                token = mNextInstallToken++;
12436
12437                PostInstallData data = new PostInstallData(args, res);
12438                mRunningInstalls.put(token, data);
12439                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12440
12441                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12442                    // Pass responsibility to the Backup Manager.  It will perform a
12443                    // restore if appropriate, then pass responsibility back to the
12444                    // Package Manager to run the post-install observer callbacks
12445                    // and broadcasts.
12446                    IBackupManager bm = IBackupManager.Stub.asInterface(
12447                            ServiceManager.getService(Context.BACKUP_SERVICE));
12448                    if (bm != null) {
12449                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12450                                + " to BM for possible restore");
12451                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12452                        try {
12453                            // TODO: http://b/22388012
12454                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12455                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12456                            } else {
12457                                doRestore = false;
12458                            }
12459                        } catch (RemoteException e) {
12460                            // can't happen; the backup manager is local
12461                        } catch (Exception e) {
12462                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12463                            doRestore = false;
12464                        }
12465                    } else {
12466                        Slog.e(TAG, "Backup Manager not found!");
12467                        doRestore = false;
12468                    }
12469                }
12470
12471                if (!doRestore) {
12472                    // No restore possible, or the Backup Manager was mysteriously not
12473                    // available -- just fire the post-install work request directly.
12474                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12475
12476                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12477
12478                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12479                    mHandler.sendMessage(msg);
12480                }
12481            }
12482        });
12483    }
12484
12485    /**
12486     * Callback from PackageSettings whenever an app is first transitioned out of the
12487     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12488     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12489     * here whether the app is the target of an ongoing install, and only send the
12490     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12491     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12492     * handling.
12493     */
12494    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12495        // Serialize this with the rest of the install-process message chain.  In the
12496        // restore-at-install case, this Runnable will necessarily run before the
12497        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12498        // are coherent.  In the non-restore case, the app has already completed install
12499        // and been launched through some other means, so it is not in a problematic
12500        // state for observers to see the FIRST_LAUNCH signal.
12501        mHandler.post(new Runnable() {
12502            @Override
12503            public void run() {
12504                for (int i = 0; i < mRunningInstalls.size(); i++) {
12505                    final PostInstallData data = mRunningInstalls.valueAt(i);
12506                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12507                        // right package; but is it for the right user?
12508                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12509                            if (userId == data.res.newUsers[uIndex]) {
12510                                if (DEBUG_BACKUP) {
12511                                    Slog.i(TAG, "Package " + pkgName
12512                                            + " being restored so deferring FIRST_LAUNCH");
12513                                }
12514                                return;
12515                            }
12516                        }
12517                    }
12518                }
12519                // didn't find it, so not being restored
12520                if (DEBUG_BACKUP) {
12521                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12522                }
12523                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12524            }
12525        });
12526    }
12527
12528    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12529        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12530                installerPkg, null, userIds);
12531    }
12532
12533    private abstract class HandlerParams {
12534        private static final int MAX_RETRIES = 4;
12535
12536        /**
12537         * Number of times startCopy() has been attempted and had a non-fatal
12538         * error.
12539         */
12540        private int mRetries = 0;
12541
12542        /** User handle for the user requesting the information or installation. */
12543        private final UserHandle mUser;
12544        String traceMethod;
12545        int traceCookie;
12546
12547        HandlerParams(UserHandle user) {
12548            mUser = user;
12549        }
12550
12551        UserHandle getUser() {
12552            return mUser;
12553        }
12554
12555        HandlerParams setTraceMethod(String traceMethod) {
12556            this.traceMethod = traceMethod;
12557            return this;
12558        }
12559
12560        HandlerParams setTraceCookie(int traceCookie) {
12561            this.traceCookie = traceCookie;
12562            return this;
12563        }
12564
12565        final boolean startCopy() {
12566            boolean res;
12567            try {
12568                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12569
12570                if (++mRetries > MAX_RETRIES) {
12571                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12572                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12573                    handleServiceError();
12574                    return false;
12575                } else {
12576                    handleStartCopy();
12577                    res = true;
12578                }
12579            } catch (RemoteException e) {
12580                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12581                mHandler.sendEmptyMessage(MCS_RECONNECT);
12582                res = false;
12583            }
12584            handleReturnCode();
12585            return res;
12586        }
12587
12588        final void serviceError() {
12589            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12590            handleServiceError();
12591            handleReturnCode();
12592        }
12593
12594        abstract void handleStartCopy() throws RemoteException;
12595        abstract void handleServiceError();
12596        abstract void handleReturnCode();
12597    }
12598
12599    class MeasureParams extends HandlerParams {
12600        private final PackageStats mStats;
12601        private boolean mSuccess;
12602
12603        private final IPackageStatsObserver mObserver;
12604
12605        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12606            super(new UserHandle(stats.userHandle));
12607            mObserver = observer;
12608            mStats = stats;
12609        }
12610
12611        @Override
12612        public String toString() {
12613            return "MeasureParams{"
12614                + Integer.toHexString(System.identityHashCode(this))
12615                + " " + mStats.packageName + "}";
12616        }
12617
12618        @Override
12619        void handleStartCopy() throws RemoteException {
12620            synchronized (mInstallLock) {
12621                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12622            }
12623
12624            if (mSuccess) {
12625                boolean mounted = false;
12626                try {
12627                    final String status = Environment.getExternalStorageState();
12628                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12629                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12630                } catch (Exception e) {
12631                }
12632
12633                if (mounted) {
12634                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12635
12636                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12637                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12638
12639                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12640                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12641
12642                    // Always subtract cache size, since it's a subdirectory
12643                    mStats.externalDataSize -= mStats.externalCacheSize;
12644
12645                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12646                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12647
12648                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12649                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12650                }
12651            }
12652        }
12653
12654        @Override
12655        void handleReturnCode() {
12656            if (mObserver != null) {
12657                try {
12658                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12659                } catch (RemoteException e) {
12660                    Slog.i(TAG, "Observer no longer exists.");
12661                }
12662            }
12663        }
12664
12665        @Override
12666        void handleServiceError() {
12667            Slog.e(TAG, "Could not measure application " + mStats.packageName
12668                            + " external storage");
12669        }
12670    }
12671
12672    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12673            throws RemoteException {
12674        long result = 0;
12675        for (File path : paths) {
12676            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12677        }
12678        return result;
12679    }
12680
12681    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12682        for (File path : paths) {
12683            try {
12684                mcs.clearDirectory(path.getAbsolutePath());
12685            } catch (RemoteException e) {
12686            }
12687        }
12688    }
12689
12690    static class OriginInfo {
12691        /**
12692         * Location where install is coming from, before it has been
12693         * copied/renamed into place. This could be a single monolithic APK
12694         * file, or a cluster directory. This location may be untrusted.
12695         */
12696        final File file;
12697        final String cid;
12698
12699        /**
12700         * Flag indicating that {@link #file} or {@link #cid} has already been
12701         * staged, meaning downstream users don't need to defensively copy the
12702         * contents.
12703         */
12704        final boolean staged;
12705
12706        /**
12707         * Flag indicating that {@link #file} or {@link #cid} is an already
12708         * installed app that is being moved.
12709         */
12710        final boolean existing;
12711
12712        final String resolvedPath;
12713        final File resolvedFile;
12714
12715        static OriginInfo fromNothing() {
12716            return new OriginInfo(null, null, false, false);
12717        }
12718
12719        static OriginInfo fromUntrustedFile(File file) {
12720            return new OriginInfo(file, null, false, false);
12721        }
12722
12723        static OriginInfo fromExistingFile(File file) {
12724            return new OriginInfo(file, null, false, true);
12725        }
12726
12727        static OriginInfo fromStagedFile(File file) {
12728            return new OriginInfo(file, null, true, false);
12729        }
12730
12731        static OriginInfo fromStagedContainer(String cid) {
12732            return new OriginInfo(null, cid, true, false);
12733        }
12734
12735        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12736            this.file = file;
12737            this.cid = cid;
12738            this.staged = staged;
12739            this.existing = existing;
12740
12741            if (cid != null) {
12742                resolvedPath = PackageHelper.getSdDir(cid);
12743                resolvedFile = new File(resolvedPath);
12744            } else if (file != null) {
12745                resolvedPath = file.getAbsolutePath();
12746                resolvedFile = file;
12747            } else {
12748                resolvedPath = null;
12749                resolvedFile = null;
12750            }
12751        }
12752    }
12753
12754    static class MoveInfo {
12755        final int moveId;
12756        final String fromUuid;
12757        final String toUuid;
12758        final String packageName;
12759        final String dataAppName;
12760        final int appId;
12761        final String seinfo;
12762        final int targetSdkVersion;
12763
12764        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12765                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12766            this.moveId = moveId;
12767            this.fromUuid = fromUuid;
12768            this.toUuid = toUuid;
12769            this.packageName = packageName;
12770            this.dataAppName = dataAppName;
12771            this.appId = appId;
12772            this.seinfo = seinfo;
12773            this.targetSdkVersion = targetSdkVersion;
12774        }
12775    }
12776
12777    static class VerificationInfo {
12778        /** A constant used to indicate that a uid value is not present. */
12779        public static final int NO_UID = -1;
12780
12781        /** URI referencing where the package was downloaded from. */
12782        final Uri originatingUri;
12783
12784        /** HTTP referrer URI associated with the originatingURI. */
12785        final Uri referrer;
12786
12787        /** UID of the application that the install request originated from. */
12788        final int originatingUid;
12789
12790        /** UID of application requesting the install */
12791        final int installerUid;
12792
12793        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12794            this.originatingUri = originatingUri;
12795            this.referrer = referrer;
12796            this.originatingUid = originatingUid;
12797            this.installerUid = installerUid;
12798        }
12799    }
12800
12801    class InstallParams extends HandlerParams {
12802        final OriginInfo origin;
12803        final MoveInfo move;
12804        final IPackageInstallObserver2 observer;
12805        int installFlags;
12806        final String installerPackageName;
12807        final String volumeUuid;
12808        private InstallArgs mArgs;
12809        private int mRet;
12810        final String packageAbiOverride;
12811        final String[] grantedRuntimePermissions;
12812        final VerificationInfo verificationInfo;
12813        final Certificate[][] certificates;
12814
12815        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12816                int installFlags, String installerPackageName, String volumeUuid,
12817                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12818                String[] grantedPermissions, Certificate[][] certificates) {
12819            super(user);
12820            this.origin = origin;
12821            this.move = move;
12822            this.observer = observer;
12823            this.installFlags = installFlags;
12824            this.installerPackageName = installerPackageName;
12825            this.volumeUuid = volumeUuid;
12826            this.verificationInfo = verificationInfo;
12827            this.packageAbiOverride = packageAbiOverride;
12828            this.grantedRuntimePermissions = grantedPermissions;
12829            this.certificates = certificates;
12830        }
12831
12832        @Override
12833        public String toString() {
12834            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12835                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12836        }
12837
12838        private int installLocationPolicy(PackageInfoLite pkgLite) {
12839            String packageName = pkgLite.packageName;
12840            int installLocation = pkgLite.installLocation;
12841            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12842            // reader
12843            synchronized (mPackages) {
12844                // Currently installed package which the new package is attempting to replace or
12845                // null if no such package is installed.
12846                PackageParser.Package installedPkg = mPackages.get(packageName);
12847                // Package which currently owns the data which the new package will own if installed.
12848                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12849                // will be null whereas dataOwnerPkg will contain information about the package
12850                // which was uninstalled while keeping its data.
12851                PackageParser.Package dataOwnerPkg = installedPkg;
12852                if (dataOwnerPkg  == null) {
12853                    PackageSetting ps = mSettings.mPackages.get(packageName);
12854                    if (ps != null) {
12855                        dataOwnerPkg = ps.pkg;
12856                    }
12857                }
12858
12859                if (dataOwnerPkg != null) {
12860                    // If installed, the package will get access to data left on the device by its
12861                    // predecessor. As a security measure, this is permited only if this is not a
12862                    // version downgrade or if the predecessor package is marked as debuggable and
12863                    // a downgrade is explicitly requested.
12864                    //
12865                    // On debuggable platform builds, downgrades are permitted even for
12866                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12867                    // not offer security guarantees and thus it's OK to disable some security
12868                    // mechanisms to make debugging/testing easier on those builds. However, even on
12869                    // debuggable builds downgrades of packages are permitted only if requested via
12870                    // installFlags. This is because we aim to keep the behavior of debuggable
12871                    // platform builds as close as possible to the behavior of non-debuggable
12872                    // platform builds.
12873                    final boolean downgradeRequested =
12874                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12875                    final boolean packageDebuggable =
12876                                (dataOwnerPkg.applicationInfo.flags
12877                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12878                    final boolean downgradePermitted =
12879                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12880                    if (!downgradePermitted) {
12881                        try {
12882                            checkDowngrade(dataOwnerPkg, pkgLite);
12883                        } catch (PackageManagerException e) {
12884                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12885                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12886                        }
12887                    }
12888                }
12889
12890                if (installedPkg != null) {
12891                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12892                        // Check for updated system application.
12893                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12894                            if (onSd) {
12895                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12896                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12897                            }
12898                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12899                        } else {
12900                            if (onSd) {
12901                                // Install flag overrides everything.
12902                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12903                            }
12904                            // If current upgrade specifies particular preference
12905                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12906                                // Application explicitly specified internal.
12907                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12908                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12909                                // App explictly prefers external. Let policy decide
12910                            } else {
12911                                // Prefer previous location
12912                                if (isExternal(installedPkg)) {
12913                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12914                                }
12915                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12916                            }
12917                        }
12918                    } else {
12919                        // Invalid install. Return error code
12920                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12921                    }
12922                }
12923            }
12924            // All the special cases have been taken care of.
12925            // Return result based on recommended install location.
12926            if (onSd) {
12927                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12928            }
12929            return pkgLite.recommendedInstallLocation;
12930        }
12931
12932        /*
12933         * Invoke remote method to get package information and install
12934         * location values. Override install location based on default
12935         * policy if needed and then create install arguments based
12936         * on the install location.
12937         */
12938        public void handleStartCopy() throws RemoteException {
12939            int ret = PackageManager.INSTALL_SUCCEEDED;
12940
12941            // If we're already staged, we've firmly committed to an install location
12942            if (origin.staged) {
12943                if (origin.file != null) {
12944                    installFlags |= PackageManager.INSTALL_INTERNAL;
12945                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12946                } else if (origin.cid != null) {
12947                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12948                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12949                } else {
12950                    throw new IllegalStateException("Invalid stage location");
12951                }
12952            }
12953
12954            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12955            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12956            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12957            PackageInfoLite pkgLite = null;
12958
12959            if (onInt && onSd) {
12960                // Check if both bits are set.
12961                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12962                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12963            } else if (onSd && ephemeral) {
12964                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12965                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12966            } else {
12967                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12968                        packageAbiOverride);
12969
12970                if (DEBUG_EPHEMERAL && ephemeral) {
12971                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12972                }
12973
12974                /*
12975                 * If we have too little free space, try to free cache
12976                 * before giving up.
12977                 */
12978                if (!origin.staged && pkgLite.recommendedInstallLocation
12979                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12980                    // TODO: focus freeing disk space on the target device
12981                    final StorageManager storage = StorageManager.from(mContext);
12982                    final long lowThreshold = storage.getStorageLowBytes(
12983                            Environment.getDataDirectory());
12984
12985                    final long sizeBytes = mContainerService.calculateInstalledSize(
12986                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12987
12988                    try {
12989                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12990                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12991                                installFlags, packageAbiOverride);
12992                    } catch (InstallerException e) {
12993                        Slog.w(TAG, "Failed to free cache", e);
12994                    }
12995
12996                    /*
12997                     * The cache free must have deleted the file we
12998                     * downloaded to install.
12999                     *
13000                     * TODO: fix the "freeCache" call to not delete
13001                     *       the file we care about.
13002                     */
13003                    if (pkgLite.recommendedInstallLocation
13004                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13005                        pkgLite.recommendedInstallLocation
13006                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13007                    }
13008                }
13009            }
13010
13011            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13012                int loc = pkgLite.recommendedInstallLocation;
13013                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13014                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13015                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13016                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13017                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13018                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13019                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13020                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13021                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13022                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13023                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13024                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13025                } else {
13026                    // Override with defaults if needed.
13027                    loc = installLocationPolicy(pkgLite);
13028                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13029                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13030                    } else if (!onSd && !onInt) {
13031                        // Override install location with flags
13032                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13033                            // Set the flag to install on external media.
13034                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13035                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13036                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13037                            if (DEBUG_EPHEMERAL) {
13038                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13039                            }
13040                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13041                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13042                                    |PackageManager.INSTALL_INTERNAL);
13043                        } else {
13044                            // Make sure the flag for installing on external
13045                            // media is unset
13046                            installFlags |= PackageManager.INSTALL_INTERNAL;
13047                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13048                        }
13049                    }
13050                }
13051            }
13052
13053            final InstallArgs args = createInstallArgs(this);
13054            mArgs = args;
13055
13056            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13057                // TODO: http://b/22976637
13058                // Apps installed for "all" users use the device owner to verify the app
13059                UserHandle verifierUser = getUser();
13060                if (verifierUser == UserHandle.ALL) {
13061                    verifierUser = UserHandle.SYSTEM;
13062                }
13063
13064                /*
13065                 * Determine if we have any installed package verifiers. If we
13066                 * do, then we'll defer to them to verify the packages.
13067                 */
13068                final int requiredUid = mRequiredVerifierPackage == null ? -1
13069                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13070                                verifierUser.getIdentifier());
13071                if (!origin.existing && requiredUid != -1
13072                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13073                    final Intent verification = new Intent(
13074                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13075                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13076                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13077                            PACKAGE_MIME_TYPE);
13078                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13079
13080                    // Query all live verifiers based on current user state
13081                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13082                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13083
13084                    if (DEBUG_VERIFY) {
13085                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13086                                + verification.toString() + " with " + pkgLite.verifiers.length
13087                                + " optional verifiers");
13088                    }
13089
13090                    final int verificationId = mPendingVerificationToken++;
13091
13092                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13093
13094                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13095                            installerPackageName);
13096
13097                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13098                            installFlags);
13099
13100                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13101                            pkgLite.packageName);
13102
13103                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13104                            pkgLite.versionCode);
13105
13106                    if (verificationInfo != null) {
13107                        if (verificationInfo.originatingUri != null) {
13108                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13109                                    verificationInfo.originatingUri);
13110                        }
13111                        if (verificationInfo.referrer != null) {
13112                            verification.putExtra(Intent.EXTRA_REFERRER,
13113                                    verificationInfo.referrer);
13114                        }
13115                        if (verificationInfo.originatingUid >= 0) {
13116                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13117                                    verificationInfo.originatingUid);
13118                        }
13119                        if (verificationInfo.installerUid >= 0) {
13120                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13121                                    verificationInfo.installerUid);
13122                        }
13123                    }
13124
13125                    final PackageVerificationState verificationState = new PackageVerificationState(
13126                            requiredUid, args);
13127
13128                    mPendingVerification.append(verificationId, verificationState);
13129
13130                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13131                            receivers, verificationState);
13132
13133                    /*
13134                     * If any sufficient verifiers were listed in the package
13135                     * manifest, attempt to ask them.
13136                     */
13137                    if (sufficientVerifiers != null) {
13138                        final int N = sufficientVerifiers.size();
13139                        if (N == 0) {
13140                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13141                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13142                        } else {
13143                            for (int i = 0; i < N; i++) {
13144                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13145
13146                                final Intent sufficientIntent = new Intent(verification);
13147                                sufficientIntent.setComponent(verifierComponent);
13148                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13149                            }
13150                        }
13151                    }
13152
13153                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13154                            mRequiredVerifierPackage, receivers);
13155                    if (ret == PackageManager.INSTALL_SUCCEEDED
13156                            && mRequiredVerifierPackage != null) {
13157                        Trace.asyncTraceBegin(
13158                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13159                        /*
13160                         * Send the intent to the required verification agent,
13161                         * but only start the verification timeout after the
13162                         * target BroadcastReceivers have run.
13163                         */
13164                        verification.setComponent(requiredVerifierComponent);
13165                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13166                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13167                                new BroadcastReceiver() {
13168                                    @Override
13169                                    public void onReceive(Context context, Intent intent) {
13170                                        final Message msg = mHandler
13171                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13172                                        msg.arg1 = verificationId;
13173                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13174                                    }
13175                                }, null, 0, null, null);
13176
13177                        /*
13178                         * We don't want the copy to proceed until verification
13179                         * succeeds, so null out this field.
13180                         */
13181                        mArgs = null;
13182                    }
13183                } else {
13184                    /*
13185                     * No package verification is enabled, so immediately start
13186                     * the remote call to initiate copy using temporary file.
13187                     */
13188                    ret = args.copyApk(mContainerService, true);
13189                }
13190            }
13191
13192            mRet = ret;
13193        }
13194
13195        @Override
13196        void handleReturnCode() {
13197            // If mArgs is null, then MCS couldn't be reached. When it
13198            // reconnects, it will try again to install. At that point, this
13199            // will succeed.
13200            if (mArgs != null) {
13201                processPendingInstall(mArgs, mRet);
13202            }
13203        }
13204
13205        @Override
13206        void handleServiceError() {
13207            mArgs = createInstallArgs(this);
13208            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13209        }
13210
13211        public boolean isForwardLocked() {
13212            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13213        }
13214    }
13215
13216    /**
13217     * Used during creation of InstallArgs
13218     *
13219     * @param installFlags package installation flags
13220     * @return true if should be installed on external storage
13221     */
13222    private static boolean installOnExternalAsec(int installFlags) {
13223        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13224            return false;
13225        }
13226        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13227            return true;
13228        }
13229        return false;
13230    }
13231
13232    /**
13233     * Used during creation of InstallArgs
13234     *
13235     * @param installFlags package installation flags
13236     * @return true if should be installed as forward locked
13237     */
13238    private static boolean installForwardLocked(int installFlags) {
13239        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13240    }
13241
13242    private InstallArgs createInstallArgs(InstallParams params) {
13243        if (params.move != null) {
13244            return new MoveInstallArgs(params);
13245        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13246            return new AsecInstallArgs(params);
13247        } else {
13248            return new FileInstallArgs(params);
13249        }
13250    }
13251
13252    /**
13253     * Create args that describe an existing installed package. Typically used
13254     * when cleaning up old installs, or used as a move source.
13255     */
13256    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13257            String resourcePath, String[] instructionSets) {
13258        final boolean isInAsec;
13259        if (installOnExternalAsec(installFlags)) {
13260            /* Apps on SD card are always in ASEC containers. */
13261            isInAsec = true;
13262        } else if (installForwardLocked(installFlags)
13263                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13264            /*
13265             * Forward-locked apps are only in ASEC containers if they're the
13266             * new style
13267             */
13268            isInAsec = true;
13269        } else {
13270            isInAsec = false;
13271        }
13272
13273        if (isInAsec) {
13274            return new AsecInstallArgs(codePath, instructionSets,
13275                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13276        } else {
13277            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13278        }
13279    }
13280
13281    static abstract class InstallArgs {
13282        /** @see InstallParams#origin */
13283        final OriginInfo origin;
13284        /** @see InstallParams#move */
13285        final MoveInfo move;
13286
13287        final IPackageInstallObserver2 observer;
13288        // Always refers to PackageManager flags only
13289        final int installFlags;
13290        final String installerPackageName;
13291        final String volumeUuid;
13292        final UserHandle user;
13293        final String abiOverride;
13294        final String[] installGrantPermissions;
13295        /** If non-null, drop an async trace when the install completes */
13296        final String traceMethod;
13297        final int traceCookie;
13298        final Certificate[][] certificates;
13299
13300        // The list of instruction sets supported by this app. This is currently
13301        // only used during the rmdex() phase to clean up resources. We can get rid of this
13302        // if we move dex files under the common app path.
13303        /* nullable */ String[] instructionSets;
13304
13305        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13306                int installFlags, String installerPackageName, String volumeUuid,
13307                UserHandle user, String[] instructionSets,
13308                String abiOverride, String[] installGrantPermissions,
13309                String traceMethod, int traceCookie, Certificate[][] certificates) {
13310            this.origin = origin;
13311            this.move = move;
13312            this.installFlags = installFlags;
13313            this.observer = observer;
13314            this.installerPackageName = installerPackageName;
13315            this.volumeUuid = volumeUuid;
13316            this.user = user;
13317            this.instructionSets = instructionSets;
13318            this.abiOverride = abiOverride;
13319            this.installGrantPermissions = installGrantPermissions;
13320            this.traceMethod = traceMethod;
13321            this.traceCookie = traceCookie;
13322            this.certificates = certificates;
13323        }
13324
13325        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13326        abstract int doPreInstall(int status);
13327
13328        /**
13329         * Rename package into final resting place. All paths on the given
13330         * scanned package should be updated to reflect the rename.
13331         */
13332        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13333        abstract int doPostInstall(int status, int uid);
13334
13335        /** @see PackageSettingBase#codePathString */
13336        abstract String getCodePath();
13337        /** @see PackageSettingBase#resourcePathString */
13338        abstract String getResourcePath();
13339
13340        // Need installer lock especially for dex file removal.
13341        abstract void cleanUpResourcesLI();
13342        abstract boolean doPostDeleteLI(boolean delete);
13343
13344        /**
13345         * Called before the source arguments are copied. This is used mostly
13346         * for MoveParams when it needs to read the source file to put it in the
13347         * destination.
13348         */
13349        int doPreCopy() {
13350            return PackageManager.INSTALL_SUCCEEDED;
13351        }
13352
13353        /**
13354         * Called after the source arguments are copied. This is used mostly for
13355         * MoveParams when it needs to read the source file to put it in the
13356         * destination.
13357         */
13358        int doPostCopy(int uid) {
13359            return PackageManager.INSTALL_SUCCEEDED;
13360        }
13361
13362        protected boolean isFwdLocked() {
13363            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13364        }
13365
13366        protected boolean isExternalAsec() {
13367            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13368        }
13369
13370        protected boolean isEphemeral() {
13371            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13372        }
13373
13374        UserHandle getUser() {
13375            return user;
13376        }
13377    }
13378
13379    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13380        if (!allCodePaths.isEmpty()) {
13381            if (instructionSets == null) {
13382                throw new IllegalStateException("instructionSet == null");
13383            }
13384            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13385            for (String codePath : allCodePaths) {
13386                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13387                    try {
13388                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13389                    } catch (InstallerException ignored) {
13390                    }
13391                }
13392            }
13393        }
13394    }
13395
13396    /**
13397     * Logic to handle installation of non-ASEC applications, including copying
13398     * and renaming logic.
13399     */
13400    class FileInstallArgs extends InstallArgs {
13401        private File codeFile;
13402        private File resourceFile;
13403
13404        // Example topology:
13405        // /data/app/com.example/base.apk
13406        // /data/app/com.example/split_foo.apk
13407        // /data/app/com.example/lib/arm/libfoo.so
13408        // /data/app/com.example/lib/arm64/libfoo.so
13409        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13410
13411        /** New install */
13412        FileInstallArgs(InstallParams params) {
13413            super(params.origin, params.move, params.observer, params.installFlags,
13414                    params.installerPackageName, params.volumeUuid,
13415                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13416                    params.grantedRuntimePermissions,
13417                    params.traceMethod, params.traceCookie, params.certificates);
13418            if (isFwdLocked()) {
13419                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13420            }
13421        }
13422
13423        /** Existing install */
13424        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13425            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13426                    null, null, null, 0, null /*certificates*/);
13427            this.codeFile = (codePath != null) ? new File(codePath) : null;
13428            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13429        }
13430
13431        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13432            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13433            try {
13434                return doCopyApk(imcs, temp);
13435            } finally {
13436                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13437            }
13438        }
13439
13440        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13441            if (origin.staged) {
13442                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13443                codeFile = origin.file;
13444                resourceFile = origin.file;
13445                return PackageManager.INSTALL_SUCCEEDED;
13446            }
13447
13448            try {
13449                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13450                final File tempDir =
13451                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13452                codeFile = tempDir;
13453                resourceFile = tempDir;
13454            } catch (IOException e) {
13455                Slog.w(TAG, "Failed to create copy file: " + e);
13456                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13457            }
13458
13459            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13460                @Override
13461                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13462                    if (!FileUtils.isValidExtFilename(name)) {
13463                        throw new IllegalArgumentException("Invalid filename: " + name);
13464                    }
13465                    try {
13466                        final File file = new File(codeFile, name);
13467                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13468                                O_RDWR | O_CREAT, 0644);
13469                        Os.chmod(file.getAbsolutePath(), 0644);
13470                        return new ParcelFileDescriptor(fd);
13471                    } catch (ErrnoException e) {
13472                        throw new RemoteException("Failed to open: " + e.getMessage());
13473                    }
13474                }
13475            };
13476
13477            int ret = PackageManager.INSTALL_SUCCEEDED;
13478            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13479            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13480                Slog.e(TAG, "Failed to copy package");
13481                return ret;
13482            }
13483
13484            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13485            NativeLibraryHelper.Handle handle = null;
13486            try {
13487                handle = NativeLibraryHelper.Handle.create(codeFile);
13488                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13489                        abiOverride);
13490            } catch (IOException e) {
13491                Slog.e(TAG, "Copying native libraries failed", e);
13492                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13493            } finally {
13494                IoUtils.closeQuietly(handle);
13495            }
13496
13497            return ret;
13498        }
13499
13500        int doPreInstall(int status) {
13501            if (status != PackageManager.INSTALL_SUCCEEDED) {
13502                cleanUp();
13503            }
13504            return status;
13505        }
13506
13507        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13508            if (status != PackageManager.INSTALL_SUCCEEDED) {
13509                cleanUp();
13510                return false;
13511            }
13512
13513            final File targetDir = codeFile.getParentFile();
13514            final File beforeCodeFile = codeFile;
13515            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13516
13517            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13518            try {
13519                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13520            } catch (ErrnoException e) {
13521                Slog.w(TAG, "Failed to rename", e);
13522                return false;
13523            }
13524
13525            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13526                Slog.w(TAG, "Failed to restorecon");
13527                return false;
13528            }
13529
13530            // Reflect the rename internally
13531            codeFile = afterCodeFile;
13532            resourceFile = afterCodeFile;
13533
13534            // Reflect the rename in scanned details
13535            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13536            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13537                    afterCodeFile, pkg.baseCodePath));
13538            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13539                    afterCodeFile, pkg.splitCodePaths));
13540
13541            // Reflect the rename in app info
13542            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13543            pkg.setApplicationInfoCodePath(pkg.codePath);
13544            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13545            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13546            pkg.setApplicationInfoResourcePath(pkg.codePath);
13547            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13548            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13549
13550            return true;
13551        }
13552
13553        int doPostInstall(int status, int uid) {
13554            if (status != PackageManager.INSTALL_SUCCEEDED) {
13555                cleanUp();
13556            }
13557            return status;
13558        }
13559
13560        @Override
13561        String getCodePath() {
13562            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13563        }
13564
13565        @Override
13566        String getResourcePath() {
13567            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13568        }
13569
13570        private boolean cleanUp() {
13571            if (codeFile == null || !codeFile.exists()) {
13572                return false;
13573            }
13574
13575            removeCodePathLI(codeFile);
13576
13577            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13578                resourceFile.delete();
13579            }
13580
13581            return true;
13582        }
13583
13584        void cleanUpResourcesLI() {
13585            // Try enumerating all code paths before deleting
13586            List<String> allCodePaths = Collections.EMPTY_LIST;
13587            if (codeFile != null && codeFile.exists()) {
13588                try {
13589                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13590                    allCodePaths = pkg.getAllCodePaths();
13591                } catch (PackageParserException e) {
13592                    // Ignored; we tried our best
13593                }
13594            }
13595
13596            cleanUp();
13597            removeDexFiles(allCodePaths, instructionSets);
13598        }
13599
13600        boolean doPostDeleteLI(boolean delete) {
13601            // XXX err, shouldn't we respect the delete flag?
13602            cleanUpResourcesLI();
13603            return true;
13604        }
13605    }
13606
13607    private boolean isAsecExternal(String cid) {
13608        final String asecPath = PackageHelper.getSdFilesystem(cid);
13609        return !asecPath.startsWith(mAsecInternalPath);
13610    }
13611
13612    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13613            PackageManagerException {
13614        if (copyRet < 0) {
13615            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13616                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13617                throw new PackageManagerException(copyRet, message);
13618            }
13619        }
13620    }
13621
13622    /**
13623     * Extract the MountService "container ID" from the full code path of an
13624     * .apk.
13625     */
13626    static String cidFromCodePath(String fullCodePath) {
13627        int eidx = fullCodePath.lastIndexOf("/");
13628        String subStr1 = fullCodePath.substring(0, eidx);
13629        int sidx = subStr1.lastIndexOf("/");
13630        return subStr1.substring(sidx+1, eidx);
13631    }
13632
13633    /**
13634     * Logic to handle installation of ASEC applications, including copying and
13635     * renaming logic.
13636     */
13637    class AsecInstallArgs extends InstallArgs {
13638        static final String RES_FILE_NAME = "pkg.apk";
13639        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13640
13641        String cid;
13642        String packagePath;
13643        String resourcePath;
13644
13645        /** New install */
13646        AsecInstallArgs(InstallParams params) {
13647            super(params.origin, params.move, params.observer, params.installFlags,
13648                    params.installerPackageName, params.volumeUuid,
13649                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13650                    params.grantedRuntimePermissions,
13651                    params.traceMethod, params.traceCookie, params.certificates);
13652        }
13653
13654        /** Existing install */
13655        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13656                        boolean isExternal, boolean isForwardLocked) {
13657            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13658              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13659                    instructionSets, null, null, null, 0, null /*certificates*/);
13660            // Hackily pretend we're still looking at a full code path
13661            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13662                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13663            }
13664
13665            // Extract cid from fullCodePath
13666            int eidx = fullCodePath.lastIndexOf("/");
13667            String subStr1 = fullCodePath.substring(0, eidx);
13668            int sidx = subStr1.lastIndexOf("/");
13669            cid = subStr1.substring(sidx+1, eidx);
13670            setMountPath(subStr1);
13671        }
13672
13673        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13674            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13675              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13676                    instructionSets, null, null, null, 0, null /*certificates*/);
13677            this.cid = cid;
13678            setMountPath(PackageHelper.getSdDir(cid));
13679        }
13680
13681        void createCopyFile() {
13682            cid = mInstallerService.allocateExternalStageCidLegacy();
13683        }
13684
13685        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13686            if (origin.staged && origin.cid != null) {
13687                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13688                cid = origin.cid;
13689                setMountPath(PackageHelper.getSdDir(cid));
13690                return PackageManager.INSTALL_SUCCEEDED;
13691            }
13692
13693            if (temp) {
13694                createCopyFile();
13695            } else {
13696                /*
13697                 * Pre-emptively destroy the container since it's destroyed if
13698                 * copying fails due to it existing anyway.
13699                 */
13700                PackageHelper.destroySdDir(cid);
13701            }
13702
13703            final String newMountPath = imcs.copyPackageToContainer(
13704                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13705                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13706
13707            if (newMountPath != null) {
13708                setMountPath(newMountPath);
13709                return PackageManager.INSTALL_SUCCEEDED;
13710            } else {
13711                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13712            }
13713        }
13714
13715        @Override
13716        String getCodePath() {
13717            return packagePath;
13718        }
13719
13720        @Override
13721        String getResourcePath() {
13722            return resourcePath;
13723        }
13724
13725        int doPreInstall(int status) {
13726            if (status != PackageManager.INSTALL_SUCCEEDED) {
13727                // Destroy container
13728                PackageHelper.destroySdDir(cid);
13729            } else {
13730                boolean mounted = PackageHelper.isContainerMounted(cid);
13731                if (!mounted) {
13732                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13733                            Process.SYSTEM_UID);
13734                    if (newMountPath != null) {
13735                        setMountPath(newMountPath);
13736                    } else {
13737                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13738                    }
13739                }
13740            }
13741            return status;
13742        }
13743
13744        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13745            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13746            String newMountPath = null;
13747            if (PackageHelper.isContainerMounted(cid)) {
13748                // Unmount the container
13749                if (!PackageHelper.unMountSdDir(cid)) {
13750                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13751                    return false;
13752                }
13753            }
13754            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13755                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13756                        " which might be stale. Will try to clean up.");
13757                // Clean up the stale container and proceed to recreate.
13758                if (!PackageHelper.destroySdDir(newCacheId)) {
13759                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13760                    return false;
13761                }
13762                // Successfully cleaned up stale container. Try to rename again.
13763                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13764                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13765                            + " inspite of cleaning it up.");
13766                    return false;
13767                }
13768            }
13769            if (!PackageHelper.isContainerMounted(newCacheId)) {
13770                Slog.w(TAG, "Mounting container " + newCacheId);
13771                newMountPath = PackageHelper.mountSdDir(newCacheId,
13772                        getEncryptKey(), Process.SYSTEM_UID);
13773            } else {
13774                newMountPath = PackageHelper.getSdDir(newCacheId);
13775            }
13776            if (newMountPath == null) {
13777                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13778                return false;
13779            }
13780            Log.i(TAG, "Succesfully renamed " + cid +
13781                    " to " + newCacheId +
13782                    " at new path: " + newMountPath);
13783            cid = newCacheId;
13784
13785            final File beforeCodeFile = new File(packagePath);
13786            setMountPath(newMountPath);
13787            final File afterCodeFile = new File(packagePath);
13788
13789            // Reflect the rename in scanned details
13790            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13791            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13792                    afterCodeFile, pkg.baseCodePath));
13793            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13794                    afterCodeFile, pkg.splitCodePaths));
13795
13796            // Reflect the rename in app info
13797            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13798            pkg.setApplicationInfoCodePath(pkg.codePath);
13799            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13800            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13801            pkg.setApplicationInfoResourcePath(pkg.codePath);
13802            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13803            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13804
13805            return true;
13806        }
13807
13808        private void setMountPath(String mountPath) {
13809            final File mountFile = new File(mountPath);
13810
13811            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13812            if (monolithicFile.exists()) {
13813                packagePath = monolithicFile.getAbsolutePath();
13814                if (isFwdLocked()) {
13815                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13816                } else {
13817                    resourcePath = packagePath;
13818                }
13819            } else {
13820                packagePath = mountFile.getAbsolutePath();
13821                resourcePath = packagePath;
13822            }
13823        }
13824
13825        int doPostInstall(int status, int uid) {
13826            if (status != PackageManager.INSTALL_SUCCEEDED) {
13827                cleanUp();
13828            } else {
13829                final int groupOwner;
13830                final String protectedFile;
13831                if (isFwdLocked()) {
13832                    groupOwner = UserHandle.getSharedAppGid(uid);
13833                    protectedFile = RES_FILE_NAME;
13834                } else {
13835                    groupOwner = -1;
13836                    protectedFile = null;
13837                }
13838
13839                if (uid < Process.FIRST_APPLICATION_UID
13840                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13841                    Slog.e(TAG, "Failed to finalize " + cid);
13842                    PackageHelper.destroySdDir(cid);
13843                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13844                }
13845
13846                boolean mounted = PackageHelper.isContainerMounted(cid);
13847                if (!mounted) {
13848                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13849                }
13850            }
13851            return status;
13852        }
13853
13854        private void cleanUp() {
13855            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13856
13857            // Destroy secure container
13858            PackageHelper.destroySdDir(cid);
13859        }
13860
13861        private List<String> getAllCodePaths() {
13862            final File codeFile = new File(getCodePath());
13863            if (codeFile != null && codeFile.exists()) {
13864                try {
13865                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13866                    return pkg.getAllCodePaths();
13867                } catch (PackageParserException e) {
13868                    // Ignored; we tried our best
13869                }
13870            }
13871            return Collections.EMPTY_LIST;
13872        }
13873
13874        void cleanUpResourcesLI() {
13875            // Enumerate all code paths before deleting
13876            cleanUpResourcesLI(getAllCodePaths());
13877        }
13878
13879        private void cleanUpResourcesLI(List<String> allCodePaths) {
13880            cleanUp();
13881            removeDexFiles(allCodePaths, instructionSets);
13882        }
13883
13884        String getPackageName() {
13885            return getAsecPackageName(cid);
13886        }
13887
13888        boolean doPostDeleteLI(boolean delete) {
13889            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13890            final List<String> allCodePaths = getAllCodePaths();
13891            boolean mounted = PackageHelper.isContainerMounted(cid);
13892            if (mounted) {
13893                // Unmount first
13894                if (PackageHelper.unMountSdDir(cid)) {
13895                    mounted = false;
13896                }
13897            }
13898            if (!mounted && delete) {
13899                cleanUpResourcesLI(allCodePaths);
13900            }
13901            return !mounted;
13902        }
13903
13904        @Override
13905        int doPreCopy() {
13906            if (isFwdLocked()) {
13907                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13908                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13909                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13910                }
13911            }
13912
13913            return PackageManager.INSTALL_SUCCEEDED;
13914        }
13915
13916        @Override
13917        int doPostCopy(int uid) {
13918            if (isFwdLocked()) {
13919                if (uid < Process.FIRST_APPLICATION_UID
13920                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13921                                RES_FILE_NAME)) {
13922                    Slog.e(TAG, "Failed to finalize " + cid);
13923                    PackageHelper.destroySdDir(cid);
13924                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13925                }
13926            }
13927
13928            return PackageManager.INSTALL_SUCCEEDED;
13929        }
13930    }
13931
13932    /**
13933     * Logic to handle movement of existing installed applications.
13934     */
13935    class MoveInstallArgs extends InstallArgs {
13936        private File codeFile;
13937        private File resourceFile;
13938
13939        /** New install */
13940        MoveInstallArgs(InstallParams params) {
13941            super(params.origin, params.move, params.observer, params.installFlags,
13942                    params.installerPackageName, params.volumeUuid,
13943                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13944                    params.grantedRuntimePermissions,
13945                    params.traceMethod, params.traceCookie, params.certificates);
13946        }
13947
13948        int copyApk(IMediaContainerService imcs, boolean temp) {
13949            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13950                    + move.fromUuid + " to " + move.toUuid);
13951            synchronized (mInstaller) {
13952                try {
13953                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13954                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13955                } catch (InstallerException e) {
13956                    Slog.w(TAG, "Failed to move app", e);
13957                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13958                }
13959            }
13960
13961            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13962            resourceFile = codeFile;
13963            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13964
13965            return PackageManager.INSTALL_SUCCEEDED;
13966        }
13967
13968        int doPreInstall(int status) {
13969            if (status != PackageManager.INSTALL_SUCCEEDED) {
13970                cleanUp(move.toUuid);
13971            }
13972            return status;
13973        }
13974
13975        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13976            if (status != PackageManager.INSTALL_SUCCEEDED) {
13977                cleanUp(move.toUuid);
13978                return false;
13979            }
13980
13981            // Reflect the move in app info
13982            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13983            pkg.setApplicationInfoCodePath(pkg.codePath);
13984            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13985            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13986            pkg.setApplicationInfoResourcePath(pkg.codePath);
13987            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13988            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13989
13990            return true;
13991        }
13992
13993        int doPostInstall(int status, int uid) {
13994            if (status == PackageManager.INSTALL_SUCCEEDED) {
13995                cleanUp(move.fromUuid);
13996            } else {
13997                cleanUp(move.toUuid);
13998            }
13999            return status;
14000        }
14001
14002        @Override
14003        String getCodePath() {
14004            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14005        }
14006
14007        @Override
14008        String getResourcePath() {
14009            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14010        }
14011
14012        private boolean cleanUp(String volumeUuid) {
14013            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14014                    move.dataAppName);
14015            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14016            final int[] userIds = sUserManager.getUserIds();
14017            synchronized (mInstallLock) {
14018                // Clean up both app data and code
14019                // All package moves are frozen until finished
14020                for (int userId : userIds) {
14021                    try {
14022                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14023                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14024                    } catch (InstallerException e) {
14025                        Slog.w(TAG, String.valueOf(e));
14026                    }
14027                }
14028                removeCodePathLI(codeFile);
14029            }
14030            return true;
14031        }
14032
14033        void cleanUpResourcesLI() {
14034            throw new UnsupportedOperationException();
14035        }
14036
14037        boolean doPostDeleteLI(boolean delete) {
14038            throw new UnsupportedOperationException();
14039        }
14040    }
14041
14042    static String getAsecPackageName(String packageCid) {
14043        int idx = packageCid.lastIndexOf("-");
14044        if (idx == -1) {
14045            return packageCid;
14046        }
14047        return packageCid.substring(0, idx);
14048    }
14049
14050    // Utility method used to create code paths based on package name and available index.
14051    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14052        String idxStr = "";
14053        int idx = 1;
14054        // Fall back to default value of idx=1 if prefix is not
14055        // part of oldCodePath
14056        if (oldCodePath != null) {
14057            String subStr = oldCodePath;
14058            // Drop the suffix right away
14059            if (suffix != null && subStr.endsWith(suffix)) {
14060                subStr = subStr.substring(0, subStr.length() - suffix.length());
14061            }
14062            // If oldCodePath already contains prefix find out the
14063            // ending index to either increment or decrement.
14064            int sidx = subStr.lastIndexOf(prefix);
14065            if (sidx != -1) {
14066                subStr = subStr.substring(sidx + prefix.length());
14067                if (subStr != null) {
14068                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14069                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14070                    }
14071                    try {
14072                        idx = Integer.parseInt(subStr);
14073                        if (idx <= 1) {
14074                            idx++;
14075                        } else {
14076                            idx--;
14077                        }
14078                    } catch(NumberFormatException e) {
14079                    }
14080                }
14081            }
14082        }
14083        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14084        return prefix + idxStr;
14085    }
14086
14087    private File getNextCodePath(File targetDir, String packageName) {
14088        int suffix = 1;
14089        File result;
14090        do {
14091            result = new File(targetDir, packageName + "-" + suffix);
14092            suffix++;
14093        } while (result.exists());
14094        return result;
14095    }
14096
14097    // Utility method that returns the relative package path with respect
14098    // to the installation directory. Like say for /data/data/com.test-1.apk
14099    // string com.test-1 is returned.
14100    static String deriveCodePathName(String codePath) {
14101        if (codePath == null) {
14102            return null;
14103        }
14104        final File codeFile = new File(codePath);
14105        final String name = codeFile.getName();
14106        if (codeFile.isDirectory()) {
14107            return name;
14108        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14109            final int lastDot = name.lastIndexOf('.');
14110            return name.substring(0, lastDot);
14111        } else {
14112            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14113            return null;
14114        }
14115    }
14116
14117    static class PackageInstalledInfo {
14118        String name;
14119        int uid;
14120        // The set of users that originally had this package installed.
14121        int[] origUsers;
14122        // The set of users that now have this package installed.
14123        int[] newUsers;
14124        PackageParser.Package pkg;
14125        int returnCode;
14126        String returnMsg;
14127        PackageRemovedInfo removedInfo;
14128        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14129
14130        public void setError(int code, String msg) {
14131            setReturnCode(code);
14132            setReturnMessage(msg);
14133            Slog.w(TAG, msg);
14134        }
14135
14136        public void setError(String msg, PackageParserException e) {
14137            setReturnCode(e.error);
14138            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14139            Slog.w(TAG, msg, e);
14140        }
14141
14142        public void setError(String msg, PackageManagerException e) {
14143            returnCode = e.error;
14144            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14145            Slog.w(TAG, msg, e);
14146        }
14147
14148        public void setReturnCode(int returnCode) {
14149            this.returnCode = returnCode;
14150            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14151            for (int i = 0; i < childCount; i++) {
14152                addedChildPackages.valueAt(i).returnCode = returnCode;
14153            }
14154        }
14155
14156        private void setReturnMessage(String returnMsg) {
14157            this.returnMsg = returnMsg;
14158            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14159            for (int i = 0; i < childCount; i++) {
14160                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14161            }
14162        }
14163
14164        // In some error cases we want to convey more info back to the observer
14165        String origPackage;
14166        String origPermission;
14167    }
14168
14169    /*
14170     * Install a non-existing package.
14171     */
14172    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14173            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14174            PackageInstalledInfo res) {
14175        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14176
14177        // Remember this for later, in case we need to rollback this install
14178        String pkgName = pkg.packageName;
14179
14180        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14181
14182        synchronized(mPackages) {
14183            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14184                // A package with the same name is already installed, though
14185                // it has been renamed to an older name.  The package we
14186                // are trying to install should be installed as an update to
14187                // the existing one, but that has not been requested, so bail.
14188                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14189                        + " without first uninstalling package running as "
14190                        + mSettings.mRenamedPackages.get(pkgName));
14191                return;
14192            }
14193            if (mPackages.containsKey(pkgName)) {
14194                // Don't allow installation over an existing package with the same name.
14195                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14196                        + " without first uninstalling.");
14197                return;
14198            }
14199        }
14200
14201        try {
14202            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14203                    System.currentTimeMillis(), user);
14204
14205            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14206
14207            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14208                prepareAppDataAfterInstallLIF(newPackage);
14209
14210            } else {
14211                // Remove package from internal structures, but keep around any
14212                // data that might have already existed
14213                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14214                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14215            }
14216        } catch (PackageManagerException e) {
14217            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14218        }
14219
14220        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14221    }
14222
14223    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14224        // Can't rotate keys during boot or if sharedUser.
14225        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14226                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14227            return false;
14228        }
14229        // app is using upgradeKeySets; make sure all are valid
14230        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14231        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14232        for (int i = 0; i < upgradeKeySets.length; i++) {
14233            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14234                Slog.wtf(TAG, "Package "
14235                         + (oldPs.name != null ? oldPs.name : "<null>")
14236                         + " contains upgrade-key-set reference to unknown key-set: "
14237                         + upgradeKeySets[i]
14238                         + " reverting to signatures check.");
14239                return false;
14240            }
14241        }
14242        return true;
14243    }
14244
14245    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14246        // Upgrade keysets are being used.  Determine if new package has a superset of the
14247        // required keys.
14248        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14249        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14250        for (int i = 0; i < upgradeKeySets.length; i++) {
14251            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14252            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14253                return true;
14254            }
14255        }
14256        return false;
14257    }
14258
14259    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14260        try (DigestInputStream digestStream =
14261                new DigestInputStream(new FileInputStream(file), digest)) {
14262            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14263        }
14264    }
14265
14266    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14267            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14268        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14269
14270        final PackageParser.Package oldPackage;
14271        final String pkgName = pkg.packageName;
14272        final int[] allUsers;
14273        final int[] installedUsers;
14274
14275        synchronized(mPackages) {
14276            oldPackage = mPackages.get(pkgName);
14277            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14278
14279            // don't allow upgrade to target a release SDK from a pre-release SDK
14280            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14281                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14282            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14283                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14284            if (oldTargetsPreRelease
14285                    && !newTargetsPreRelease
14286                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14287                Slog.w(TAG, "Can't install package targeting released sdk");
14288                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14289                return;
14290            }
14291
14292            // don't allow an upgrade from full to ephemeral
14293            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14294            if (isEphemeral && !oldIsEphemeral) {
14295                // can't downgrade from full to ephemeral
14296                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14297                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14298                return;
14299            }
14300
14301            // verify signatures are valid
14302            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14303            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14304                if (!checkUpgradeKeySetLP(ps, pkg)) {
14305                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14306                            "New package not signed by keys specified by upgrade-keysets: "
14307                                    + pkgName);
14308                    return;
14309                }
14310            } else {
14311                // default to original signature matching
14312                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14313                        != PackageManager.SIGNATURE_MATCH) {
14314                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14315                            "New package has a different signature: " + pkgName);
14316                    return;
14317                }
14318            }
14319
14320            // don't allow a system upgrade unless the upgrade hash matches
14321            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14322                byte[] digestBytes = null;
14323                try {
14324                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14325                    updateDigest(digest, new File(pkg.baseCodePath));
14326                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14327                        for (String path : pkg.splitCodePaths) {
14328                            updateDigest(digest, new File(path));
14329                        }
14330                    }
14331                    digestBytes = digest.digest();
14332                } catch (NoSuchAlgorithmException | IOException e) {
14333                    res.setError(INSTALL_FAILED_INVALID_APK,
14334                            "Could not compute hash: " + pkgName);
14335                    return;
14336                }
14337                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14338                    res.setError(INSTALL_FAILED_INVALID_APK,
14339                            "New package fails restrict-update check: " + pkgName);
14340                    return;
14341                }
14342                // retain upgrade restriction
14343                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14344            }
14345
14346            // Check for shared user id changes
14347            String invalidPackageName =
14348                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14349            if (invalidPackageName != null) {
14350                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14351                        "Package " + invalidPackageName + " tried to change user "
14352                                + oldPackage.mSharedUserId);
14353                return;
14354            }
14355
14356            // In case of rollback, remember per-user/profile install state
14357            allUsers = sUserManager.getUserIds();
14358            installedUsers = ps.queryInstalledUsers(allUsers, true);
14359        }
14360
14361        // Update what is removed
14362        res.removedInfo = new PackageRemovedInfo();
14363        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14364        res.removedInfo.removedPackage = oldPackage.packageName;
14365        res.removedInfo.isUpdate = true;
14366        res.removedInfo.origUsers = installedUsers;
14367        final int childCount = (oldPackage.childPackages != null)
14368                ? oldPackage.childPackages.size() : 0;
14369        for (int i = 0; i < childCount; i++) {
14370            boolean childPackageUpdated = false;
14371            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14372            if (res.addedChildPackages != null) {
14373                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14374                if (childRes != null) {
14375                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14376                    childRes.removedInfo.removedPackage = childPkg.packageName;
14377                    childRes.removedInfo.isUpdate = true;
14378                    childPackageUpdated = true;
14379                }
14380            }
14381            if (!childPackageUpdated) {
14382                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14383                childRemovedRes.removedPackage = childPkg.packageName;
14384                childRemovedRes.isUpdate = false;
14385                childRemovedRes.dataRemoved = true;
14386                synchronized (mPackages) {
14387                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14388                    if (childPs != null) {
14389                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14390                    }
14391                }
14392                if (res.removedInfo.removedChildPackages == null) {
14393                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14394                }
14395                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14396            }
14397        }
14398
14399        boolean sysPkg = (isSystemApp(oldPackage));
14400        if (sysPkg) {
14401            // Set the system/privileged flags as needed
14402            final boolean privileged =
14403                    (oldPackage.applicationInfo.privateFlags
14404                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14405            final int systemPolicyFlags = policyFlags
14406                    | PackageParser.PARSE_IS_SYSTEM
14407                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14408
14409            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14410                    user, allUsers, installerPackageName, res);
14411        } else {
14412            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14413                    user, allUsers, installerPackageName, res);
14414        }
14415    }
14416
14417    public List<String> getPreviousCodePaths(String packageName) {
14418        final PackageSetting ps = mSettings.mPackages.get(packageName);
14419        final List<String> result = new ArrayList<String>();
14420        if (ps != null && ps.oldCodePaths != null) {
14421            result.addAll(ps.oldCodePaths);
14422        }
14423        return result;
14424    }
14425
14426    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14427            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14428            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14429        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14430                + deletedPackage);
14431
14432        String pkgName = deletedPackage.packageName;
14433        boolean deletedPkg = true;
14434        boolean addedPkg = false;
14435        boolean updatedSettings = false;
14436        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14437        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14438                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14439
14440        final long origUpdateTime = (pkg.mExtras != null)
14441                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14442
14443        // First delete the existing package while retaining the data directory
14444        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14445                res.removedInfo, true, pkg)) {
14446            // If the existing package wasn't successfully deleted
14447            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14448            deletedPkg = false;
14449        } else {
14450            // Successfully deleted the old package; proceed with replace.
14451
14452            // If deleted package lived in a container, give users a chance to
14453            // relinquish resources before killing.
14454            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14455                if (DEBUG_INSTALL) {
14456                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14457                }
14458                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14459                final ArrayList<String> pkgList = new ArrayList<String>(1);
14460                pkgList.add(deletedPackage.applicationInfo.packageName);
14461                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14462            }
14463
14464            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14465                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14466            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14467
14468            try {
14469                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14470                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14471                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14472
14473                // Update the in-memory copy of the previous code paths.
14474                PackageSetting ps = mSettings.mPackages.get(pkgName);
14475                if (!killApp) {
14476                    if (ps.oldCodePaths == null) {
14477                        ps.oldCodePaths = new ArraySet<>();
14478                    }
14479                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14480                    if (deletedPackage.splitCodePaths != null) {
14481                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14482                    }
14483                } else {
14484                    ps.oldCodePaths = null;
14485                }
14486                if (ps.childPackageNames != null) {
14487                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14488                        final String childPkgName = ps.childPackageNames.get(i);
14489                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14490                        childPs.oldCodePaths = ps.oldCodePaths;
14491                    }
14492                }
14493                prepareAppDataAfterInstallLIF(newPackage);
14494                addedPkg = true;
14495            } catch (PackageManagerException e) {
14496                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14497            }
14498        }
14499
14500        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14501            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14502
14503            // Revert all internal state mutations and added folders for the failed install
14504            if (addedPkg) {
14505                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14506                        res.removedInfo, true, null);
14507            }
14508
14509            // Restore the old package
14510            if (deletedPkg) {
14511                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14512                File restoreFile = new File(deletedPackage.codePath);
14513                // Parse old package
14514                boolean oldExternal = isExternal(deletedPackage);
14515                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14516                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14517                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14518                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14519                try {
14520                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14521                            null);
14522                } catch (PackageManagerException e) {
14523                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14524                            + e.getMessage());
14525                    return;
14526                }
14527
14528                synchronized (mPackages) {
14529                    // Ensure the installer package name up to date
14530                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14531
14532                    // Update permissions for restored package
14533                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14534
14535                    mSettings.writeLPr();
14536                }
14537
14538                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14539            }
14540        } else {
14541            synchronized (mPackages) {
14542                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14543                if (ps != null) {
14544                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14545                    if (res.removedInfo.removedChildPackages != null) {
14546                        final int childCount = res.removedInfo.removedChildPackages.size();
14547                        // Iterate in reverse as we may modify the collection
14548                        for (int i = childCount - 1; i >= 0; i--) {
14549                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14550                            if (res.addedChildPackages.containsKey(childPackageName)) {
14551                                res.removedInfo.removedChildPackages.removeAt(i);
14552                            } else {
14553                                PackageRemovedInfo childInfo = res.removedInfo
14554                                        .removedChildPackages.valueAt(i);
14555                                childInfo.removedForAllUsers = mPackages.get(
14556                                        childInfo.removedPackage) == null;
14557                            }
14558                        }
14559                    }
14560                }
14561            }
14562        }
14563    }
14564
14565    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14566            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14567            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14568        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14569                + ", old=" + deletedPackage);
14570
14571        final boolean disabledSystem;
14572
14573        // Remove existing system package
14574        removePackageLI(deletedPackage, true);
14575
14576        synchronized (mPackages) {
14577            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14578        }
14579        if (!disabledSystem) {
14580            // We didn't need to disable the .apk as a current system package,
14581            // which means we are replacing another update that is already
14582            // installed.  We need to make sure to delete the older one's .apk.
14583            res.removedInfo.args = createInstallArgsForExisting(0,
14584                    deletedPackage.applicationInfo.getCodePath(),
14585                    deletedPackage.applicationInfo.getResourcePath(),
14586                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14587        } else {
14588            res.removedInfo.args = null;
14589        }
14590
14591        // Successfully disabled the old package. Now proceed with re-installation
14592        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14593                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14594        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14595
14596        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14597        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14598                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14599
14600        PackageParser.Package newPackage = null;
14601        try {
14602            // Add the package to the internal data structures
14603            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14604
14605            // Set the update and install times
14606            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14607            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14608                    System.currentTimeMillis());
14609
14610            // Update the package dynamic state if succeeded
14611            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14612                // Now that the install succeeded make sure we remove data
14613                // directories for any child package the update removed.
14614                final int deletedChildCount = (deletedPackage.childPackages != null)
14615                        ? deletedPackage.childPackages.size() : 0;
14616                final int newChildCount = (newPackage.childPackages != null)
14617                        ? newPackage.childPackages.size() : 0;
14618                for (int i = 0; i < deletedChildCount; i++) {
14619                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14620                    boolean childPackageDeleted = true;
14621                    for (int j = 0; j < newChildCount; j++) {
14622                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14623                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14624                            childPackageDeleted = false;
14625                            break;
14626                        }
14627                    }
14628                    if (childPackageDeleted) {
14629                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14630                                deletedChildPkg.packageName);
14631                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14632                            PackageRemovedInfo removedChildRes = res.removedInfo
14633                                    .removedChildPackages.get(deletedChildPkg.packageName);
14634                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14635                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14636                        }
14637                    }
14638                }
14639
14640                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14641                prepareAppDataAfterInstallLIF(newPackage);
14642            }
14643        } catch (PackageManagerException e) {
14644            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14645            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14646        }
14647
14648        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14649            // Re installation failed. Restore old information
14650            // Remove new pkg information
14651            if (newPackage != null) {
14652                removeInstalledPackageLI(newPackage, true);
14653            }
14654            // Add back the old system package
14655            try {
14656                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14657            } catch (PackageManagerException e) {
14658                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14659            }
14660
14661            synchronized (mPackages) {
14662                if (disabledSystem) {
14663                    enableSystemPackageLPw(deletedPackage);
14664                }
14665
14666                // Ensure the installer package name up to date
14667                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14668
14669                // Update permissions for restored package
14670                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14671
14672                mSettings.writeLPr();
14673            }
14674
14675            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14676                    + " after failed upgrade");
14677        }
14678    }
14679
14680    /**
14681     * Checks whether the parent or any of the child packages have a change shared
14682     * user. For a package to be a valid update the shred users of the parent and
14683     * the children should match. We may later support changing child shared users.
14684     * @param oldPkg The updated package.
14685     * @param newPkg The update package.
14686     * @return The shared user that change between the versions.
14687     */
14688    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14689            PackageParser.Package newPkg) {
14690        // Check parent shared user
14691        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14692            return newPkg.packageName;
14693        }
14694        // Check child shared users
14695        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14696        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14697        for (int i = 0; i < newChildCount; i++) {
14698            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14699            // If this child was present, did it have the same shared user?
14700            for (int j = 0; j < oldChildCount; j++) {
14701                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14702                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14703                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14704                    return newChildPkg.packageName;
14705                }
14706            }
14707        }
14708        return null;
14709    }
14710
14711    private void removeNativeBinariesLI(PackageSetting ps) {
14712        // Remove the lib path for the parent package
14713        if (ps != null) {
14714            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14715            // Remove the lib path for the child packages
14716            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14717            for (int i = 0; i < childCount; i++) {
14718                PackageSetting childPs = null;
14719                synchronized (mPackages) {
14720                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14721                }
14722                if (childPs != null) {
14723                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14724                            .legacyNativeLibraryPathString);
14725                }
14726            }
14727        }
14728    }
14729
14730    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14731        // Enable the parent package
14732        mSettings.enableSystemPackageLPw(pkg.packageName);
14733        // Enable the child packages
14734        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14735        for (int i = 0; i < childCount; i++) {
14736            PackageParser.Package childPkg = pkg.childPackages.get(i);
14737            mSettings.enableSystemPackageLPw(childPkg.packageName);
14738        }
14739    }
14740
14741    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14742            PackageParser.Package newPkg) {
14743        // Disable the parent package (parent always replaced)
14744        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14745        // Disable the child packages
14746        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14747        for (int i = 0; i < childCount; i++) {
14748            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14749            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14750            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14751        }
14752        return disabled;
14753    }
14754
14755    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14756            String installerPackageName) {
14757        // Enable the parent package
14758        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14759        // Enable the child packages
14760        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14761        for (int i = 0; i < childCount; i++) {
14762            PackageParser.Package childPkg = pkg.childPackages.get(i);
14763            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14764        }
14765    }
14766
14767    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14768        // Collect all used permissions in the UID
14769        ArraySet<String> usedPermissions = new ArraySet<>();
14770        final int packageCount = su.packages.size();
14771        for (int i = 0; i < packageCount; i++) {
14772            PackageSetting ps = su.packages.valueAt(i);
14773            if (ps.pkg == null) {
14774                continue;
14775            }
14776            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14777            for (int j = 0; j < requestedPermCount; j++) {
14778                String permission = ps.pkg.requestedPermissions.get(j);
14779                BasePermission bp = mSettings.mPermissions.get(permission);
14780                if (bp != null) {
14781                    usedPermissions.add(permission);
14782                }
14783            }
14784        }
14785
14786        PermissionsState permissionsState = su.getPermissionsState();
14787        // Prune install permissions
14788        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14789        final int installPermCount = installPermStates.size();
14790        for (int i = installPermCount - 1; i >= 0;  i--) {
14791            PermissionState permissionState = installPermStates.get(i);
14792            if (!usedPermissions.contains(permissionState.getName())) {
14793                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14794                if (bp != null) {
14795                    permissionsState.revokeInstallPermission(bp);
14796                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14797                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14798                }
14799            }
14800        }
14801
14802        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14803
14804        // Prune runtime permissions
14805        for (int userId : allUserIds) {
14806            List<PermissionState> runtimePermStates = permissionsState
14807                    .getRuntimePermissionStates(userId);
14808            final int runtimePermCount = runtimePermStates.size();
14809            for (int i = runtimePermCount - 1; i >= 0; i--) {
14810                PermissionState permissionState = runtimePermStates.get(i);
14811                if (!usedPermissions.contains(permissionState.getName())) {
14812                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14813                    if (bp != null) {
14814                        permissionsState.revokeRuntimePermission(bp, userId);
14815                        permissionsState.updatePermissionFlags(bp, userId,
14816                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14817                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14818                                runtimePermissionChangedUserIds, userId);
14819                    }
14820                }
14821            }
14822        }
14823
14824        return runtimePermissionChangedUserIds;
14825    }
14826
14827    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14828            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14829        // Update the parent package setting
14830        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14831                res, user);
14832        // Update the child packages setting
14833        final int childCount = (newPackage.childPackages != null)
14834                ? newPackage.childPackages.size() : 0;
14835        for (int i = 0; i < childCount; i++) {
14836            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14837            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14838            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14839                    childRes.origUsers, childRes, user);
14840        }
14841    }
14842
14843    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14844            String installerPackageName, int[] allUsers, int[] installedForUsers,
14845            PackageInstalledInfo res, UserHandle user) {
14846        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14847
14848        String pkgName = newPackage.packageName;
14849        synchronized (mPackages) {
14850            //write settings. the installStatus will be incomplete at this stage.
14851            //note that the new package setting would have already been
14852            //added to mPackages. It hasn't been persisted yet.
14853            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14854            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14855            mSettings.writeLPr();
14856            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14857        }
14858
14859        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14860        synchronized (mPackages) {
14861            updatePermissionsLPw(newPackage.packageName, newPackage,
14862                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14863                            ? UPDATE_PERMISSIONS_ALL : 0));
14864            // For system-bundled packages, we assume that installing an upgraded version
14865            // of the package implies that the user actually wants to run that new code,
14866            // so we enable the package.
14867            PackageSetting ps = mSettings.mPackages.get(pkgName);
14868            final int userId = user.getIdentifier();
14869            if (ps != null) {
14870                if (isSystemApp(newPackage)) {
14871                    if (DEBUG_INSTALL) {
14872                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14873                    }
14874                    // Enable system package for requested users
14875                    if (res.origUsers != null) {
14876                        for (int origUserId : res.origUsers) {
14877                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14878                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14879                                        origUserId, installerPackageName);
14880                            }
14881                        }
14882                    }
14883                    // Also convey the prior install/uninstall state
14884                    if (allUsers != null && installedForUsers != null) {
14885                        for (int currentUserId : allUsers) {
14886                            final boolean installed = ArrayUtils.contains(
14887                                    installedForUsers, currentUserId);
14888                            if (DEBUG_INSTALL) {
14889                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14890                            }
14891                            ps.setInstalled(installed, currentUserId);
14892                        }
14893                        // these install state changes will be persisted in the
14894                        // upcoming call to mSettings.writeLPr().
14895                    }
14896                }
14897                // It's implied that when a user requests installation, they want the app to be
14898                // installed and enabled.
14899                if (userId != UserHandle.USER_ALL) {
14900                    ps.setInstalled(true, userId);
14901                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14902                }
14903            }
14904            res.name = pkgName;
14905            res.uid = newPackage.applicationInfo.uid;
14906            res.pkg = newPackage;
14907            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14908            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14909            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14910            //to update install status
14911            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14912            mSettings.writeLPr();
14913            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14914        }
14915
14916        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14917    }
14918
14919    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14920        try {
14921            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14922            installPackageLI(args, res);
14923        } finally {
14924            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14925        }
14926    }
14927
14928    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14929        final int installFlags = args.installFlags;
14930        final String installerPackageName = args.installerPackageName;
14931        final String volumeUuid = args.volumeUuid;
14932        final File tmpPackageFile = new File(args.getCodePath());
14933        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14934        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14935                || (args.volumeUuid != null));
14936        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14937        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14938        boolean replace = false;
14939        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14940        if (args.move != null) {
14941            // moving a complete application; perform an initial scan on the new install location
14942            scanFlags |= SCAN_INITIAL;
14943        }
14944        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14945            scanFlags |= SCAN_DONT_KILL_APP;
14946        }
14947
14948        // Result object to be returned
14949        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14950
14951        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14952
14953        // Sanity check
14954        if (ephemeral && (forwardLocked || onExternal)) {
14955            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14956                    + " external=" + onExternal);
14957            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14958            return;
14959        }
14960
14961        // Retrieve PackageSettings and parse package
14962        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14963                | PackageParser.PARSE_ENFORCE_CODE
14964                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14965                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14966                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14967                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14968        PackageParser pp = new PackageParser();
14969        pp.setSeparateProcesses(mSeparateProcesses);
14970        pp.setDisplayMetrics(mMetrics);
14971
14972        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14973        final PackageParser.Package pkg;
14974        try {
14975            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14976        } catch (PackageParserException e) {
14977            res.setError("Failed parse during installPackageLI", e);
14978            return;
14979        } finally {
14980            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14981        }
14982
14983        // If we are installing a clustered package add results for the children
14984        if (pkg.childPackages != null) {
14985            synchronized (mPackages) {
14986                final int childCount = pkg.childPackages.size();
14987                for (int i = 0; i < childCount; i++) {
14988                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14989                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14990                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14991                    childRes.pkg = childPkg;
14992                    childRes.name = childPkg.packageName;
14993                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14994                    if (childPs != null) {
14995                        childRes.origUsers = childPs.queryInstalledUsers(
14996                                sUserManager.getUserIds(), true);
14997                    }
14998                    if ((mPackages.containsKey(childPkg.packageName))) {
14999                        childRes.removedInfo = new PackageRemovedInfo();
15000                        childRes.removedInfo.removedPackage = childPkg.packageName;
15001                    }
15002                    if (res.addedChildPackages == null) {
15003                        res.addedChildPackages = new ArrayMap<>();
15004                    }
15005                    res.addedChildPackages.put(childPkg.packageName, childRes);
15006                }
15007            }
15008        }
15009
15010        // If package doesn't declare API override, mark that we have an install
15011        // time CPU ABI override.
15012        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15013            pkg.cpuAbiOverride = args.abiOverride;
15014        }
15015
15016        String pkgName = res.name = pkg.packageName;
15017        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15018            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15019                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15020                return;
15021            }
15022        }
15023
15024        try {
15025            // either use what we've been given or parse directly from the APK
15026            if (args.certificates != null) {
15027                try {
15028                    PackageParser.populateCertificates(pkg, args.certificates);
15029                } catch (PackageParserException e) {
15030                    // there was something wrong with the certificates we were given;
15031                    // try to pull them from the APK
15032                    PackageParser.collectCertificates(pkg, parseFlags);
15033                }
15034            } else {
15035                PackageParser.collectCertificates(pkg, parseFlags);
15036            }
15037        } catch (PackageParserException e) {
15038            res.setError("Failed collect during installPackageLI", e);
15039            return;
15040        }
15041
15042        // Get rid of all references to package scan path via parser.
15043        pp = null;
15044        String oldCodePath = null;
15045        boolean systemApp = false;
15046        synchronized (mPackages) {
15047            // Check if installing already existing package
15048            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15049                String oldName = mSettings.mRenamedPackages.get(pkgName);
15050                if (pkg.mOriginalPackages != null
15051                        && pkg.mOriginalPackages.contains(oldName)
15052                        && mPackages.containsKey(oldName)) {
15053                    // This package is derived from an original package,
15054                    // and this device has been updating from that original
15055                    // name.  We must continue using the original name, so
15056                    // rename the new package here.
15057                    pkg.setPackageName(oldName);
15058                    pkgName = pkg.packageName;
15059                    replace = true;
15060                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15061                            + oldName + " pkgName=" + pkgName);
15062                } else if (mPackages.containsKey(pkgName)) {
15063                    // This package, under its official name, already exists
15064                    // on the device; we should replace it.
15065                    replace = true;
15066                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15067                }
15068
15069                // Child packages are installed through the parent package
15070                if (pkg.parentPackage != null) {
15071                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15072                            "Package " + pkg.packageName + " is child of package "
15073                                    + pkg.parentPackage.parentPackage + ". Child packages "
15074                                    + "can be updated only through the parent package.");
15075                    return;
15076                }
15077
15078                if (replace) {
15079                    // Prevent apps opting out from runtime permissions
15080                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15081                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15082                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15083                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15084                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15085                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15086                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15087                                        + " doesn't support runtime permissions but the old"
15088                                        + " target SDK " + oldTargetSdk + " does.");
15089                        return;
15090                    }
15091
15092                    // Prevent installing of child packages
15093                    if (oldPackage.parentPackage != null) {
15094                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15095                                "Package " + pkg.packageName + " is child of package "
15096                                        + oldPackage.parentPackage + ". Child packages "
15097                                        + "can be updated only through the parent package.");
15098                        return;
15099                    }
15100                }
15101            }
15102
15103            PackageSetting ps = mSettings.mPackages.get(pkgName);
15104            if (ps != null) {
15105                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15106
15107                // Quick sanity check that we're signed correctly if updating;
15108                // we'll check this again later when scanning, but we want to
15109                // bail early here before tripping over redefined permissions.
15110                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15111                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15112                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15113                                + pkg.packageName + " upgrade keys do not match the "
15114                                + "previously installed version");
15115                        return;
15116                    }
15117                } else {
15118                    try {
15119                        verifySignaturesLP(ps, pkg);
15120                    } catch (PackageManagerException e) {
15121                        res.setError(e.error, e.getMessage());
15122                        return;
15123                    }
15124                }
15125
15126                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15127                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15128                    systemApp = (ps.pkg.applicationInfo.flags &
15129                            ApplicationInfo.FLAG_SYSTEM) != 0;
15130                }
15131                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15132            }
15133
15134            // Check whether the newly-scanned package wants to define an already-defined perm
15135            int N = pkg.permissions.size();
15136            for (int i = N-1; i >= 0; i--) {
15137                PackageParser.Permission perm = pkg.permissions.get(i);
15138                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15139                if (bp != null) {
15140                    // If the defining package is signed with our cert, it's okay.  This
15141                    // also includes the "updating the same package" case, of course.
15142                    // "updating same package" could also involve key-rotation.
15143                    final boolean sigsOk;
15144                    if (bp.sourcePackage.equals(pkg.packageName)
15145                            && (bp.packageSetting instanceof PackageSetting)
15146                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15147                                    scanFlags))) {
15148                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15149                    } else {
15150                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15151                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15152                    }
15153                    if (!sigsOk) {
15154                        // If the owning package is the system itself, we log but allow
15155                        // install to proceed; we fail the install on all other permission
15156                        // redefinitions.
15157                        if (!bp.sourcePackage.equals("android")) {
15158                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15159                                    + pkg.packageName + " attempting to redeclare permission "
15160                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15161                            res.origPermission = perm.info.name;
15162                            res.origPackage = bp.sourcePackage;
15163                            return;
15164                        } else {
15165                            Slog.w(TAG, "Package " + pkg.packageName
15166                                    + " attempting to redeclare system permission "
15167                                    + perm.info.name + "; ignoring new declaration");
15168                            pkg.permissions.remove(i);
15169                        }
15170                    }
15171                }
15172            }
15173        }
15174
15175        if (systemApp) {
15176            if (onExternal) {
15177                // Abort update; system app can't be replaced with app on sdcard
15178                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15179                        "Cannot install updates to system apps on sdcard");
15180                return;
15181            } else if (ephemeral) {
15182                // Abort update; system app can't be replaced with an ephemeral app
15183                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15184                        "Cannot update a system app with an ephemeral app");
15185                return;
15186            }
15187        }
15188
15189        if (args.move != null) {
15190            // We did an in-place move, so dex is ready to roll
15191            scanFlags |= SCAN_NO_DEX;
15192            scanFlags |= SCAN_MOVE;
15193
15194            synchronized (mPackages) {
15195                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15196                if (ps == null) {
15197                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15198                            "Missing settings for moved package " + pkgName);
15199                }
15200
15201                // We moved the entire application as-is, so bring over the
15202                // previously derived ABI information.
15203                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15204                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15205            }
15206
15207        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15208            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15209            scanFlags |= SCAN_NO_DEX;
15210
15211            try {
15212                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15213                    args.abiOverride : pkg.cpuAbiOverride);
15214                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15215                        true /* extract libs */);
15216            } catch (PackageManagerException pme) {
15217                Slog.e(TAG, "Error deriving application ABI", pme);
15218                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15219                return;
15220            }
15221
15222            // Shared libraries for the package need to be updated.
15223            synchronized (mPackages) {
15224                try {
15225                    updateSharedLibrariesLPw(pkg, null);
15226                } catch (PackageManagerException e) {
15227                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15228                }
15229            }
15230            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15231            // Do not run PackageDexOptimizer through the local performDexOpt
15232            // method because `pkg` may not be in `mPackages` yet.
15233            //
15234            // Also, don't fail application installs if the dexopt step fails.
15235            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15236                    null /* instructionSets */, false /* checkProfiles */,
15237                    getCompilerFilterForReason(REASON_INSTALL));
15238            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15239
15240            // Notify BackgroundDexOptService that the package has been changed.
15241            // If this is an update of a package which used to fail to compile,
15242            // BDOS will remove it from its blacklist.
15243            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15244        }
15245
15246        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15247            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15248            return;
15249        }
15250
15251        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15252
15253        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15254                "installPackageLI")) {
15255            if (replace) {
15256                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15257                        installerPackageName, res);
15258            } else {
15259                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15260                        args.user, installerPackageName, volumeUuid, res);
15261            }
15262        }
15263        synchronized (mPackages) {
15264            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15265            if (ps != null) {
15266                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15267            }
15268
15269            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15270            for (int i = 0; i < childCount; i++) {
15271                PackageParser.Package childPkg = pkg.childPackages.get(i);
15272                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15273                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15274                if (childPs != null) {
15275                    childRes.newUsers = childPs.queryInstalledUsers(
15276                            sUserManager.getUserIds(), true);
15277                }
15278            }
15279        }
15280    }
15281
15282    private void startIntentFilterVerifications(int userId, boolean replacing,
15283            PackageParser.Package pkg) {
15284        if (mIntentFilterVerifierComponent == null) {
15285            Slog.w(TAG, "No IntentFilter verification will not be done as "
15286                    + "there is no IntentFilterVerifier available!");
15287            return;
15288        }
15289
15290        final int verifierUid = getPackageUid(
15291                mIntentFilterVerifierComponent.getPackageName(),
15292                MATCH_DEBUG_TRIAGED_MISSING,
15293                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15294
15295        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15296        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15297        mHandler.sendMessage(msg);
15298
15299        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15300        for (int i = 0; i < childCount; i++) {
15301            PackageParser.Package childPkg = pkg.childPackages.get(i);
15302            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15303            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15304            mHandler.sendMessage(msg);
15305        }
15306    }
15307
15308    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15309            PackageParser.Package pkg) {
15310        int size = pkg.activities.size();
15311        if (size == 0) {
15312            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15313                    "No activity, so no need to verify any IntentFilter!");
15314            return;
15315        }
15316
15317        final boolean hasDomainURLs = hasDomainURLs(pkg);
15318        if (!hasDomainURLs) {
15319            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15320                    "No domain URLs, so no need to verify any IntentFilter!");
15321            return;
15322        }
15323
15324        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15325                + " if any IntentFilter from the " + size
15326                + " Activities needs verification ...");
15327
15328        int count = 0;
15329        final String packageName = pkg.packageName;
15330
15331        synchronized (mPackages) {
15332            // If this is a new install and we see that we've already run verification for this
15333            // package, we have nothing to do: it means the state was restored from backup.
15334            if (!replacing) {
15335                IntentFilterVerificationInfo ivi =
15336                        mSettings.getIntentFilterVerificationLPr(packageName);
15337                if (ivi != null) {
15338                    if (DEBUG_DOMAIN_VERIFICATION) {
15339                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15340                                + ivi.getStatusString());
15341                    }
15342                    return;
15343                }
15344            }
15345
15346            // If any filters need to be verified, then all need to be.
15347            boolean needToVerify = false;
15348            for (PackageParser.Activity a : pkg.activities) {
15349                for (ActivityIntentInfo filter : a.intents) {
15350                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15351                        if (DEBUG_DOMAIN_VERIFICATION) {
15352                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15353                        }
15354                        needToVerify = true;
15355                        break;
15356                    }
15357                }
15358            }
15359
15360            if (needToVerify) {
15361                final int verificationId = mIntentFilterVerificationToken++;
15362                for (PackageParser.Activity a : pkg.activities) {
15363                    for (ActivityIntentInfo filter : a.intents) {
15364                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15365                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15366                                    "Verification needed for IntentFilter:" + filter.toString());
15367                            mIntentFilterVerifier.addOneIntentFilterVerification(
15368                                    verifierUid, userId, verificationId, filter, packageName);
15369                            count++;
15370                        }
15371                    }
15372                }
15373            }
15374        }
15375
15376        if (count > 0) {
15377            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15378                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15379                    +  " for userId:" + userId);
15380            mIntentFilterVerifier.startVerifications(userId);
15381        } else {
15382            if (DEBUG_DOMAIN_VERIFICATION) {
15383                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15384            }
15385        }
15386    }
15387
15388    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15389        final ComponentName cn  = filter.activity.getComponentName();
15390        final String packageName = cn.getPackageName();
15391
15392        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15393                packageName);
15394        if (ivi == null) {
15395            return true;
15396        }
15397        int status = ivi.getStatus();
15398        switch (status) {
15399            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15400            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15401                return true;
15402
15403            default:
15404                // Nothing to do
15405                return false;
15406        }
15407    }
15408
15409    private static boolean isMultiArch(ApplicationInfo info) {
15410        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15411    }
15412
15413    private static boolean isExternal(PackageParser.Package pkg) {
15414        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15415    }
15416
15417    private static boolean isExternal(PackageSetting ps) {
15418        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15419    }
15420
15421    private static boolean isEphemeral(PackageParser.Package pkg) {
15422        return pkg.applicationInfo.isEphemeralApp();
15423    }
15424
15425    private static boolean isEphemeral(PackageSetting ps) {
15426        return ps.pkg != null && isEphemeral(ps.pkg);
15427    }
15428
15429    private static boolean isSystemApp(PackageParser.Package pkg) {
15430        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15431    }
15432
15433    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15434        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15435    }
15436
15437    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15438        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15439    }
15440
15441    private static boolean isSystemApp(PackageSetting ps) {
15442        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15443    }
15444
15445    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15446        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15447    }
15448
15449    private int packageFlagsToInstallFlags(PackageSetting ps) {
15450        int installFlags = 0;
15451        if (isEphemeral(ps)) {
15452            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15453        }
15454        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15455            // This existing package was an external ASEC install when we have
15456            // the external flag without a UUID
15457            installFlags |= PackageManager.INSTALL_EXTERNAL;
15458        }
15459        if (ps.isForwardLocked()) {
15460            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15461        }
15462        return installFlags;
15463    }
15464
15465    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15466        if (isExternal(pkg)) {
15467            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15468                return StorageManager.UUID_PRIMARY_PHYSICAL;
15469            } else {
15470                return pkg.volumeUuid;
15471            }
15472        } else {
15473            return StorageManager.UUID_PRIVATE_INTERNAL;
15474        }
15475    }
15476
15477    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15478        if (isExternal(pkg)) {
15479            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15480                return mSettings.getExternalVersion();
15481            } else {
15482                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15483            }
15484        } else {
15485            return mSettings.getInternalVersion();
15486        }
15487    }
15488
15489    private void deleteTempPackageFiles() {
15490        final FilenameFilter filter = new FilenameFilter() {
15491            public boolean accept(File dir, String name) {
15492                return name.startsWith("vmdl") && name.endsWith(".tmp");
15493            }
15494        };
15495        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15496            file.delete();
15497        }
15498    }
15499
15500    @Override
15501    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15502            int flags) {
15503        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15504                flags);
15505    }
15506
15507    @Override
15508    public void deletePackage(final String packageName,
15509            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15510        mContext.enforceCallingOrSelfPermission(
15511                android.Manifest.permission.DELETE_PACKAGES, null);
15512        Preconditions.checkNotNull(packageName);
15513        Preconditions.checkNotNull(observer);
15514        final int uid = Binder.getCallingUid();
15515        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15516        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15517        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15518            mContext.enforceCallingOrSelfPermission(
15519                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15520                    "deletePackage for user " + userId);
15521        }
15522
15523        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15524            try {
15525                observer.onPackageDeleted(packageName,
15526                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15527            } catch (RemoteException re) {
15528            }
15529            return;
15530        }
15531
15532        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15533            try {
15534                observer.onPackageDeleted(packageName,
15535                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15536            } catch (RemoteException re) {
15537            }
15538            return;
15539        }
15540
15541        if (DEBUG_REMOVE) {
15542            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15543                    + " deleteAllUsers: " + deleteAllUsers );
15544        }
15545        // Queue up an async operation since the package deletion may take a little while.
15546        mHandler.post(new Runnable() {
15547            public void run() {
15548                mHandler.removeCallbacks(this);
15549                int returnCode;
15550                if (!deleteAllUsers) {
15551                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15552                } else {
15553                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15554                    // If nobody is blocking uninstall, proceed with delete for all users
15555                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15556                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15557                    } else {
15558                        // Otherwise uninstall individually for users with blockUninstalls=false
15559                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15560                        for (int userId : users) {
15561                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15562                                returnCode = deletePackageX(packageName, userId, userFlags);
15563                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15564                                    Slog.w(TAG, "Package delete failed for user " + userId
15565                                            + ", returnCode " + returnCode);
15566                                }
15567                            }
15568                        }
15569                        // The app has only been marked uninstalled for certain users.
15570                        // We still need to report that delete was blocked
15571                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15572                    }
15573                }
15574                try {
15575                    observer.onPackageDeleted(packageName, returnCode, null);
15576                } catch (RemoteException e) {
15577                    Log.i(TAG, "Observer no longer exists.");
15578                } //end catch
15579            } //end run
15580        });
15581    }
15582
15583    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15584        int[] result = EMPTY_INT_ARRAY;
15585        for (int userId : userIds) {
15586            if (getBlockUninstallForUser(packageName, userId)) {
15587                result = ArrayUtils.appendInt(result, userId);
15588            }
15589        }
15590        return result;
15591    }
15592
15593    @Override
15594    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15595        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15596    }
15597
15598    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15599        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15600                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15601        try {
15602            if (dpm != null) {
15603                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15604                        /* callingUserOnly =*/ false);
15605                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15606                        : deviceOwnerComponentName.getPackageName();
15607                // Does the package contains the device owner?
15608                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15609                // this check is probably not needed, since DO should be registered as a device
15610                // admin on some user too. (Original bug for this: b/17657954)
15611                if (packageName.equals(deviceOwnerPackageName)) {
15612                    return true;
15613                }
15614                // Does it contain a device admin for any user?
15615                int[] users;
15616                if (userId == UserHandle.USER_ALL) {
15617                    users = sUserManager.getUserIds();
15618                } else {
15619                    users = new int[]{userId};
15620                }
15621                for (int i = 0; i < users.length; ++i) {
15622                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15623                        return true;
15624                    }
15625                }
15626            }
15627        } catch (RemoteException e) {
15628        }
15629        return false;
15630    }
15631
15632    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15633        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15634    }
15635
15636    /**
15637     *  This method is an internal method that could be get invoked either
15638     *  to delete an installed package or to clean up a failed installation.
15639     *  After deleting an installed package, a broadcast is sent to notify any
15640     *  listeners that the package has been removed. For cleaning up a failed
15641     *  installation, the broadcast is not necessary since the package's
15642     *  installation wouldn't have sent the initial broadcast either
15643     *  The key steps in deleting a package are
15644     *  deleting the package information in internal structures like mPackages,
15645     *  deleting the packages base directories through installd
15646     *  updating mSettings to reflect current status
15647     *  persisting settings for later use
15648     *  sending a broadcast if necessary
15649     */
15650    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15651        final PackageRemovedInfo info = new PackageRemovedInfo();
15652        final boolean res;
15653
15654        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15655                ? UserHandle.USER_ALL : userId;
15656
15657        if (isPackageDeviceAdmin(packageName, removeUser)) {
15658            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15659            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15660        }
15661
15662        PackageSetting uninstalledPs = null;
15663
15664        // for the uninstall-updates case and restricted profiles, remember the per-
15665        // user handle installed state
15666        int[] allUsers;
15667        synchronized (mPackages) {
15668            uninstalledPs = mSettings.mPackages.get(packageName);
15669            if (uninstalledPs == null) {
15670                Slog.w(TAG, "Not removing non-existent package " + packageName);
15671                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15672            }
15673            allUsers = sUserManager.getUserIds();
15674            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15675        }
15676
15677        final int freezeUser;
15678        if (isUpdatedSystemApp(uninstalledPs)
15679                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15680            // We're downgrading a system app, which will apply to all users, so
15681            // freeze them all during the downgrade
15682            freezeUser = UserHandle.USER_ALL;
15683        } else {
15684            freezeUser = removeUser;
15685        }
15686
15687        synchronized (mInstallLock) {
15688            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15689            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15690                    deleteFlags, "deletePackageX")) {
15691                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15692                        deleteFlags | REMOVE_CHATTY, info, true, null);
15693            }
15694            synchronized (mPackages) {
15695                if (res) {
15696                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15697                }
15698            }
15699        }
15700
15701        if (res) {
15702            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15703            info.sendPackageRemovedBroadcasts(killApp);
15704            info.sendSystemPackageUpdatedBroadcasts();
15705            info.sendSystemPackageAppearedBroadcasts();
15706        }
15707        // Force a gc here.
15708        Runtime.getRuntime().gc();
15709        // Delete the resources here after sending the broadcast to let
15710        // other processes clean up before deleting resources.
15711        if (info.args != null) {
15712            synchronized (mInstallLock) {
15713                info.args.doPostDeleteLI(true);
15714            }
15715        }
15716
15717        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15718    }
15719
15720    class PackageRemovedInfo {
15721        String removedPackage;
15722        int uid = -1;
15723        int removedAppId = -1;
15724        int[] origUsers;
15725        int[] removedUsers = null;
15726        boolean isRemovedPackageSystemUpdate = false;
15727        boolean isUpdate;
15728        boolean dataRemoved;
15729        boolean removedForAllUsers;
15730        // Clean up resources deleted packages.
15731        InstallArgs args = null;
15732        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15733        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15734
15735        void sendPackageRemovedBroadcasts(boolean killApp) {
15736            sendPackageRemovedBroadcastInternal(killApp);
15737            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15738            for (int i = 0; i < childCount; i++) {
15739                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15740                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15741            }
15742        }
15743
15744        void sendSystemPackageUpdatedBroadcasts() {
15745            if (isRemovedPackageSystemUpdate) {
15746                sendSystemPackageUpdatedBroadcastsInternal();
15747                final int childCount = (removedChildPackages != null)
15748                        ? removedChildPackages.size() : 0;
15749                for (int i = 0; i < childCount; i++) {
15750                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15751                    if (childInfo.isRemovedPackageSystemUpdate) {
15752                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15753                    }
15754                }
15755            }
15756        }
15757
15758        void sendSystemPackageAppearedBroadcasts() {
15759            final int packageCount = (appearedChildPackages != null)
15760                    ? appearedChildPackages.size() : 0;
15761            for (int i = 0; i < packageCount; i++) {
15762                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15763                for (int userId : installedInfo.newUsers) {
15764                    sendPackageAddedForUser(installedInfo.name, true,
15765                            UserHandle.getAppId(installedInfo.uid), userId);
15766                }
15767            }
15768        }
15769
15770        private void sendSystemPackageUpdatedBroadcastsInternal() {
15771            Bundle extras = new Bundle(2);
15772            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15773            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15774            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15775                    extras, 0, null, null, null);
15776            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15777                    extras, 0, null, null, null);
15778            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15779                    null, 0, removedPackage, null, null);
15780        }
15781
15782        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15783            Bundle extras = new Bundle(2);
15784            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15785            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15786            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15787            if (isUpdate || isRemovedPackageSystemUpdate) {
15788                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15789            }
15790            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15791            if (removedPackage != null) {
15792                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15793                        extras, 0, null, null, removedUsers);
15794                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15795                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15796                            removedPackage, extras, 0, null, null, removedUsers);
15797                }
15798            }
15799            if (removedAppId >= 0) {
15800                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15801                        removedUsers);
15802            }
15803        }
15804    }
15805
15806    /*
15807     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15808     * flag is not set, the data directory is removed as well.
15809     * make sure this flag is set for partially installed apps. If not its meaningless to
15810     * delete a partially installed application.
15811     */
15812    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15813            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15814        String packageName = ps.name;
15815        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15816        // Retrieve object to delete permissions for shared user later on
15817        final PackageParser.Package deletedPkg;
15818        final PackageSetting deletedPs;
15819        // reader
15820        synchronized (mPackages) {
15821            deletedPkg = mPackages.get(packageName);
15822            deletedPs = mSettings.mPackages.get(packageName);
15823            if (outInfo != null) {
15824                outInfo.removedPackage = packageName;
15825                outInfo.removedUsers = deletedPs != null
15826                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15827                        : null;
15828            }
15829        }
15830
15831        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15832
15833        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15834            final PackageParser.Package resolvedPkg;
15835            if (deletedPkg != null) {
15836                resolvedPkg = deletedPkg;
15837            } else {
15838                // We don't have a parsed package when it lives on an ejected
15839                // adopted storage device, so fake something together
15840                resolvedPkg = new PackageParser.Package(ps.name);
15841                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15842            }
15843            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15844                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15845            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15846            if (outInfo != null) {
15847                outInfo.dataRemoved = true;
15848            }
15849            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15850        }
15851
15852        // writer
15853        synchronized (mPackages) {
15854            if (deletedPs != null) {
15855                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15856                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15857                    clearDefaultBrowserIfNeeded(packageName);
15858                    if (outInfo != null) {
15859                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15860                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15861                    }
15862                    updatePermissionsLPw(deletedPs.name, null, 0);
15863                    if (deletedPs.sharedUser != null) {
15864                        // Remove permissions associated with package. Since runtime
15865                        // permissions are per user we have to kill the removed package
15866                        // or packages running under the shared user of the removed
15867                        // package if revoking the permissions requested only by the removed
15868                        // package is successful and this causes a change in gids.
15869                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15870                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15871                                    userId);
15872                            if (userIdToKill == UserHandle.USER_ALL
15873                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15874                                // If gids changed for this user, kill all affected packages.
15875                                mHandler.post(new Runnable() {
15876                                    @Override
15877                                    public void run() {
15878                                        // This has to happen with no lock held.
15879                                        killApplication(deletedPs.name, deletedPs.appId,
15880                                                KILL_APP_REASON_GIDS_CHANGED);
15881                                    }
15882                                });
15883                                break;
15884                            }
15885                        }
15886                    }
15887                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15888                }
15889                // make sure to preserve per-user disabled state if this removal was just
15890                // a downgrade of a system app to the factory package
15891                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15892                    if (DEBUG_REMOVE) {
15893                        Slog.d(TAG, "Propagating install state across downgrade");
15894                    }
15895                    for (int userId : allUserHandles) {
15896                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15897                        if (DEBUG_REMOVE) {
15898                            Slog.d(TAG, "    user " + userId + " => " + installed);
15899                        }
15900                        ps.setInstalled(installed, userId);
15901                    }
15902                }
15903            }
15904            // can downgrade to reader
15905            if (writeSettings) {
15906                // Save settings now
15907                mSettings.writeLPr();
15908            }
15909        }
15910        if (outInfo != null) {
15911            // A user ID was deleted here. Go through all users and remove it
15912            // from KeyStore.
15913            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15914        }
15915    }
15916
15917    static boolean locationIsPrivileged(File path) {
15918        try {
15919            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15920                    .getCanonicalPath();
15921            return path.getCanonicalPath().startsWith(privilegedAppDir);
15922        } catch (IOException e) {
15923            Slog.e(TAG, "Unable to access code path " + path);
15924        }
15925        return false;
15926    }
15927
15928    /*
15929     * Tries to delete system package.
15930     */
15931    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15932            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15933            boolean writeSettings) {
15934        if (deletedPs.parentPackageName != null) {
15935            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15936            return false;
15937        }
15938
15939        final boolean applyUserRestrictions
15940                = (allUserHandles != null) && (outInfo.origUsers != null);
15941        final PackageSetting disabledPs;
15942        // Confirm if the system package has been updated
15943        // An updated system app can be deleted. This will also have to restore
15944        // the system pkg from system partition
15945        // reader
15946        synchronized (mPackages) {
15947            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15948        }
15949
15950        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15951                + " disabledPs=" + disabledPs);
15952
15953        if (disabledPs == null) {
15954            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15955            return false;
15956        } else if (DEBUG_REMOVE) {
15957            Slog.d(TAG, "Deleting system pkg from data partition");
15958        }
15959
15960        if (DEBUG_REMOVE) {
15961            if (applyUserRestrictions) {
15962                Slog.d(TAG, "Remembering install states:");
15963                for (int userId : allUserHandles) {
15964                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15965                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15966                }
15967            }
15968        }
15969
15970        // Delete the updated package
15971        outInfo.isRemovedPackageSystemUpdate = true;
15972        if (outInfo.removedChildPackages != null) {
15973            final int childCount = (deletedPs.childPackageNames != null)
15974                    ? deletedPs.childPackageNames.size() : 0;
15975            for (int i = 0; i < childCount; i++) {
15976                String childPackageName = deletedPs.childPackageNames.get(i);
15977                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15978                        .contains(childPackageName)) {
15979                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15980                            childPackageName);
15981                    if (childInfo != null) {
15982                        childInfo.isRemovedPackageSystemUpdate = true;
15983                    }
15984                }
15985            }
15986        }
15987
15988        if (disabledPs.versionCode < deletedPs.versionCode) {
15989            // Delete data for downgrades
15990            flags &= ~PackageManager.DELETE_KEEP_DATA;
15991        } else {
15992            // Preserve data by setting flag
15993            flags |= PackageManager.DELETE_KEEP_DATA;
15994        }
15995
15996        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15997                outInfo, writeSettings, disabledPs.pkg);
15998        if (!ret) {
15999            return false;
16000        }
16001
16002        // writer
16003        synchronized (mPackages) {
16004            // Reinstate the old system package
16005            enableSystemPackageLPw(disabledPs.pkg);
16006            // Remove any native libraries from the upgraded package.
16007            removeNativeBinariesLI(deletedPs);
16008        }
16009
16010        // Install the system package
16011        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16012        int parseFlags = mDefParseFlags
16013                | PackageParser.PARSE_MUST_BE_APK
16014                | PackageParser.PARSE_IS_SYSTEM
16015                | PackageParser.PARSE_IS_SYSTEM_DIR;
16016        if (locationIsPrivileged(disabledPs.codePath)) {
16017            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16018        }
16019
16020        final PackageParser.Package newPkg;
16021        try {
16022            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16023        } catch (PackageManagerException e) {
16024            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16025                    + e.getMessage());
16026            return false;
16027        }
16028
16029        prepareAppDataAfterInstallLIF(newPkg);
16030
16031        // writer
16032        synchronized (mPackages) {
16033            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16034
16035            // Propagate the permissions state as we do not want to drop on the floor
16036            // runtime permissions. The update permissions method below will take
16037            // care of removing obsolete permissions and grant install permissions.
16038            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16039            updatePermissionsLPw(newPkg.packageName, newPkg,
16040                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16041
16042            if (applyUserRestrictions) {
16043                if (DEBUG_REMOVE) {
16044                    Slog.d(TAG, "Propagating install state across reinstall");
16045                }
16046                for (int userId : allUserHandles) {
16047                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16048                    if (DEBUG_REMOVE) {
16049                        Slog.d(TAG, "    user " + userId + " => " + installed);
16050                    }
16051                    ps.setInstalled(installed, userId);
16052
16053                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16054                }
16055                // Regardless of writeSettings we need to ensure that this restriction
16056                // state propagation is persisted
16057                mSettings.writeAllUsersPackageRestrictionsLPr();
16058            }
16059            // can downgrade to reader here
16060            if (writeSettings) {
16061                mSettings.writeLPr();
16062            }
16063        }
16064        return true;
16065    }
16066
16067    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16068            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16069            PackageRemovedInfo outInfo, boolean writeSettings,
16070            PackageParser.Package replacingPackage) {
16071        synchronized (mPackages) {
16072            if (outInfo != null) {
16073                outInfo.uid = ps.appId;
16074            }
16075
16076            if (outInfo != null && outInfo.removedChildPackages != null) {
16077                final int childCount = (ps.childPackageNames != null)
16078                        ? ps.childPackageNames.size() : 0;
16079                for (int i = 0; i < childCount; i++) {
16080                    String childPackageName = ps.childPackageNames.get(i);
16081                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16082                    if (childPs == null) {
16083                        return false;
16084                    }
16085                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16086                            childPackageName);
16087                    if (childInfo != null) {
16088                        childInfo.uid = childPs.appId;
16089                    }
16090                }
16091            }
16092        }
16093
16094        // Delete package data from internal structures and also remove data if flag is set
16095        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16096
16097        // Delete the child packages data
16098        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16099        for (int i = 0; i < childCount; i++) {
16100            PackageSetting childPs;
16101            synchronized (mPackages) {
16102                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16103            }
16104            if (childPs != null) {
16105                PackageRemovedInfo childOutInfo = (outInfo != null
16106                        && outInfo.removedChildPackages != null)
16107                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16108                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16109                        && (replacingPackage != null
16110                        && !replacingPackage.hasChildPackage(childPs.name))
16111                        ? flags & ~DELETE_KEEP_DATA : flags;
16112                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16113                        deleteFlags, writeSettings);
16114            }
16115        }
16116
16117        // Delete application code and resources only for parent packages
16118        if (ps.parentPackageName == null) {
16119            if (deleteCodeAndResources && (outInfo != null)) {
16120                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16121                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16122                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16123            }
16124        }
16125
16126        return true;
16127    }
16128
16129    @Override
16130    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16131            int userId) {
16132        mContext.enforceCallingOrSelfPermission(
16133                android.Manifest.permission.DELETE_PACKAGES, null);
16134        synchronized (mPackages) {
16135            PackageSetting ps = mSettings.mPackages.get(packageName);
16136            if (ps == null) {
16137                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16138                return false;
16139            }
16140            if (!ps.getInstalled(userId)) {
16141                // Can't block uninstall for an app that is not installed or enabled.
16142                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16143                return false;
16144            }
16145            ps.setBlockUninstall(blockUninstall, userId);
16146            mSettings.writePackageRestrictionsLPr(userId);
16147        }
16148        return true;
16149    }
16150
16151    @Override
16152    public boolean getBlockUninstallForUser(String packageName, int userId) {
16153        synchronized (mPackages) {
16154            PackageSetting ps = mSettings.mPackages.get(packageName);
16155            if (ps == null) {
16156                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16157                return false;
16158            }
16159            return ps.getBlockUninstall(userId);
16160        }
16161    }
16162
16163    @Override
16164    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16165        int callingUid = Binder.getCallingUid();
16166        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16167            throw new SecurityException(
16168                    "setRequiredForSystemUser can only be run by the system or root");
16169        }
16170        synchronized (mPackages) {
16171            PackageSetting ps = mSettings.mPackages.get(packageName);
16172            if (ps == null) {
16173                Log.w(TAG, "Package doesn't exist: " + packageName);
16174                return false;
16175            }
16176            if (systemUserApp) {
16177                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16178            } else {
16179                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16180            }
16181            mSettings.writeLPr();
16182        }
16183        return true;
16184    }
16185
16186    /*
16187     * This method handles package deletion in general
16188     */
16189    private boolean deletePackageLIF(String packageName, UserHandle user,
16190            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16191            PackageRemovedInfo outInfo, boolean writeSettings,
16192            PackageParser.Package replacingPackage) {
16193        if (packageName == null) {
16194            Slog.w(TAG, "Attempt to delete null packageName.");
16195            return false;
16196        }
16197
16198        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16199
16200        PackageSetting ps;
16201
16202        synchronized (mPackages) {
16203            ps = mSettings.mPackages.get(packageName);
16204            if (ps == null) {
16205                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16206                return false;
16207            }
16208
16209            if (ps.parentPackageName != null && (!isSystemApp(ps)
16210                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16211                if (DEBUG_REMOVE) {
16212                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16213                            + ((user == null) ? UserHandle.USER_ALL : user));
16214                }
16215                final int removedUserId = (user != null) ? user.getIdentifier()
16216                        : UserHandle.USER_ALL;
16217                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16218                    return false;
16219                }
16220                markPackageUninstalledForUserLPw(ps, user);
16221                scheduleWritePackageRestrictionsLocked(user);
16222                return true;
16223            }
16224        }
16225
16226        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16227                && user.getIdentifier() != UserHandle.USER_ALL)) {
16228            // The caller is asking that the package only be deleted for a single
16229            // user.  To do this, we just mark its uninstalled state and delete
16230            // its data. If this is a system app, we only allow this to happen if
16231            // they have set the special DELETE_SYSTEM_APP which requests different
16232            // semantics than normal for uninstalling system apps.
16233            markPackageUninstalledForUserLPw(ps, user);
16234
16235            if (!isSystemApp(ps)) {
16236                // Do not uninstall the APK if an app should be cached
16237                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16238                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16239                    // Other user 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, "Still installed by other users");
16243                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16244                        return false;
16245                    }
16246                    scheduleWritePackageRestrictionsLocked(user);
16247                    return true;
16248                } else {
16249                    // We need to set it back to 'installed' so the uninstall
16250                    // broadcasts will be sent correctly.
16251                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16252                    ps.setInstalled(true, user.getIdentifier());
16253                }
16254            } else {
16255                // This is a system app, so we assume that the
16256                // other users still have this package installed, so all
16257                // we need to do is clear this user's data and save that
16258                // it is uninstalled.
16259                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16260                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16261                    return false;
16262                }
16263                scheduleWritePackageRestrictionsLocked(user);
16264                return true;
16265            }
16266        }
16267
16268        // If we are deleting a composite package for all users, keep track
16269        // of result for each child.
16270        if (ps.childPackageNames != null && outInfo != null) {
16271            synchronized (mPackages) {
16272                final int childCount = ps.childPackageNames.size();
16273                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16274                for (int i = 0; i < childCount; i++) {
16275                    String childPackageName = ps.childPackageNames.get(i);
16276                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16277                    childInfo.removedPackage = childPackageName;
16278                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16279                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16280                    if (childPs != null) {
16281                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16282                    }
16283                }
16284            }
16285        }
16286
16287        boolean ret = false;
16288        if (isSystemApp(ps)) {
16289            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16290            // When an updated system application is deleted we delete the existing resources
16291            // as well and fall back to existing code in system partition
16292            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16293        } else {
16294            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16295            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16296                    outInfo, writeSettings, replacingPackage);
16297        }
16298
16299        // Take a note whether we deleted the package for all users
16300        if (outInfo != null) {
16301            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16302            if (outInfo.removedChildPackages != null) {
16303                synchronized (mPackages) {
16304                    final int childCount = outInfo.removedChildPackages.size();
16305                    for (int i = 0; i < childCount; i++) {
16306                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16307                        if (childInfo != null) {
16308                            childInfo.removedForAllUsers = mPackages.get(
16309                                    childInfo.removedPackage) == null;
16310                        }
16311                    }
16312                }
16313            }
16314            // If we uninstalled an update to a system app there may be some
16315            // child packages that appeared as they are declared in the system
16316            // app but were not declared in the update.
16317            if (isSystemApp(ps)) {
16318                synchronized (mPackages) {
16319                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16320                    final int childCount = (updatedPs.childPackageNames != null)
16321                            ? updatedPs.childPackageNames.size() : 0;
16322                    for (int i = 0; i < childCount; i++) {
16323                        String childPackageName = updatedPs.childPackageNames.get(i);
16324                        if (outInfo.removedChildPackages == null
16325                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16326                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16327                            if (childPs == null) {
16328                                continue;
16329                            }
16330                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16331                            installRes.name = childPackageName;
16332                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16333                            installRes.pkg = mPackages.get(childPackageName);
16334                            installRes.uid = childPs.pkg.applicationInfo.uid;
16335                            if (outInfo.appearedChildPackages == null) {
16336                                outInfo.appearedChildPackages = new ArrayMap<>();
16337                            }
16338                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16339                        }
16340                    }
16341                }
16342            }
16343        }
16344
16345        return ret;
16346    }
16347
16348    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16349        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16350                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16351        for (int nextUserId : userIds) {
16352            if (DEBUG_REMOVE) {
16353                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16354            }
16355            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16356                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16357                    false /*hidden*/, false /*suspended*/, null, null, null,
16358                    false /*blockUninstall*/,
16359                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16360        }
16361    }
16362
16363    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16364            PackageRemovedInfo outInfo) {
16365        final PackageParser.Package pkg;
16366        synchronized (mPackages) {
16367            pkg = mPackages.get(ps.name);
16368        }
16369
16370        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16371                : new int[] {userId};
16372        for (int nextUserId : userIds) {
16373            if (DEBUG_REMOVE) {
16374                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16375                        + nextUserId);
16376            }
16377
16378            destroyAppDataLIF(pkg, userId,
16379                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16380            destroyAppProfilesLIF(pkg, userId);
16381            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16382            schedulePackageCleaning(ps.name, nextUserId, false);
16383            synchronized (mPackages) {
16384                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16385                    scheduleWritePackageRestrictionsLocked(nextUserId);
16386                }
16387                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16388            }
16389        }
16390
16391        if (outInfo != null) {
16392            outInfo.removedPackage = ps.name;
16393            outInfo.removedAppId = ps.appId;
16394            outInfo.removedUsers = userIds;
16395        }
16396
16397        return true;
16398    }
16399
16400    private final class ClearStorageConnection implements ServiceConnection {
16401        IMediaContainerService mContainerService;
16402
16403        @Override
16404        public void onServiceConnected(ComponentName name, IBinder service) {
16405            synchronized (this) {
16406                mContainerService = IMediaContainerService.Stub.asInterface(service);
16407                notifyAll();
16408            }
16409        }
16410
16411        @Override
16412        public void onServiceDisconnected(ComponentName name) {
16413        }
16414    }
16415
16416    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16417        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16418
16419        final boolean mounted;
16420        if (Environment.isExternalStorageEmulated()) {
16421            mounted = true;
16422        } else {
16423            final String status = Environment.getExternalStorageState();
16424
16425            mounted = status.equals(Environment.MEDIA_MOUNTED)
16426                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16427        }
16428
16429        if (!mounted) {
16430            return;
16431        }
16432
16433        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16434        int[] users;
16435        if (userId == UserHandle.USER_ALL) {
16436            users = sUserManager.getUserIds();
16437        } else {
16438            users = new int[] { userId };
16439        }
16440        final ClearStorageConnection conn = new ClearStorageConnection();
16441        if (mContext.bindServiceAsUser(
16442                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16443            try {
16444                for (int curUser : users) {
16445                    long timeout = SystemClock.uptimeMillis() + 5000;
16446                    synchronized (conn) {
16447                        long now;
16448                        while (conn.mContainerService == null &&
16449                                (now = SystemClock.uptimeMillis()) < timeout) {
16450                            try {
16451                                conn.wait(timeout - now);
16452                            } catch (InterruptedException e) {
16453                            }
16454                        }
16455                    }
16456                    if (conn.mContainerService == null) {
16457                        return;
16458                    }
16459
16460                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16461                    clearDirectory(conn.mContainerService,
16462                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16463                    if (allData) {
16464                        clearDirectory(conn.mContainerService,
16465                                userEnv.buildExternalStorageAppDataDirs(packageName));
16466                        clearDirectory(conn.mContainerService,
16467                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16468                    }
16469                }
16470            } finally {
16471                mContext.unbindService(conn);
16472            }
16473        }
16474    }
16475
16476    @Override
16477    public void clearApplicationProfileData(String packageName) {
16478        enforceSystemOrRoot("Only the system can clear all profile data");
16479
16480        final PackageParser.Package pkg;
16481        synchronized (mPackages) {
16482            pkg = mPackages.get(packageName);
16483        }
16484
16485        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16486            synchronized (mInstallLock) {
16487                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16488                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16489                        true /* removeBaseMarker */);
16490            }
16491        }
16492    }
16493
16494    @Override
16495    public void clearApplicationUserData(final String packageName,
16496            final IPackageDataObserver observer, final int userId) {
16497        mContext.enforceCallingOrSelfPermission(
16498                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16499
16500        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16501                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16502
16503        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16504            throw new SecurityException("Cannot clear data for a protected package: "
16505                    + packageName);
16506        }
16507        // Queue up an async operation since the package deletion may take a little while.
16508        mHandler.post(new Runnable() {
16509            public void run() {
16510                mHandler.removeCallbacks(this);
16511                final boolean succeeded;
16512                try (PackageFreezer freezer = freezePackage(packageName,
16513                        "clearApplicationUserData")) {
16514                    synchronized (mInstallLock) {
16515                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16516                    }
16517                    clearExternalStorageDataSync(packageName, userId, true);
16518                }
16519                if (succeeded) {
16520                    // invoke DeviceStorageMonitor's update method to clear any notifications
16521                    DeviceStorageMonitorInternal dsm = LocalServices
16522                            .getService(DeviceStorageMonitorInternal.class);
16523                    if (dsm != null) {
16524                        dsm.checkMemory();
16525                    }
16526                }
16527                if(observer != null) {
16528                    try {
16529                        observer.onRemoveCompleted(packageName, succeeded);
16530                    } catch (RemoteException e) {
16531                        Log.i(TAG, "Observer no longer exists.");
16532                    }
16533                } //end if observer
16534            } //end run
16535        });
16536    }
16537
16538    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16539        if (packageName == null) {
16540            Slog.w(TAG, "Attempt to delete null packageName.");
16541            return false;
16542        }
16543
16544        // Try finding details about the requested package
16545        PackageParser.Package pkg;
16546        synchronized (mPackages) {
16547            pkg = mPackages.get(packageName);
16548            if (pkg == null) {
16549                final PackageSetting ps = mSettings.mPackages.get(packageName);
16550                if (ps != null) {
16551                    pkg = ps.pkg;
16552                }
16553            }
16554
16555            if (pkg == null) {
16556                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16557                return false;
16558            }
16559
16560            PackageSetting ps = (PackageSetting) pkg.mExtras;
16561            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16562        }
16563
16564        clearAppDataLIF(pkg, userId,
16565                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16566
16567        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16568        removeKeystoreDataIfNeeded(userId, appId);
16569
16570        UserManagerInternal umInternal = getUserManagerInternal();
16571        final int flags;
16572        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16573            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16574        } else if (umInternal.isUserRunning(userId)) {
16575            flags = StorageManager.FLAG_STORAGE_DE;
16576        } else {
16577            flags = 0;
16578        }
16579        prepareAppDataContentsLIF(pkg, userId, flags);
16580
16581        return true;
16582    }
16583
16584    /**
16585     * Reverts user permission state changes (permissions and flags) in
16586     * all packages for a given user.
16587     *
16588     * @param userId The device user for which to do a reset.
16589     */
16590    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16591        final int packageCount = mPackages.size();
16592        for (int i = 0; i < packageCount; i++) {
16593            PackageParser.Package pkg = mPackages.valueAt(i);
16594            PackageSetting ps = (PackageSetting) pkg.mExtras;
16595            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16596        }
16597    }
16598
16599    private void resetNetworkPolicies(int userId) {
16600        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16601    }
16602
16603    /**
16604     * Reverts user permission state changes (permissions and flags).
16605     *
16606     * @param ps The package for which to reset.
16607     * @param userId The device user for which to do a reset.
16608     */
16609    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16610            final PackageSetting ps, final int userId) {
16611        if (ps.pkg == null) {
16612            return;
16613        }
16614
16615        // These are flags that can change base on user actions.
16616        final int userSettableMask = FLAG_PERMISSION_USER_SET
16617                | FLAG_PERMISSION_USER_FIXED
16618                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16619                | FLAG_PERMISSION_REVIEW_REQUIRED;
16620
16621        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16622                | FLAG_PERMISSION_POLICY_FIXED;
16623
16624        boolean writeInstallPermissions = false;
16625        boolean writeRuntimePermissions = false;
16626
16627        final int permissionCount = ps.pkg.requestedPermissions.size();
16628        for (int i = 0; i < permissionCount; i++) {
16629            String permission = ps.pkg.requestedPermissions.get(i);
16630
16631            BasePermission bp = mSettings.mPermissions.get(permission);
16632            if (bp == null) {
16633                continue;
16634            }
16635
16636            // If shared user we just reset the state to which only this app contributed.
16637            if (ps.sharedUser != null) {
16638                boolean used = false;
16639                final int packageCount = ps.sharedUser.packages.size();
16640                for (int j = 0; j < packageCount; j++) {
16641                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16642                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16643                            && pkg.pkg.requestedPermissions.contains(permission)) {
16644                        used = true;
16645                        break;
16646                    }
16647                }
16648                if (used) {
16649                    continue;
16650                }
16651            }
16652
16653            PermissionsState permissionsState = ps.getPermissionsState();
16654
16655            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16656
16657            // Always clear the user settable flags.
16658            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16659                    bp.name) != null;
16660            // If permission review is enabled and this is a legacy app, mark the
16661            // permission as requiring a review as this is the initial state.
16662            int flags = 0;
16663            if (Build.PERMISSIONS_REVIEW_REQUIRED
16664                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16665                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16666            }
16667            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16668                if (hasInstallState) {
16669                    writeInstallPermissions = true;
16670                } else {
16671                    writeRuntimePermissions = true;
16672                }
16673            }
16674
16675            // Below is only runtime permission handling.
16676            if (!bp.isRuntime()) {
16677                continue;
16678            }
16679
16680            // Never clobber system or policy.
16681            if ((oldFlags & policyOrSystemFlags) != 0) {
16682                continue;
16683            }
16684
16685            // If this permission was granted by default, make sure it is.
16686            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16687                if (permissionsState.grantRuntimePermission(bp, userId)
16688                        != PERMISSION_OPERATION_FAILURE) {
16689                    writeRuntimePermissions = true;
16690                }
16691            // If permission review is enabled the permissions for a legacy apps
16692            // are represented as constantly granted runtime ones, so don't revoke.
16693            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16694                // Otherwise, reset the permission.
16695                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16696                switch (revokeResult) {
16697                    case PERMISSION_OPERATION_SUCCESS:
16698                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16699                        writeRuntimePermissions = true;
16700                        final int appId = ps.appId;
16701                        mHandler.post(new Runnable() {
16702                            @Override
16703                            public void run() {
16704                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16705                            }
16706                        });
16707                    } break;
16708                }
16709            }
16710        }
16711
16712        // Synchronously write as we are taking permissions away.
16713        if (writeRuntimePermissions) {
16714            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16715        }
16716
16717        // Synchronously write as we are taking permissions away.
16718        if (writeInstallPermissions) {
16719            mSettings.writeLPr();
16720        }
16721    }
16722
16723    /**
16724     * Remove entries from the keystore daemon. Will only remove it if the
16725     * {@code appId} is valid.
16726     */
16727    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16728        if (appId < 0) {
16729            return;
16730        }
16731
16732        final KeyStore keyStore = KeyStore.getInstance();
16733        if (keyStore != null) {
16734            if (userId == UserHandle.USER_ALL) {
16735                for (final int individual : sUserManager.getUserIds()) {
16736                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16737                }
16738            } else {
16739                keyStore.clearUid(UserHandle.getUid(userId, appId));
16740            }
16741        } else {
16742            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16743        }
16744    }
16745
16746    @Override
16747    public void deleteApplicationCacheFiles(final String packageName,
16748            final IPackageDataObserver observer) {
16749        final int userId = UserHandle.getCallingUserId();
16750        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16751    }
16752
16753    @Override
16754    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16755            final IPackageDataObserver observer) {
16756        mContext.enforceCallingOrSelfPermission(
16757                android.Manifest.permission.DELETE_CACHE_FILES, null);
16758        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16759                /* requireFullPermission= */ true, /* checkShell= */ false,
16760                "delete application cache files");
16761
16762        final PackageParser.Package pkg;
16763        synchronized (mPackages) {
16764            pkg = mPackages.get(packageName);
16765        }
16766
16767        // Queue up an async operation since the package deletion may take a little while.
16768        mHandler.post(new Runnable() {
16769            public void run() {
16770                synchronized (mInstallLock) {
16771                    final int flags = StorageManager.FLAG_STORAGE_DE
16772                            | StorageManager.FLAG_STORAGE_CE;
16773                    // We're only clearing cache files, so we don't care if the
16774                    // app is unfrozen and still able to run
16775                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16776                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16777                }
16778                clearExternalStorageDataSync(packageName, userId, false);
16779                if (observer != null) {
16780                    try {
16781                        observer.onRemoveCompleted(packageName, true);
16782                    } catch (RemoteException e) {
16783                        Log.i(TAG, "Observer no longer exists.");
16784                    }
16785                }
16786            }
16787        });
16788    }
16789
16790    @Override
16791    public void getPackageSizeInfo(final String packageName, int userHandle,
16792            final IPackageStatsObserver observer) {
16793        mContext.enforceCallingOrSelfPermission(
16794                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16795        if (packageName == null) {
16796            throw new IllegalArgumentException("Attempt to get size of null packageName");
16797        }
16798
16799        PackageStats stats = new PackageStats(packageName, userHandle);
16800
16801        /*
16802         * Queue up an async operation since the package measurement may take a
16803         * little while.
16804         */
16805        Message msg = mHandler.obtainMessage(INIT_COPY);
16806        msg.obj = new MeasureParams(stats, observer);
16807        mHandler.sendMessage(msg);
16808    }
16809
16810    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16811        final PackageSetting ps;
16812        synchronized (mPackages) {
16813            ps = mSettings.mPackages.get(packageName);
16814            if (ps == null) {
16815                Slog.w(TAG, "Failed to find settings for " + packageName);
16816                return false;
16817            }
16818        }
16819        try {
16820            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16821                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16822                    ps.getCeDataInode(userId), ps.codePathString, stats);
16823        } catch (InstallerException e) {
16824            Slog.w(TAG, String.valueOf(e));
16825            return false;
16826        }
16827
16828        // For now, ignore code size of packages on system partition
16829        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16830            stats.codeSize = 0;
16831        }
16832
16833        return true;
16834    }
16835
16836    private int getUidTargetSdkVersionLockedLPr(int uid) {
16837        Object obj = mSettings.getUserIdLPr(uid);
16838        if (obj instanceof SharedUserSetting) {
16839            final SharedUserSetting sus = (SharedUserSetting) obj;
16840            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16841            final Iterator<PackageSetting> it = sus.packages.iterator();
16842            while (it.hasNext()) {
16843                final PackageSetting ps = it.next();
16844                if (ps.pkg != null) {
16845                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16846                    if (v < vers) vers = v;
16847                }
16848            }
16849            return vers;
16850        } else if (obj instanceof PackageSetting) {
16851            final PackageSetting ps = (PackageSetting) obj;
16852            if (ps.pkg != null) {
16853                return ps.pkg.applicationInfo.targetSdkVersion;
16854            }
16855        }
16856        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16857    }
16858
16859    @Override
16860    public void addPreferredActivity(IntentFilter filter, int match,
16861            ComponentName[] set, ComponentName activity, int userId) {
16862        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16863                "Adding preferred");
16864    }
16865
16866    private void addPreferredActivityInternal(IntentFilter filter, int match,
16867            ComponentName[] set, ComponentName activity, boolean always, int userId,
16868            String opname) {
16869        // writer
16870        int callingUid = Binder.getCallingUid();
16871        enforceCrossUserPermission(callingUid, userId,
16872                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16873        if (filter.countActions() == 0) {
16874            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16875            return;
16876        }
16877        synchronized (mPackages) {
16878            if (mContext.checkCallingOrSelfPermission(
16879                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16880                    != PackageManager.PERMISSION_GRANTED) {
16881                if (getUidTargetSdkVersionLockedLPr(callingUid)
16882                        < Build.VERSION_CODES.FROYO) {
16883                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16884                            + callingUid);
16885                    return;
16886                }
16887                mContext.enforceCallingOrSelfPermission(
16888                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16889            }
16890
16891            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16892            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16893                    + userId + ":");
16894            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16895            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16896            scheduleWritePackageRestrictionsLocked(userId);
16897        }
16898    }
16899
16900    @Override
16901    public void replacePreferredActivity(IntentFilter filter, int match,
16902            ComponentName[] set, ComponentName activity, int userId) {
16903        if (filter.countActions() != 1) {
16904            throw new IllegalArgumentException(
16905                    "replacePreferredActivity expects filter to have only 1 action.");
16906        }
16907        if (filter.countDataAuthorities() != 0
16908                || filter.countDataPaths() != 0
16909                || filter.countDataSchemes() > 1
16910                || filter.countDataTypes() != 0) {
16911            throw new IllegalArgumentException(
16912                    "replacePreferredActivity expects filter to have no data authorities, " +
16913                    "paths, or types; and at most one scheme.");
16914        }
16915
16916        final int callingUid = Binder.getCallingUid();
16917        enforceCrossUserPermission(callingUid, userId,
16918                true /* requireFullPermission */, false /* checkShell */,
16919                "replace preferred activity");
16920        synchronized (mPackages) {
16921            if (mContext.checkCallingOrSelfPermission(
16922                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16923                    != PackageManager.PERMISSION_GRANTED) {
16924                if (getUidTargetSdkVersionLockedLPr(callingUid)
16925                        < Build.VERSION_CODES.FROYO) {
16926                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16927                            + Binder.getCallingUid());
16928                    return;
16929                }
16930                mContext.enforceCallingOrSelfPermission(
16931                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16932            }
16933
16934            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16935            if (pir != null) {
16936                // Get all of the existing entries that exactly match this filter.
16937                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16938                if (existing != null && existing.size() == 1) {
16939                    PreferredActivity cur = existing.get(0);
16940                    if (DEBUG_PREFERRED) {
16941                        Slog.i(TAG, "Checking replace of preferred:");
16942                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16943                        if (!cur.mPref.mAlways) {
16944                            Slog.i(TAG, "  -- CUR; not mAlways!");
16945                        } else {
16946                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16947                            Slog.i(TAG, "  -- CUR: mSet="
16948                                    + Arrays.toString(cur.mPref.mSetComponents));
16949                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16950                            Slog.i(TAG, "  -- NEW: mMatch="
16951                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16952                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16953                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16954                        }
16955                    }
16956                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16957                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16958                            && cur.mPref.sameSet(set)) {
16959                        // Setting the preferred activity to what it happens to be already
16960                        if (DEBUG_PREFERRED) {
16961                            Slog.i(TAG, "Replacing with same preferred activity "
16962                                    + cur.mPref.mShortComponent + " for user "
16963                                    + userId + ":");
16964                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16965                        }
16966                        return;
16967                    }
16968                }
16969
16970                if (existing != null) {
16971                    if (DEBUG_PREFERRED) {
16972                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16973                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16974                    }
16975                    for (int i = 0; i < existing.size(); i++) {
16976                        PreferredActivity pa = existing.get(i);
16977                        if (DEBUG_PREFERRED) {
16978                            Slog.i(TAG, "Removing existing preferred activity "
16979                                    + pa.mPref.mComponent + ":");
16980                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16981                        }
16982                        pir.removeFilter(pa);
16983                    }
16984                }
16985            }
16986            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16987                    "Replacing preferred");
16988        }
16989    }
16990
16991    @Override
16992    public void clearPackagePreferredActivities(String packageName) {
16993        final int uid = Binder.getCallingUid();
16994        // writer
16995        synchronized (mPackages) {
16996            PackageParser.Package pkg = mPackages.get(packageName);
16997            if (pkg == null || pkg.applicationInfo.uid != uid) {
16998                if (mContext.checkCallingOrSelfPermission(
16999                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17000                        != PackageManager.PERMISSION_GRANTED) {
17001                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17002                            < Build.VERSION_CODES.FROYO) {
17003                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17004                                + Binder.getCallingUid());
17005                        return;
17006                    }
17007                    mContext.enforceCallingOrSelfPermission(
17008                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17009                }
17010            }
17011
17012            int user = UserHandle.getCallingUserId();
17013            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17014                scheduleWritePackageRestrictionsLocked(user);
17015            }
17016        }
17017    }
17018
17019    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17020    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17021        ArrayList<PreferredActivity> removed = null;
17022        boolean changed = false;
17023        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17024            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17025            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17026            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17027                continue;
17028            }
17029            Iterator<PreferredActivity> it = pir.filterIterator();
17030            while (it.hasNext()) {
17031                PreferredActivity pa = it.next();
17032                // Mark entry for removal only if it matches the package name
17033                // and the entry is of type "always".
17034                if (packageName == null ||
17035                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17036                                && pa.mPref.mAlways)) {
17037                    if (removed == null) {
17038                        removed = new ArrayList<PreferredActivity>();
17039                    }
17040                    removed.add(pa);
17041                }
17042            }
17043            if (removed != null) {
17044                for (int j=0; j<removed.size(); j++) {
17045                    PreferredActivity pa = removed.get(j);
17046                    pir.removeFilter(pa);
17047                }
17048                changed = true;
17049            }
17050        }
17051        return changed;
17052    }
17053
17054    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17055    private void clearIntentFilterVerificationsLPw(int userId) {
17056        final int packageCount = mPackages.size();
17057        for (int i = 0; i < packageCount; i++) {
17058            PackageParser.Package pkg = mPackages.valueAt(i);
17059            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17060        }
17061    }
17062
17063    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17064    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17065        if (userId == UserHandle.USER_ALL) {
17066            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17067                    sUserManager.getUserIds())) {
17068                for (int oneUserId : sUserManager.getUserIds()) {
17069                    scheduleWritePackageRestrictionsLocked(oneUserId);
17070                }
17071            }
17072        } else {
17073            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17074                scheduleWritePackageRestrictionsLocked(userId);
17075            }
17076        }
17077    }
17078
17079    void clearDefaultBrowserIfNeeded(String packageName) {
17080        for (int oneUserId : sUserManager.getUserIds()) {
17081            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17082            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17083            if (packageName.equals(defaultBrowserPackageName)) {
17084                setDefaultBrowserPackageName(null, oneUserId);
17085            }
17086        }
17087    }
17088
17089    @Override
17090    public void resetApplicationPreferences(int userId) {
17091        mContext.enforceCallingOrSelfPermission(
17092                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17093        final long identity = Binder.clearCallingIdentity();
17094        // writer
17095        try {
17096            synchronized (mPackages) {
17097                clearPackagePreferredActivitiesLPw(null, userId);
17098                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17099                // TODO: We have to reset the default SMS and Phone. This requires
17100                // significant refactoring to keep all default apps in the package
17101                // manager (cleaner but more work) or have the services provide
17102                // callbacks to the package manager to request a default app reset.
17103                applyFactoryDefaultBrowserLPw(userId);
17104                clearIntentFilterVerificationsLPw(userId);
17105                primeDomainVerificationsLPw(userId);
17106                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17107                scheduleWritePackageRestrictionsLocked(userId);
17108            }
17109            resetNetworkPolicies(userId);
17110        } finally {
17111            Binder.restoreCallingIdentity(identity);
17112        }
17113    }
17114
17115    @Override
17116    public int getPreferredActivities(List<IntentFilter> outFilters,
17117            List<ComponentName> outActivities, String packageName) {
17118
17119        int num = 0;
17120        final int userId = UserHandle.getCallingUserId();
17121        // reader
17122        synchronized (mPackages) {
17123            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17124            if (pir != null) {
17125                final Iterator<PreferredActivity> it = pir.filterIterator();
17126                while (it.hasNext()) {
17127                    final PreferredActivity pa = it.next();
17128                    if (packageName == null
17129                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17130                                    && pa.mPref.mAlways)) {
17131                        if (outFilters != null) {
17132                            outFilters.add(new IntentFilter(pa));
17133                        }
17134                        if (outActivities != null) {
17135                            outActivities.add(pa.mPref.mComponent);
17136                        }
17137                    }
17138                }
17139            }
17140        }
17141
17142        return num;
17143    }
17144
17145    @Override
17146    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17147            int userId) {
17148        int callingUid = Binder.getCallingUid();
17149        if (callingUid != Process.SYSTEM_UID) {
17150            throw new SecurityException(
17151                    "addPersistentPreferredActivity can only be run by the system");
17152        }
17153        if (filter.countActions() == 0) {
17154            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17155            return;
17156        }
17157        synchronized (mPackages) {
17158            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17159                    ":");
17160            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17161            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17162                    new PersistentPreferredActivity(filter, activity));
17163            scheduleWritePackageRestrictionsLocked(userId);
17164        }
17165    }
17166
17167    @Override
17168    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17169        int callingUid = Binder.getCallingUid();
17170        if (callingUid != Process.SYSTEM_UID) {
17171            throw new SecurityException(
17172                    "clearPackagePersistentPreferredActivities can only be run by the system");
17173        }
17174        ArrayList<PersistentPreferredActivity> removed = null;
17175        boolean changed = false;
17176        synchronized (mPackages) {
17177            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17178                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17179                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17180                        .valueAt(i);
17181                if (userId != thisUserId) {
17182                    continue;
17183                }
17184                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17185                while (it.hasNext()) {
17186                    PersistentPreferredActivity ppa = it.next();
17187                    // Mark entry for removal only if it matches the package name.
17188                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17189                        if (removed == null) {
17190                            removed = new ArrayList<PersistentPreferredActivity>();
17191                        }
17192                        removed.add(ppa);
17193                    }
17194                }
17195                if (removed != null) {
17196                    for (int j=0; j<removed.size(); j++) {
17197                        PersistentPreferredActivity ppa = removed.get(j);
17198                        ppir.removeFilter(ppa);
17199                    }
17200                    changed = true;
17201                }
17202            }
17203
17204            if (changed) {
17205                scheduleWritePackageRestrictionsLocked(userId);
17206            }
17207        }
17208    }
17209
17210    /**
17211     * Common machinery for picking apart a restored XML blob and passing
17212     * it to a caller-supplied functor to be applied to the running system.
17213     */
17214    private void restoreFromXml(XmlPullParser parser, int userId,
17215            String expectedStartTag, BlobXmlRestorer functor)
17216            throws IOException, XmlPullParserException {
17217        int type;
17218        while ((type = parser.next()) != XmlPullParser.START_TAG
17219                && type != XmlPullParser.END_DOCUMENT) {
17220        }
17221        if (type != XmlPullParser.START_TAG) {
17222            // oops didn't find a start tag?!
17223            if (DEBUG_BACKUP) {
17224                Slog.e(TAG, "Didn't find start tag during restore");
17225            }
17226            return;
17227        }
17228Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17229        // this is supposed to be TAG_PREFERRED_BACKUP
17230        if (!expectedStartTag.equals(parser.getName())) {
17231            if (DEBUG_BACKUP) {
17232                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17233            }
17234            return;
17235        }
17236
17237        // skip interfering stuff, then we're aligned with the backing implementation
17238        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17239Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17240        functor.apply(parser, userId);
17241    }
17242
17243    private interface BlobXmlRestorer {
17244        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17245    }
17246
17247    /**
17248     * Non-Binder method, support for the backup/restore mechanism: write the
17249     * full set of preferred activities in its canonical XML format.  Returns the
17250     * XML output as a byte array, or null if there is none.
17251     */
17252    @Override
17253    public byte[] getPreferredActivityBackup(int userId) {
17254        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17255            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17256        }
17257
17258        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17259        try {
17260            final XmlSerializer serializer = new FastXmlSerializer();
17261            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17262            serializer.startDocument(null, true);
17263            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17264
17265            synchronized (mPackages) {
17266                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17267            }
17268
17269            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17270            serializer.endDocument();
17271            serializer.flush();
17272        } catch (Exception e) {
17273            if (DEBUG_BACKUP) {
17274                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17275            }
17276            return null;
17277        }
17278
17279        return dataStream.toByteArray();
17280    }
17281
17282    @Override
17283    public void restorePreferredActivities(byte[] backup, int userId) {
17284        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17285            throw new SecurityException("Only the system may call restorePreferredActivities()");
17286        }
17287
17288        try {
17289            final XmlPullParser parser = Xml.newPullParser();
17290            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17291            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17292                    new BlobXmlRestorer() {
17293                        @Override
17294                        public void apply(XmlPullParser parser, int userId)
17295                                throws XmlPullParserException, IOException {
17296                            synchronized (mPackages) {
17297                                mSettings.readPreferredActivitiesLPw(parser, userId);
17298                            }
17299                        }
17300                    } );
17301        } catch (Exception e) {
17302            if (DEBUG_BACKUP) {
17303                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17304            }
17305        }
17306    }
17307
17308    /**
17309     * Non-Binder method, support for the backup/restore mechanism: write the
17310     * default browser (etc) settings in its canonical XML format.  Returns the default
17311     * browser XML representation as a byte array, or null if there is none.
17312     */
17313    @Override
17314    public byte[] getDefaultAppsBackup(int userId) {
17315        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17316            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17317        }
17318
17319        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17320        try {
17321            final XmlSerializer serializer = new FastXmlSerializer();
17322            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17323            serializer.startDocument(null, true);
17324            serializer.startTag(null, TAG_DEFAULT_APPS);
17325
17326            synchronized (mPackages) {
17327                mSettings.writeDefaultAppsLPr(serializer, userId);
17328            }
17329
17330            serializer.endTag(null, TAG_DEFAULT_APPS);
17331            serializer.endDocument();
17332            serializer.flush();
17333        } catch (Exception e) {
17334            if (DEBUG_BACKUP) {
17335                Slog.e(TAG, "Unable to write default apps for backup", e);
17336            }
17337            return null;
17338        }
17339
17340        return dataStream.toByteArray();
17341    }
17342
17343    @Override
17344    public void restoreDefaultApps(byte[] backup, int userId) {
17345        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17346            throw new SecurityException("Only the system may call restoreDefaultApps()");
17347        }
17348
17349        try {
17350            final XmlPullParser parser = Xml.newPullParser();
17351            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17352            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17353                    new BlobXmlRestorer() {
17354                        @Override
17355                        public void apply(XmlPullParser parser, int userId)
17356                                throws XmlPullParserException, IOException {
17357                            synchronized (mPackages) {
17358                                mSettings.readDefaultAppsLPw(parser, userId);
17359                            }
17360                        }
17361                    } );
17362        } catch (Exception e) {
17363            if (DEBUG_BACKUP) {
17364                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17365            }
17366        }
17367    }
17368
17369    @Override
17370    public byte[] getIntentFilterVerificationBackup(int userId) {
17371        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17372            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17373        }
17374
17375        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17376        try {
17377            final XmlSerializer serializer = new FastXmlSerializer();
17378            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17379            serializer.startDocument(null, true);
17380            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17381
17382            synchronized (mPackages) {
17383                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17384            }
17385
17386            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17387            serializer.endDocument();
17388            serializer.flush();
17389        } catch (Exception e) {
17390            if (DEBUG_BACKUP) {
17391                Slog.e(TAG, "Unable to write default apps for backup", e);
17392            }
17393            return null;
17394        }
17395
17396        return dataStream.toByteArray();
17397    }
17398
17399    @Override
17400    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17401        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17402            throw new SecurityException("Only the system may call restorePreferredActivities()");
17403        }
17404
17405        try {
17406            final XmlPullParser parser = Xml.newPullParser();
17407            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17408            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17409                    new BlobXmlRestorer() {
17410                        @Override
17411                        public void apply(XmlPullParser parser, int userId)
17412                                throws XmlPullParserException, IOException {
17413                            synchronized (mPackages) {
17414                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17415                                mSettings.writeLPr();
17416                            }
17417                        }
17418                    } );
17419        } catch (Exception e) {
17420            if (DEBUG_BACKUP) {
17421                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17422            }
17423        }
17424    }
17425
17426    @Override
17427    public byte[] getPermissionGrantBackup(int userId) {
17428        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17429            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17430        }
17431
17432        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17433        try {
17434            final XmlSerializer serializer = new FastXmlSerializer();
17435            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17436            serializer.startDocument(null, true);
17437            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17438
17439            synchronized (mPackages) {
17440                serializeRuntimePermissionGrantsLPr(serializer, userId);
17441            }
17442
17443            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17444            serializer.endDocument();
17445            serializer.flush();
17446        } catch (Exception e) {
17447            if (DEBUG_BACKUP) {
17448                Slog.e(TAG, "Unable to write default apps for backup", e);
17449            }
17450            return null;
17451        }
17452
17453        return dataStream.toByteArray();
17454    }
17455
17456    @Override
17457    public void restorePermissionGrants(byte[] backup, int userId) {
17458        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17459            throw new SecurityException("Only the system may call restorePermissionGrants()");
17460        }
17461
17462        try {
17463            final XmlPullParser parser = Xml.newPullParser();
17464            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17465            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17466                    new BlobXmlRestorer() {
17467                        @Override
17468                        public void apply(XmlPullParser parser, int userId)
17469                                throws XmlPullParserException, IOException {
17470                            synchronized (mPackages) {
17471                                processRestoredPermissionGrantsLPr(parser, userId);
17472                            }
17473                        }
17474                    } );
17475        } catch (Exception e) {
17476            if (DEBUG_BACKUP) {
17477                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17478            }
17479        }
17480    }
17481
17482    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17483            throws IOException {
17484        serializer.startTag(null, TAG_ALL_GRANTS);
17485
17486        final int N = mSettings.mPackages.size();
17487        for (int i = 0; i < N; i++) {
17488            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17489            boolean pkgGrantsKnown = false;
17490
17491            PermissionsState packagePerms = ps.getPermissionsState();
17492
17493            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17494                final int grantFlags = state.getFlags();
17495                // only look at grants that are not system/policy fixed
17496                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17497                    final boolean isGranted = state.isGranted();
17498                    // And only back up the user-twiddled state bits
17499                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17500                        final String packageName = mSettings.mPackages.keyAt(i);
17501                        if (!pkgGrantsKnown) {
17502                            serializer.startTag(null, TAG_GRANT);
17503                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17504                            pkgGrantsKnown = true;
17505                        }
17506
17507                        final boolean userSet =
17508                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17509                        final boolean userFixed =
17510                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17511                        final boolean revoke =
17512                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17513
17514                        serializer.startTag(null, TAG_PERMISSION);
17515                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17516                        if (isGranted) {
17517                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17518                        }
17519                        if (userSet) {
17520                            serializer.attribute(null, ATTR_USER_SET, "true");
17521                        }
17522                        if (userFixed) {
17523                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17524                        }
17525                        if (revoke) {
17526                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17527                        }
17528                        serializer.endTag(null, TAG_PERMISSION);
17529                    }
17530                }
17531            }
17532
17533            if (pkgGrantsKnown) {
17534                serializer.endTag(null, TAG_GRANT);
17535            }
17536        }
17537
17538        serializer.endTag(null, TAG_ALL_GRANTS);
17539    }
17540
17541    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17542            throws XmlPullParserException, IOException {
17543        String pkgName = null;
17544        int outerDepth = parser.getDepth();
17545        int type;
17546        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17547                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17548            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17549                continue;
17550            }
17551
17552            final String tagName = parser.getName();
17553            if (tagName.equals(TAG_GRANT)) {
17554                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17555                if (DEBUG_BACKUP) {
17556                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17557                }
17558            } else if (tagName.equals(TAG_PERMISSION)) {
17559
17560                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17561                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17562
17563                int newFlagSet = 0;
17564                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17565                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17566                }
17567                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17568                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17569                }
17570                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17571                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17572                }
17573                if (DEBUG_BACKUP) {
17574                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17575                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17576                }
17577                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17578                if (ps != null) {
17579                    // Already installed so we apply the grant immediately
17580                    if (DEBUG_BACKUP) {
17581                        Slog.v(TAG, "        + already installed; applying");
17582                    }
17583                    PermissionsState perms = ps.getPermissionsState();
17584                    BasePermission bp = mSettings.mPermissions.get(permName);
17585                    if (bp != null) {
17586                        if (isGranted) {
17587                            perms.grantRuntimePermission(bp, userId);
17588                        }
17589                        if (newFlagSet != 0) {
17590                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17591                        }
17592                    }
17593                } else {
17594                    // Need to wait for post-restore install to apply the grant
17595                    if (DEBUG_BACKUP) {
17596                        Slog.v(TAG, "        - not yet installed; saving for later");
17597                    }
17598                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17599                            isGranted, newFlagSet, userId);
17600                }
17601            } else {
17602                PackageManagerService.reportSettingsProblem(Log.WARN,
17603                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17604                XmlUtils.skipCurrentTag(parser);
17605            }
17606        }
17607
17608        scheduleWriteSettingsLocked();
17609        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17610    }
17611
17612    @Override
17613    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17614            int sourceUserId, int targetUserId, int flags) {
17615        mContext.enforceCallingOrSelfPermission(
17616                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17617        int callingUid = Binder.getCallingUid();
17618        enforceOwnerRights(ownerPackage, callingUid);
17619        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17620        if (intentFilter.countActions() == 0) {
17621            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17622            return;
17623        }
17624        synchronized (mPackages) {
17625            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17626                    ownerPackage, targetUserId, flags);
17627            CrossProfileIntentResolver resolver =
17628                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17629            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17630            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17631            if (existing != null) {
17632                int size = existing.size();
17633                for (int i = 0; i < size; i++) {
17634                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17635                        return;
17636                    }
17637                }
17638            }
17639            resolver.addFilter(newFilter);
17640            scheduleWritePackageRestrictionsLocked(sourceUserId);
17641        }
17642    }
17643
17644    @Override
17645    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17646        mContext.enforceCallingOrSelfPermission(
17647                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17648        int callingUid = Binder.getCallingUid();
17649        enforceOwnerRights(ownerPackage, callingUid);
17650        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17651        synchronized (mPackages) {
17652            CrossProfileIntentResolver resolver =
17653                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17654            ArraySet<CrossProfileIntentFilter> set =
17655                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17656            for (CrossProfileIntentFilter filter : set) {
17657                if (filter.getOwnerPackage().equals(ownerPackage)) {
17658                    resolver.removeFilter(filter);
17659                }
17660            }
17661            scheduleWritePackageRestrictionsLocked(sourceUserId);
17662        }
17663    }
17664
17665    // Enforcing that callingUid is owning pkg on userId
17666    private void enforceOwnerRights(String pkg, int callingUid) {
17667        // The system owns everything.
17668        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17669            return;
17670        }
17671        int callingUserId = UserHandle.getUserId(callingUid);
17672        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17673        if (pi == null) {
17674            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17675                    + callingUserId);
17676        }
17677        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17678            throw new SecurityException("Calling uid " + callingUid
17679                    + " does not own package " + pkg);
17680        }
17681    }
17682
17683    @Override
17684    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17685        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17686    }
17687
17688    private Intent getHomeIntent() {
17689        Intent intent = new Intent(Intent.ACTION_MAIN);
17690        intent.addCategory(Intent.CATEGORY_HOME);
17691        intent.addCategory(Intent.CATEGORY_DEFAULT);
17692        return intent;
17693    }
17694
17695    private IntentFilter getHomeFilter() {
17696        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17697        filter.addCategory(Intent.CATEGORY_HOME);
17698        filter.addCategory(Intent.CATEGORY_DEFAULT);
17699        return filter;
17700    }
17701
17702    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17703            int userId) {
17704        Intent intent  = getHomeIntent();
17705        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17706                PackageManager.GET_META_DATA, userId);
17707        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17708                true, false, false, userId);
17709
17710        allHomeCandidates.clear();
17711        if (list != null) {
17712            for (ResolveInfo ri : list) {
17713                allHomeCandidates.add(ri);
17714            }
17715        }
17716        return (preferred == null || preferred.activityInfo == null)
17717                ? null
17718                : new ComponentName(preferred.activityInfo.packageName,
17719                        preferred.activityInfo.name);
17720    }
17721
17722    @Override
17723    public void setHomeActivity(ComponentName comp, int userId) {
17724        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17725        getHomeActivitiesAsUser(homeActivities, userId);
17726
17727        boolean found = false;
17728
17729        final int size = homeActivities.size();
17730        final ComponentName[] set = new ComponentName[size];
17731        for (int i = 0; i < size; i++) {
17732            final ResolveInfo candidate = homeActivities.get(i);
17733            final ActivityInfo info = candidate.activityInfo;
17734            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17735            set[i] = activityName;
17736            if (!found && activityName.equals(comp)) {
17737                found = true;
17738            }
17739        }
17740        if (!found) {
17741            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17742                    + userId);
17743        }
17744        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17745                set, comp, userId);
17746    }
17747
17748    private @Nullable String getSetupWizardPackageName() {
17749        final Intent intent = new Intent(Intent.ACTION_MAIN);
17750        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17751
17752        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17753                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17754                        | MATCH_DISABLED_COMPONENTS,
17755                UserHandle.myUserId());
17756        if (matches.size() == 1) {
17757            return matches.get(0).getComponentInfo().packageName;
17758        } else {
17759            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17760                    + ": matches=" + matches);
17761            return null;
17762        }
17763    }
17764
17765    @Override
17766    public void setApplicationEnabledSetting(String appPackageName,
17767            int newState, int flags, int userId, String callingPackage) {
17768        if (!sUserManager.exists(userId)) return;
17769        if (callingPackage == null) {
17770            callingPackage = Integer.toString(Binder.getCallingUid());
17771        }
17772        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17773    }
17774
17775    @Override
17776    public void setComponentEnabledSetting(ComponentName componentName,
17777            int newState, int flags, int userId) {
17778        if (!sUserManager.exists(userId)) return;
17779        setEnabledSetting(componentName.getPackageName(),
17780                componentName.getClassName(), newState, flags, userId, null);
17781    }
17782
17783    private void setEnabledSetting(final String packageName, String className, int newState,
17784            final int flags, int userId, String callingPackage) {
17785        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17786              || newState == COMPONENT_ENABLED_STATE_ENABLED
17787              || newState == COMPONENT_ENABLED_STATE_DISABLED
17788              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17789              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17790            throw new IllegalArgumentException("Invalid new component state: "
17791                    + newState);
17792        }
17793        PackageSetting pkgSetting;
17794        final int uid = Binder.getCallingUid();
17795        final int permission;
17796        if (uid == Process.SYSTEM_UID) {
17797            permission = PackageManager.PERMISSION_GRANTED;
17798        } else {
17799            permission = mContext.checkCallingOrSelfPermission(
17800                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17801        }
17802        enforceCrossUserPermission(uid, userId,
17803                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17804        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17805        boolean sendNow = false;
17806        boolean isApp = (className == null);
17807        String componentName = isApp ? packageName : className;
17808        int packageUid = -1;
17809        ArrayList<String> components;
17810
17811        // writer
17812        synchronized (mPackages) {
17813            pkgSetting = mSettings.mPackages.get(packageName);
17814            if (pkgSetting == null) {
17815                if (className == null) {
17816                    throw new IllegalArgumentException("Unknown package: " + packageName);
17817                }
17818                throw new IllegalArgumentException(
17819                        "Unknown component: " + packageName + "/" + className);
17820            }
17821        }
17822
17823        // Limit who can change which apps
17824        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17825            // Don't allow apps that don't have permission to modify other apps
17826            if (!allowedByPermission) {
17827                throw new SecurityException(
17828                        "Permission Denial: attempt to change component state from pid="
17829                        + Binder.getCallingPid()
17830                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17831            }
17832            // Don't allow changing protected packages.
17833            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17834                throw new SecurityException("Cannot disable a protected package: " + packageName);
17835            }
17836        }
17837
17838        synchronized (mPackages) {
17839            if (uid == Process.SHELL_UID) {
17840                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17841                int oldState = pkgSetting.getEnabled(userId);
17842                if (className == null
17843                    &&
17844                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17845                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17846                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17847                    &&
17848                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17849                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17850                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17851                    // ok
17852                } else {
17853                    throw new SecurityException(
17854                            "Shell cannot change component state for " + packageName + "/"
17855                            + className + " to " + newState);
17856                }
17857            }
17858            if (className == null) {
17859                // We're dealing with an application/package level state change
17860                if (pkgSetting.getEnabled(userId) == newState) {
17861                    // Nothing to do
17862                    return;
17863                }
17864                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17865                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17866                    // Don't care about who enables an app.
17867                    callingPackage = null;
17868                }
17869                pkgSetting.setEnabled(newState, userId, callingPackage);
17870                // pkgSetting.pkg.mSetEnabled = newState;
17871            } else {
17872                // We're dealing with a component level state change
17873                // First, verify that this is a valid class name.
17874                PackageParser.Package pkg = pkgSetting.pkg;
17875                if (pkg == null || !pkg.hasComponentClassName(className)) {
17876                    if (pkg != null &&
17877                            pkg.applicationInfo.targetSdkVersion >=
17878                                    Build.VERSION_CODES.JELLY_BEAN) {
17879                        throw new IllegalArgumentException("Component class " + className
17880                                + " does not exist in " + packageName);
17881                    } else {
17882                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17883                                + className + " does not exist in " + packageName);
17884                    }
17885                }
17886                switch (newState) {
17887                case COMPONENT_ENABLED_STATE_ENABLED:
17888                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17889                        return;
17890                    }
17891                    break;
17892                case COMPONENT_ENABLED_STATE_DISABLED:
17893                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17894                        return;
17895                    }
17896                    break;
17897                case COMPONENT_ENABLED_STATE_DEFAULT:
17898                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17899                        return;
17900                    }
17901                    break;
17902                default:
17903                    Slog.e(TAG, "Invalid new component state: " + newState);
17904                    return;
17905                }
17906            }
17907            scheduleWritePackageRestrictionsLocked(userId);
17908            components = mPendingBroadcasts.get(userId, packageName);
17909            final boolean newPackage = components == null;
17910            if (newPackage) {
17911                components = new ArrayList<String>();
17912            }
17913            if (!components.contains(componentName)) {
17914                components.add(componentName);
17915            }
17916            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17917                sendNow = true;
17918                // Purge entry from pending broadcast list if another one exists already
17919                // since we are sending one right away.
17920                mPendingBroadcasts.remove(userId, packageName);
17921            } else {
17922                if (newPackage) {
17923                    mPendingBroadcasts.put(userId, packageName, components);
17924                }
17925                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17926                    // Schedule a message
17927                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17928                }
17929            }
17930        }
17931
17932        long callingId = Binder.clearCallingIdentity();
17933        try {
17934            if (sendNow) {
17935                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17936                sendPackageChangedBroadcast(packageName,
17937                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17938            }
17939        } finally {
17940            Binder.restoreCallingIdentity(callingId);
17941        }
17942    }
17943
17944    @Override
17945    public void flushPackageRestrictionsAsUser(int userId) {
17946        if (!sUserManager.exists(userId)) {
17947            return;
17948        }
17949        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17950                false /* checkShell */, "flushPackageRestrictions");
17951        synchronized (mPackages) {
17952            mSettings.writePackageRestrictionsLPr(userId);
17953            mDirtyUsers.remove(userId);
17954            if (mDirtyUsers.isEmpty()) {
17955                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17956            }
17957        }
17958    }
17959
17960    private void sendPackageChangedBroadcast(String packageName,
17961            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17962        if (DEBUG_INSTALL)
17963            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17964                    + componentNames);
17965        Bundle extras = new Bundle(4);
17966        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17967        String nameList[] = new String[componentNames.size()];
17968        componentNames.toArray(nameList);
17969        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17970        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17971        extras.putInt(Intent.EXTRA_UID, packageUid);
17972        // If this is not reporting a change of the overall package, then only send it
17973        // to registered receivers.  We don't want to launch a swath of apps for every
17974        // little component state change.
17975        final int flags = !componentNames.contains(packageName)
17976                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17977        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17978                new int[] {UserHandle.getUserId(packageUid)});
17979    }
17980
17981    @Override
17982    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17983        if (!sUserManager.exists(userId)) return;
17984        final int uid = Binder.getCallingUid();
17985        final int permission = mContext.checkCallingOrSelfPermission(
17986                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17987        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17988        enforceCrossUserPermission(uid, userId,
17989                true /* requireFullPermission */, true /* checkShell */, "stop package");
17990        // writer
17991        synchronized (mPackages) {
17992            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17993                    allowedByPermission, uid, userId)) {
17994                scheduleWritePackageRestrictionsLocked(userId);
17995            }
17996        }
17997    }
17998
17999    @Override
18000    public String getInstallerPackageName(String packageName) {
18001        // reader
18002        synchronized (mPackages) {
18003            return mSettings.getInstallerPackageNameLPr(packageName);
18004        }
18005    }
18006
18007    public boolean isOrphaned(String packageName) {
18008        // reader
18009        synchronized (mPackages) {
18010            return mSettings.isOrphaned(packageName);
18011        }
18012    }
18013
18014    @Override
18015    public int getApplicationEnabledSetting(String packageName, int userId) {
18016        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18017        int uid = Binder.getCallingUid();
18018        enforceCrossUserPermission(uid, userId,
18019                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18020        // reader
18021        synchronized (mPackages) {
18022            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18023        }
18024    }
18025
18026    @Override
18027    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18028        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18029        int uid = Binder.getCallingUid();
18030        enforceCrossUserPermission(uid, userId,
18031                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18032        // reader
18033        synchronized (mPackages) {
18034            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18035        }
18036    }
18037
18038    @Override
18039    public void enterSafeMode() {
18040        enforceSystemOrRoot("Only the system can request entering safe mode");
18041
18042        if (!mSystemReady) {
18043            mSafeMode = true;
18044        }
18045    }
18046
18047    @Override
18048    public void systemReady() {
18049        mSystemReady = true;
18050
18051        // Read the compatibilty setting when the system is ready.
18052        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18053                mContext.getContentResolver(),
18054                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18055        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18056        if (DEBUG_SETTINGS) {
18057            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18058        }
18059
18060        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18061
18062        synchronized (mPackages) {
18063            // Verify that all of the preferred activity components actually
18064            // exist.  It is possible for applications to be updated and at
18065            // that point remove a previously declared activity component that
18066            // had been set as a preferred activity.  We try to clean this up
18067            // the next time we encounter that preferred activity, but it is
18068            // possible for the user flow to never be able to return to that
18069            // situation so here we do a sanity check to make sure we haven't
18070            // left any junk around.
18071            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18072            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18073                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18074                removed.clear();
18075                for (PreferredActivity pa : pir.filterSet()) {
18076                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18077                        removed.add(pa);
18078                    }
18079                }
18080                if (removed.size() > 0) {
18081                    for (int r=0; r<removed.size(); r++) {
18082                        PreferredActivity pa = removed.get(r);
18083                        Slog.w(TAG, "Removing dangling preferred activity: "
18084                                + pa.mPref.mComponent);
18085                        pir.removeFilter(pa);
18086                    }
18087                    mSettings.writePackageRestrictionsLPr(
18088                            mSettings.mPreferredActivities.keyAt(i));
18089                }
18090            }
18091
18092            for (int userId : UserManagerService.getInstance().getUserIds()) {
18093                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18094                    grantPermissionsUserIds = ArrayUtils.appendInt(
18095                            grantPermissionsUserIds, userId);
18096                }
18097            }
18098        }
18099        sUserManager.systemReady();
18100
18101        // If we upgraded grant all default permissions before kicking off.
18102        for (int userId : grantPermissionsUserIds) {
18103            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18104        }
18105
18106        // Kick off any messages waiting for system ready
18107        if (mPostSystemReadyMessages != null) {
18108            for (Message msg : mPostSystemReadyMessages) {
18109                msg.sendToTarget();
18110            }
18111            mPostSystemReadyMessages = null;
18112        }
18113
18114        // Watch for external volumes that come and go over time
18115        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18116        storage.registerListener(mStorageListener);
18117
18118        mInstallerService.systemReady();
18119        mPackageDexOptimizer.systemReady();
18120
18121        MountServiceInternal mountServiceInternal = LocalServices.getService(
18122                MountServiceInternal.class);
18123        mountServiceInternal.addExternalStoragePolicy(
18124                new MountServiceInternal.ExternalStorageMountPolicy() {
18125            @Override
18126            public int getMountMode(int uid, String packageName) {
18127                if (Process.isIsolated(uid)) {
18128                    return Zygote.MOUNT_EXTERNAL_NONE;
18129                }
18130                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18131                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18132                }
18133                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18134                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18135                }
18136                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18137                    return Zygote.MOUNT_EXTERNAL_READ;
18138                }
18139                return Zygote.MOUNT_EXTERNAL_WRITE;
18140            }
18141
18142            @Override
18143            public boolean hasExternalStorage(int uid, String packageName) {
18144                return true;
18145            }
18146        });
18147
18148        // Now that we're mostly running, clean up stale users and apps
18149        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18150        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18151    }
18152
18153    @Override
18154    public boolean isSafeMode() {
18155        return mSafeMode;
18156    }
18157
18158    @Override
18159    public boolean hasSystemUidErrors() {
18160        return mHasSystemUidErrors;
18161    }
18162
18163    static String arrayToString(int[] array) {
18164        StringBuffer buf = new StringBuffer(128);
18165        buf.append('[');
18166        if (array != null) {
18167            for (int i=0; i<array.length; i++) {
18168                if (i > 0) buf.append(", ");
18169                buf.append(array[i]);
18170            }
18171        }
18172        buf.append(']');
18173        return buf.toString();
18174    }
18175
18176    static class DumpState {
18177        public static final int DUMP_LIBS = 1 << 0;
18178        public static final int DUMP_FEATURES = 1 << 1;
18179        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18180        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18181        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18182        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18183        public static final int DUMP_PERMISSIONS = 1 << 6;
18184        public static final int DUMP_PACKAGES = 1 << 7;
18185        public static final int DUMP_SHARED_USERS = 1 << 8;
18186        public static final int DUMP_MESSAGES = 1 << 9;
18187        public static final int DUMP_PROVIDERS = 1 << 10;
18188        public static final int DUMP_VERIFIERS = 1 << 11;
18189        public static final int DUMP_PREFERRED = 1 << 12;
18190        public static final int DUMP_PREFERRED_XML = 1 << 13;
18191        public static final int DUMP_KEYSETS = 1 << 14;
18192        public static final int DUMP_VERSION = 1 << 15;
18193        public static final int DUMP_INSTALLS = 1 << 16;
18194        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18195        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18196        public static final int DUMP_FROZEN = 1 << 19;
18197        public static final int DUMP_DEXOPT = 1 << 20;
18198
18199        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18200
18201        private int mTypes;
18202
18203        private int mOptions;
18204
18205        private boolean mTitlePrinted;
18206
18207        private SharedUserSetting mSharedUser;
18208
18209        public boolean isDumping(int type) {
18210            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18211                return true;
18212            }
18213
18214            return (mTypes & type) != 0;
18215        }
18216
18217        public void setDump(int type) {
18218            mTypes |= type;
18219        }
18220
18221        public boolean isOptionEnabled(int option) {
18222            return (mOptions & option) != 0;
18223        }
18224
18225        public void setOptionEnabled(int option) {
18226            mOptions |= option;
18227        }
18228
18229        public boolean onTitlePrinted() {
18230            final boolean printed = mTitlePrinted;
18231            mTitlePrinted = true;
18232            return printed;
18233        }
18234
18235        public boolean getTitlePrinted() {
18236            return mTitlePrinted;
18237        }
18238
18239        public void setTitlePrinted(boolean enabled) {
18240            mTitlePrinted = enabled;
18241        }
18242
18243        public SharedUserSetting getSharedUser() {
18244            return mSharedUser;
18245        }
18246
18247        public void setSharedUser(SharedUserSetting user) {
18248            mSharedUser = user;
18249        }
18250    }
18251
18252    @Override
18253    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18254            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18255        (new PackageManagerShellCommand(this)).exec(
18256                this, in, out, err, args, resultReceiver);
18257    }
18258
18259    @Override
18260    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18261        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18262                != PackageManager.PERMISSION_GRANTED) {
18263            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18264                    + Binder.getCallingPid()
18265                    + ", uid=" + Binder.getCallingUid()
18266                    + " without permission "
18267                    + android.Manifest.permission.DUMP);
18268            return;
18269        }
18270
18271        DumpState dumpState = new DumpState();
18272        boolean fullPreferred = false;
18273        boolean checkin = false;
18274
18275        String packageName = null;
18276        ArraySet<String> permissionNames = null;
18277
18278        int opti = 0;
18279        while (opti < args.length) {
18280            String opt = args[opti];
18281            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18282                break;
18283            }
18284            opti++;
18285
18286            if ("-a".equals(opt)) {
18287                // Right now we only know how to print all.
18288            } else if ("-h".equals(opt)) {
18289                pw.println("Package manager dump options:");
18290                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18291                pw.println("    --checkin: dump for a checkin");
18292                pw.println("    -f: print details of intent filters");
18293                pw.println("    -h: print this help");
18294                pw.println("  cmd may be one of:");
18295                pw.println("    l[ibraries]: list known shared libraries");
18296                pw.println("    f[eatures]: list device features");
18297                pw.println("    k[eysets]: print known keysets");
18298                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18299                pw.println("    perm[issions]: dump permissions");
18300                pw.println("    permission [name ...]: dump declaration and use of given permission");
18301                pw.println("    pref[erred]: print preferred package settings");
18302                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18303                pw.println("    prov[iders]: dump content providers");
18304                pw.println("    p[ackages]: dump installed packages");
18305                pw.println("    s[hared-users]: dump shared user IDs");
18306                pw.println("    m[essages]: print collected runtime messages");
18307                pw.println("    v[erifiers]: print package verifier info");
18308                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18309                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18310                pw.println("    version: print database version info");
18311                pw.println("    write: write current settings now");
18312                pw.println("    installs: details about install sessions");
18313                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18314                pw.println("    dexopt: dump dexopt state");
18315                pw.println("    <package.name>: info about given package");
18316                return;
18317            } else if ("--checkin".equals(opt)) {
18318                checkin = true;
18319            } else if ("-f".equals(opt)) {
18320                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18321            } else {
18322                pw.println("Unknown argument: " + opt + "; use -h for help");
18323            }
18324        }
18325
18326        // Is the caller requesting to dump a particular piece of data?
18327        if (opti < args.length) {
18328            String cmd = args[opti];
18329            opti++;
18330            // Is this a package name?
18331            if ("android".equals(cmd) || cmd.contains(".")) {
18332                packageName = cmd;
18333                // When dumping a single package, we always dump all of its
18334                // filter information since the amount of data will be reasonable.
18335                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18336            } else if ("check-permission".equals(cmd)) {
18337                if (opti >= args.length) {
18338                    pw.println("Error: check-permission missing permission argument");
18339                    return;
18340                }
18341                String perm = args[opti];
18342                opti++;
18343                if (opti >= args.length) {
18344                    pw.println("Error: check-permission missing package argument");
18345                    return;
18346                }
18347                String pkg = args[opti];
18348                opti++;
18349                int user = UserHandle.getUserId(Binder.getCallingUid());
18350                if (opti < args.length) {
18351                    try {
18352                        user = Integer.parseInt(args[opti]);
18353                    } catch (NumberFormatException e) {
18354                        pw.println("Error: check-permission user argument is not a number: "
18355                                + args[opti]);
18356                        return;
18357                    }
18358                }
18359                pw.println(checkPermission(perm, pkg, user));
18360                return;
18361            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18362                dumpState.setDump(DumpState.DUMP_LIBS);
18363            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18364                dumpState.setDump(DumpState.DUMP_FEATURES);
18365            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18366                if (opti >= args.length) {
18367                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18368                            | DumpState.DUMP_SERVICE_RESOLVERS
18369                            | DumpState.DUMP_RECEIVER_RESOLVERS
18370                            | DumpState.DUMP_CONTENT_RESOLVERS);
18371                } else {
18372                    while (opti < args.length) {
18373                        String name = args[opti];
18374                        if ("a".equals(name) || "activity".equals(name)) {
18375                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18376                        } else if ("s".equals(name) || "service".equals(name)) {
18377                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18378                        } else if ("r".equals(name) || "receiver".equals(name)) {
18379                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18380                        } else if ("c".equals(name) || "content".equals(name)) {
18381                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18382                        } else {
18383                            pw.println("Error: unknown resolver table type: " + name);
18384                            return;
18385                        }
18386                        opti++;
18387                    }
18388                }
18389            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18390                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18391            } else if ("permission".equals(cmd)) {
18392                if (opti >= args.length) {
18393                    pw.println("Error: permission requires permission name");
18394                    return;
18395                }
18396                permissionNames = new ArraySet<>();
18397                while (opti < args.length) {
18398                    permissionNames.add(args[opti]);
18399                    opti++;
18400                }
18401                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18402                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18403            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18404                dumpState.setDump(DumpState.DUMP_PREFERRED);
18405            } else if ("preferred-xml".equals(cmd)) {
18406                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18407                if (opti < args.length && "--full".equals(args[opti])) {
18408                    fullPreferred = true;
18409                    opti++;
18410                }
18411            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18412                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18413            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18414                dumpState.setDump(DumpState.DUMP_PACKAGES);
18415            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18416                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18417            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18418                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18419            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18420                dumpState.setDump(DumpState.DUMP_MESSAGES);
18421            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18422                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18423            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18424                    || "intent-filter-verifiers".equals(cmd)) {
18425                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18426            } else if ("version".equals(cmd)) {
18427                dumpState.setDump(DumpState.DUMP_VERSION);
18428            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18429                dumpState.setDump(DumpState.DUMP_KEYSETS);
18430            } else if ("installs".equals(cmd)) {
18431                dumpState.setDump(DumpState.DUMP_INSTALLS);
18432            } else if ("frozen".equals(cmd)) {
18433                dumpState.setDump(DumpState.DUMP_FROZEN);
18434            } else if ("dexopt".equals(cmd)) {
18435                dumpState.setDump(DumpState.DUMP_DEXOPT);
18436            } else if ("write".equals(cmd)) {
18437                synchronized (mPackages) {
18438                    mSettings.writeLPr();
18439                    pw.println("Settings written.");
18440                    return;
18441                }
18442            }
18443        }
18444
18445        if (checkin) {
18446            pw.println("vers,1");
18447        }
18448
18449        // reader
18450        synchronized (mPackages) {
18451            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18452                if (!checkin) {
18453                    if (dumpState.onTitlePrinted())
18454                        pw.println();
18455                    pw.println("Database versions:");
18456                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18457                }
18458            }
18459
18460            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18461                if (!checkin) {
18462                    if (dumpState.onTitlePrinted())
18463                        pw.println();
18464                    pw.println("Verifiers:");
18465                    pw.print("  Required: ");
18466                    pw.print(mRequiredVerifierPackage);
18467                    pw.print(" (uid=");
18468                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18469                            UserHandle.USER_SYSTEM));
18470                    pw.println(")");
18471                } else if (mRequiredVerifierPackage != null) {
18472                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18473                    pw.print(",");
18474                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18475                            UserHandle.USER_SYSTEM));
18476                }
18477            }
18478
18479            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18480                    packageName == null) {
18481                if (mIntentFilterVerifierComponent != null) {
18482                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18483                    if (!checkin) {
18484                        if (dumpState.onTitlePrinted())
18485                            pw.println();
18486                        pw.println("Intent Filter Verifier:");
18487                        pw.print("  Using: ");
18488                        pw.print(verifierPackageName);
18489                        pw.print(" (uid=");
18490                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18491                                UserHandle.USER_SYSTEM));
18492                        pw.println(")");
18493                    } else if (verifierPackageName != null) {
18494                        pw.print("ifv,"); pw.print(verifierPackageName);
18495                        pw.print(",");
18496                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18497                                UserHandle.USER_SYSTEM));
18498                    }
18499                } else {
18500                    pw.println();
18501                    pw.println("No Intent Filter Verifier available!");
18502                }
18503            }
18504
18505            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18506                boolean printedHeader = false;
18507                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18508                while (it.hasNext()) {
18509                    String name = it.next();
18510                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18511                    if (!checkin) {
18512                        if (!printedHeader) {
18513                            if (dumpState.onTitlePrinted())
18514                                pw.println();
18515                            pw.println("Libraries:");
18516                            printedHeader = true;
18517                        }
18518                        pw.print("  ");
18519                    } else {
18520                        pw.print("lib,");
18521                    }
18522                    pw.print(name);
18523                    if (!checkin) {
18524                        pw.print(" -> ");
18525                    }
18526                    if (ent.path != null) {
18527                        if (!checkin) {
18528                            pw.print("(jar) ");
18529                            pw.print(ent.path);
18530                        } else {
18531                            pw.print(",jar,");
18532                            pw.print(ent.path);
18533                        }
18534                    } else {
18535                        if (!checkin) {
18536                            pw.print("(apk) ");
18537                            pw.print(ent.apk);
18538                        } else {
18539                            pw.print(",apk,");
18540                            pw.print(ent.apk);
18541                        }
18542                    }
18543                    pw.println();
18544                }
18545            }
18546
18547            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18548                if (dumpState.onTitlePrinted())
18549                    pw.println();
18550                if (!checkin) {
18551                    pw.println("Features:");
18552                }
18553
18554                for (FeatureInfo feat : mAvailableFeatures.values()) {
18555                    if (checkin) {
18556                        pw.print("feat,");
18557                        pw.print(feat.name);
18558                        pw.print(",");
18559                        pw.println(feat.version);
18560                    } else {
18561                        pw.print("  ");
18562                        pw.print(feat.name);
18563                        if (feat.version > 0) {
18564                            pw.print(" version=");
18565                            pw.print(feat.version);
18566                        }
18567                        pw.println();
18568                    }
18569                }
18570            }
18571
18572            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18573                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18574                        : "Activity Resolver Table:", "  ", packageName,
18575                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18576                    dumpState.setTitlePrinted(true);
18577                }
18578            }
18579            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18580                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18581                        : "Receiver Resolver Table:", "  ", packageName,
18582                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18583                    dumpState.setTitlePrinted(true);
18584                }
18585            }
18586            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18587                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18588                        : "Service Resolver Table:", "  ", packageName,
18589                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18590                    dumpState.setTitlePrinted(true);
18591                }
18592            }
18593            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18594                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18595                        : "Provider Resolver Table:", "  ", packageName,
18596                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18597                    dumpState.setTitlePrinted(true);
18598                }
18599            }
18600
18601            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18602                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18603                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18604                    int user = mSettings.mPreferredActivities.keyAt(i);
18605                    if (pir.dump(pw,
18606                            dumpState.getTitlePrinted()
18607                                ? "\nPreferred Activities User " + user + ":"
18608                                : "Preferred Activities User " + user + ":", "  ",
18609                            packageName, true, false)) {
18610                        dumpState.setTitlePrinted(true);
18611                    }
18612                }
18613            }
18614
18615            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18616                pw.flush();
18617                FileOutputStream fout = new FileOutputStream(fd);
18618                BufferedOutputStream str = new BufferedOutputStream(fout);
18619                XmlSerializer serializer = new FastXmlSerializer();
18620                try {
18621                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18622                    serializer.startDocument(null, true);
18623                    serializer.setFeature(
18624                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18625                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18626                    serializer.endDocument();
18627                    serializer.flush();
18628                } catch (IllegalArgumentException e) {
18629                    pw.println("Failed writing: " + e);
18630                } catch (IllegalStateException e) {
18631                    pw.println("Failed writing: " + e);
18632                } catch (IOException e) {
18633                    pw.println("Failed writing: " + e);
18634                }
18635            }
18636
18637            if (!checkin
18638                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18639                    && packageName == null) {
18640                pw.println();
18641                int count = mSettings.mPackages.size();
18642                if (count == 0) {
18643                    pw.println("No applications!");
18644                    pw.println();
18645                } else {
18646                    final String prefix = "  ";
18647                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18648                    if (allPackageSettings.size() == 0) {
18649                        pw.println("No domain preferred apps!");
18650                        pw.println();
18651                    } else {
18652                        pw.println("App verification status:");
18653                        pw.println();
18654                        count = 0;
18655                        for (PackageSetting ps : allPackageSettings) {
18656                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18657                            if (ivi == null || ivi.getPackageName() == null) continue;
18658                            pw.println(prefix + "Package: " + ivi.getPackageName());
18659                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18660                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18661                            pw.println();
18662                            count++;
18663                        }
18664                        if (count == 0) {
18665                            pw.println(prefix + "No app verification established.");
18666                            pw.println();
18667                        }
18668                        for (int userId : sUserManager.getUserIds()) {
18669                            pw.println("App linkages for user " + userId + ":");
18670                            pw.println();
18671                            count = 0;
18672                            for (PackageSetting ps : allPackageSettings) {
18673                                final long status = ps.getDomainVerificationStatusForUser(userId);
18674                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18675                                    continue;
18676                                }
18677                                pw.println(prefix + "Package: " + ps.name);
18678                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18679                                String statusStr = IntentFilterVerificationInfo.
18680                                        getStatusStringFromValue(status);
18681                                pw.println(prefix + "Status:  " + statusStr);
18682                                pw.println();
18683                                count++;
18684                            }
18685                            if (count == 0) {
18686                                pw.println(prefix + "No configured app linkages.");
18687                                pw.println();
18688                            }
18689                        }
18690                    }
18691                }
18692            }
18693
18694            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18695                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18696                if (packageName == null && permissionNames == null) {
18697                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18698                        if (iperm == 0) {
18699                            if (dumpState.onTitlePrinted())
18700                                pw.println();
18701                            pw.println("AppOp Permissions:");
18702                        }
18703                        pw.print("  AppOp Permission ");
18704                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18705                        pw.println(":");
18706                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18707                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18708                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18709                        }
18710                    }
18711                }
18712            }
18713
18714            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18715                boolean printedSomething = false;
18716                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18717                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18718                        continue;
18719                    }
18720                    if (!printedSomething) {
18721                        if (dumpState.onTitlePrinted())
18722                            pw.println();
18723                        pw.println("Registered ContentProviders:");
18724                        printedSomething = true;
18725                    }
18726                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18727                    pw.print("    "); pw.println(p.toString());
18728                }
18729                printedSomething = false;
18730                for (Map.Entry<String, PackageParser.Provider> entry :
18731                        mProvidersByAuthority.entrySet()) {
18732                    PackageParser.Provider p = entry.getValue();
18733                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18734                        continue;
18735                    }
18736                    if (!printedSomething) {
18737                        if (dumpState.onTitlePrinted())
18738                            pw.println();
18739                        pw.println("ContentProvider Authorities:");
18740                        printedSomething = true;
18741                    }
18742                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18743                    pw.print("    "); pw.println(p.toString());
18744                    if (p.info != null && p.info.applicationInfo != null) {
18745                        final String appInfo = p.info.applicationInfo.toString();
18746                        pw.print("      applicationInfo="); pw.println(appInfo);
18747                    }
18748                }
18749            }
18750
18751            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18752                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18753            }
18754
18755            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18756                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18757            }
18758
18759            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18760                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18761            }
18762
18763            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18764                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18765            }
18766
18767            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18768                // XXX should handle packageName != null by dumping only install data that
18769                // the given package is involved with.
18770                if (dumpState.onTitlePrinted()) pw.println();
18771                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18772            }
18773
18774            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18775                // XXX should handle packageName != null by dumping only install data that
18776                // the given package is involved with.
18777                if (dumpState.onTitlePrinted()) pw.println();
18778
18779                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18780                ipw.println();
18781                ipw.println("Frozen packages:");
18782                ipw.increaseIndent();
18783                if (mFrozenPackages.size() == 0) {
18784                    ipw.println("(none)");
18785                } else {
18786                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18787                        ipw.println(mFrozenPackages.valueAt(i));
18788                    }
18789                }
18790                ipw.decreaseIndent();
18791            }
18792
18793            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18794                if (dumpState.onTitlePrinted()) pw.println();
18795                dumpDexoptStateLPr(pw, packageName);
18796            }
18797
18798            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18799                if (dumpState.onTitlePrinted()) pw.println();
18800                mSettings.dumpReadMessagesLPr(pw, dumpState);
18801
18802                pw.println();
18803                pw.println("Package warning messages:");
18804                BufferedReader in = null;
18805                String line = null;
18806                try {
18807                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18808                    while ((line = in.readLine()) != null) {
18809                        if (line.contains("ignored: updated version")) continue;
18810                        pw.println(line);
18811                    }
18812                } catch (IOException ignored) {
18813                } finally {
18814                    IoUtils.closeQuietly(in);
18815                }
18816            }
18817
18818            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18819                BufferedReader in = null;
18820                String line = null;
18821                try {
18822                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18823                    while ((line = in.readLine()) != null) {
18824                        if (line.contains("ignored: updated version")) continue;
18825                        pw.print("msg,");
18826                        pw.println(line);
18827                    }
18828                } catch (IOException ignored) {
18829                } finally {
18830                    IoUtils.closeQuietly(in);
18831                }
18832            }
18833        }
18834    }
18835
18836    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18837        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18838        ipw.println();
18839        ipw.println("Dexopt state:");
18840        ipw.increaseIndent();
18841        Collection<PackageParser.Package> packages = null;
18842        if (packageName != null) {
18843            PackageParser.Package targetPackage = mPackages.get(packageName);
18844            if (targetPackage != null) {
18845                packages = Collections.singletonList(targetPackage);
18846            } else {
18847                ipw.println("Unable to find package: " + packageName);
18848                return;
18849            }
18850        } else {
18851            packages = mPackages.values();
18852        }
18853
18854        for (PackageParser.Package pkg : packages) {
18855            ipw.println("[" + pkg.packageName + "]");
18856            ipw.increaseIndent();
18857            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18858            ipw.decreaseIndent();
18859        }
18860    }
18861
18862    private String dumpDomainString(String packageName) {
18863        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18864                .getList();
18865        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18866
18867        ArraySet<String> result = new ArraySet<>();
18868        if (iviList.size() > 0) {
18869            for (IntentFilterVerificationInfo ivi : iviList) {
18870                for (String host : ivi.getDomains()) {
18871                    result.add(host);
18872                }
18873            }
18874        }
18875        if (filters != null && filters.size() > 0) {
18876            for (IntentFilter filter : filters) {
18877                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18878                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18879                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18880                    result.addAll(filter.getHostsList());
18881                }
18882            }
18883        }
18884
18885        StringBuilder sb = new StringBuilder(result.size() * 16);
18886        for (String domain : result) {
18887            if (sb.length() > 0) sb.append(" ");
18888            sb.append(domain);
18889        }
18890        return sb.toString();
18891    }
18892
18893    // ------- apps on sdcard specific code -------
18894    static final boolean DEBUG_SD_INSTALL = false;
18895
18896    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18897
18898    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18899
18900    private boolean mMediaMounted = false;
18901
18902    static String getEncryptKey() {
18903        try {
18904            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18905                    SD_ENCRYPTION_KEYSTORE_NAME);
18906            if (sdEncKey == null) {
18907                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18908                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18909                if (sdEncKey == null) {
18910                    Slog.e(TAG, "Failed to create encryption keys");
18911                    return null;
18912                }
18913            }
18914            return sdEncKey;
18915        } catch (NoSuchAlgorithmException nsae) {
18916            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18917            return null;
18918        } catch (IOException ioe) {
18919            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18920            return null;
18921        }
18922    }
18923
18924    /*
18925     * Update media status on PackageManager.
18926     */
18927    @Override
18928    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18929        int callingUid = Binder.getCallingUid();
18930        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18931            throw new SecurityException("Media status can only be updated by the system");
18932        }
18933        // reader; this apparently protects mMediaMounted, but should probably
18934        // be a different lock in that case.
18935        synchronized (mPackages) {
18936            Log.i(TAG, "Updating external media status from "
18937                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18938                    + (mediaStatus ? "mounted" : "unmounted"));
18939            if (DEBUG_SD_INSTALL)
18940                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18941                        + ", mMediaMounted=" + mMediaMounted);
18942            if (mediaStatus == mMediaMounted) {
18943                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18944                        : 0, -1);
18945                mHandler.sendMessage(msg);
18946                return;
18947            }
18948            mMediaMounted = mediaStatus;
18949        }
18950        // Queue up an async operation since the package installation may take a
18951        // little while.
18952        mHandler.post(new Runnable() {
18953            public void run() {
18954                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18955            }
18956        });
18957    }
18958
18959    /**
18960     * Called by MountService when the initial ASECs to scan are available.
18961     * Should block until all the ASEC containers are finished being scanned.
18962     */
18963    public void scanAvailableAsecs() {
18964        updateExternalMediaStatusInner(true, false, false);
18965    }
18966
18967    /*
18968     * Collect information of applications on external media, map them against
18969     * existing containers and update information based on current mount status.
18970     * Please note that we always have to report status if reportStatus has been
18971     * set to true especially when unloading packages.
18972     */
18973    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18974            boolean externalStorage) {
18975        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18976        int[] uidArr = EmptyArray.INT;
18977
18978        final String[] list = PackageHelper.getSecureContainerList();
18979        if (ArrayUtils.isEmpty(list)) {
18980            Log.i(TAG, "No secure containers found");
18981        } else {
18982            // Process list of secure containers and categorize them
18983            // as active or stale based on their package internal state.
18984
18985            // reader
18986            synchronized (mPackages) {
18987                for (String cid : list) {
18988                    // Leave stages untouched for now; installer service owns them
18989                    if (PackageInstallerService.isStageName(cid)) continue;
18990
18991                    if (DEBUG_SD_INSTALL)
18992                        Log.i(TAG, "Processing container " + cid);
18993                    String pkgName = getAsecPackageName(cid);
18994                    if (pkgName == null) {
18995                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18996                        continue;
18997                    }
18998                    if (DEBUG_SD_INSTALL)
18999                        Log.i(TAG, "Looking for pkg : " + pkgName);
19000
19001                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19002                    if (ps == null) {
19003                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19004                        continue;
19005                    }
19006
19007                    /*
19008                     * Skip packages that are not external if we're unmounting
19009                     * external storage.
19010                     */
19011                    if (externalStorage && !isMounted && !isExternal(ps)) {
19012                        continue;
19013                    }
19014
19015                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19016                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19017                    // The package status is changed only if the code path
19018                    // matches between settings and the container id.
19019                    if (ps.codePathString != null
19020                            && ps.codePathString.startsWith(args.getCodePath())) {
19021                        if (DEBUG_SD_INSTALL) {
19022                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19023                                    + " at code path: " + ps.codePathString);
19024                        }
19025
19026                        // We do have a valid package installed on sdcard
19027                        processCids.put(args, ps.codePathString);
19028                        final int uid = ps.appId;
19029                        if (uid != -1) {
19030                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19031                        }
19032                    } else {
19033                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19034                                + ps.codePathString);
19035                    }
19036                }
19037            }
19038
19039            Arrays.sort(uidArr);
19040        }
19041
19042        // Process packages with valid entries.
19043        if (isMounted) {
19044            if (DEBUG_SD_INSTALL)
19045                Log.i(TAG, "Loading packages");
19046            loadMediaPackages(processCids, uidArr, externalStorage);
19047            startCleaningPackages();
19048            mInstallerService.onSecureContainersAvailable();
19049        } else {
19050            if (DEBUG_SD_INSTALL)
19051                Log.i(TAG, "Unloading packages");
19052            unloadMediaPackages(processCids, uidArr, reportStatus);
19053        }
19054    }
19055
19056    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19057            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19058        final int size = infos.size();
19059        final String[] packageNames = new String[size];
19060        final int[] packageUids = new int[size];
19061        for (int i = 0; i < size; i++) {
19062            final ApplicationInfo info = infos.get(i);
19063            packageNames[i] = info.packageName;
19064            packageUids[i] = info.uid;
19065        }
19066        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19067                finishedReceiver);
19068    }
19069
19070    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19071            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19072        sendResourcesChangedBroadcast(mediaStatus, replacing,
19073                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19074    }
19075
19076    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19077            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19078        int size = pkgList.length;
19079        if (size > 0) {
19080            // Send broadcasts here
19081            Bundle extras = new Bundle();
19082            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19083            if (uidArr != null) {
19084                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19085            }
19086            if (replacing) {
19087                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19088            }
19089            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19090                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19091            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19092        }
19093    }
19094
19095   /*
19096     * Look at potentially valid container ids from processCids If package
19097     * information doesn't match the one on record or package scanning fails,
19098     * the cid is added to list of removeCids. We currently don't delete stale
19099     * containers.
19100     */
19101    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19102            boolean externalStorage) {
19103        ArrayList<String> pkgList = new ArrayList<String>();
19104        Set<AsecInstallArgs> keys = processCids.keySet();
19105
19106        for (AsecInstallArgs args : keys) {
19107            String codePath = processCids.get(args);
19108            if (DEBUG_SD_INSTALL)
19109                Log.i(TAG, "Loading container : " + args.cid);
19110            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19111            try {
19112                // Make sure there are no container errors first.
19113                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19114                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19115                            + " when installing from sdcard");
19116                    continue;
19117                }
19118                // Check code path here.
19119                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19120                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19121                            + " does not match one in settings " + codePath);
19122                    continue;
19123                }
19124                // Parse package
19125                int parseFlags = mDefParseFlags;
19126                if (args.isExternalAsec()) {
19127                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19128                }
19129                if (args.isFwdLocked()) {
19130                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19131                }
19132
19133                synchronized (mInstallLock) {
19134                    PackageParser.Package pkg = null;
19135                    try {
19136                        // Sadly we don't know the package name yet to freeze it
19137                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19138                                SCAN_IGNORE_FROZEN, 0, null);
19139                    } catch (PackageManagerException e) {
19140                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19141                    }
19142                    // Scan the package
19143                    if (pkg != null) {
19144                        /*
19145                         * TODO why is the lock being held? doPostInstall is
19146                         * called in other places without the lock. This needs
19147                         * to be straightened out.
19148                         */
19149                        // writer
19150                        synchronized (mPackages) {
19151                            retCode = PackageManager.INSTALL_SUCCEEDED;
19152                            pkgList.add(pkg.packageName);
19153                            // Post process args
19154                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19155                                    pkg.applicationInfo.uid);
19156                        }
19157                    } else {
19158                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19159                    }
19160                }
19161
19162            } finally {
19163                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19164                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19165                }
19166            }
19167        }
19168        // writer
19169        synchronized (mPackages) {
19170            // If the platform SDK has changed since the last time we booted,
19171            // we need to re-grant app permission to catch any new ones that
19172            // appear. This is really a hack, and means that apps can in some
19173            // cases get permissions that the user didn't initially explicitly
19174            // allow... it would be nice to have some better way to handle
19175            // this situation.
19176            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19177                    : mSettings.getInternalVersion();
19178            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19179                    : StorageManager.UUID_PRIVATE_INTERNAL;
19180
19181            int updateFlags = UPDATE_PERMISSIONS_ALL;
19182            if (ver.sdkVersion != mSdkVersion) {
19183                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19184                        + mSdkVersion + "; regranting permissions for external");
19185                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19186            }
19187            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19188
19189            // Yay, everything is now upgraded
19190            ver.forceCurrent();
19191
19192            // can downgrade to reader
19193            // Persist settings
19194            mSettings.writeLPr();
19195        }
19196        // Send a broadcast to let everyone know we are done processing
19197        if (pkgList.size() > 0) {
19198            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19199        }
19200    }
19201
19202   /*
19203     * Utility method to unload a list of specified containers
19204     */
19205    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19206        // Just unmount all valid containers.
19207        for (AsecInstallArgs arg : cidArgs) {
19208            synchronized (mInstallLock) {
19209                arg.doPostDeleteLI(false);
19210           }
19211       }
19212   }
19213
19214    /*
19215     * Unload packages mounted on external media. This involves deleting package
19216     * data from internal structures, sending broadcasts about disabled packages,
19217     * gc'ing to free up references, unmounting all secure containers
19218     * corresponding to packages on external media, and posting a
19219     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19220     * that we always have to post this message if status has been requested no
19221     * matter what.
19222     */
19223    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19224            final boolean reportStatus) {
19225        if (DEBUG_SD_INSTALL)
19226            Log.i(TAG, "unloading media packages");
19227        ArrayList<String> pkgList = new ArrayList<String>();
19228        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19229        final Set<AsecInstallArgs> keys = processCids.keySet();
19230        for (AsecInstallArgs args : keys) {
19231            String pkgName = args.getPackageName();
19232            if (DEBUG_SD_INSTALL)
19233                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19234            // Delete package internally
19235            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19236            synchronized (mInstallLock) {
19237                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19238                final boolean res;
19239                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19240                        "unloadMediaPackages")) {
19241                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19242                            null);
19243                }
19244                if (res) {
19245                    pkgList.add(pkgName);
19246                } else {
19247                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19248                    failedList.add(args);
19249                }
19250            }
19251        }
19252
19253        // reader
19254        synchronized (mPackages) {
19255            // We didn't update the settings after removing each package;
19256            // write them now for all packages.
19257            mSettings.writeLPr();
19258        }
19259
19260        // We have to absolutely send UPDATED_MEDIA_STATUS only
19261        // after confirming that all the receivers processed the ordered
19262        // broadcast when packages get disabled, force a gc to clean things up.
19263        // and unload all the containers.
19264        if (pkgList.size() > 0) {
19265            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19266                    new IIntentReceiver.Stub() {
19267                public void performReceive(Intent intent, int resultCode, String data,
19268                        Bundle extras, boolean ordered, boolean sticky,
19269                        int sendingUser) throws RemoteException {
19270                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19271                            reportStatus ? 1 : 0, 1, keys);
19272                    mHandler.sendMessage(msg);
19273                }
19274            });
19275        } else {
19276            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19277                    keys);
19278            mHandler.sendMessage(msg);
19279        }
19280    }
19281
19282    private void loadPrivatePackages(final VolumeInfo vol) {
19283        mHandler.post(new Runnable() {
19284            @Override
19285            public void run() {
19286                loadPrivatePackagesInner(vol);
19287            }
19288        });
19289    }
19290
19291    private void loadPrivatePackagesInner(VolumeInfo vol) {
19292        final String volumeUuid = vol.fsUuid;
19293        if (TextUtils.isEmpty(volumeUuid)) {
19294            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19295            return;
19296        }
19297
19298        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19299        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19300        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19301
19302        final VersionInfo ver;
19303        final List<PackageSetting> packages;
19304        synchronized (mPackages) {
19305            ver = mSettings.findOrCreateVersion(volumeUuid);
19306            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19307        }
19308
19309        for (PackageSetting ps : packages) {
19310            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19311            synchronized (mInstallLock) {
19312                final PackageParser.Package pkg;
19313                try {
19314                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19315                    loaded.add(pkg.applicationInfo);
19316
19317                } catch (PackageManagerException e) {
19318                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19319                }
19320
19321                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19322                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19323                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19324                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19325                }
19326            }
19327        }
19328
19329        // Reconcile app data for all started/unlocked users
19330        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19331        final UserManager um = mContext.getSystemService(UserManager.class);
19332        UserManagerInternal umInternal = getUserManagerInternal();
19333        for (UserInfo user : um.getUsers()) {
19334            final int flags;
19335            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19336                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19337            } else if (umInternal.isUserRunning(user.id)) {
19338                flags = StorageManager.FLAG_STORAGE_DE;
19339            } else {
19340                continue;
19341            }
19342
19343            try {
19344                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19345                synchronized (mInstallLock) {
19346                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19347                }
19348            } catch (IllegalStateException e) {
19349                // Device was probably ejected, and we'll process that event momentarily
19350                Slog.w(TAG, "Failed to prepare storage: " + e);
19351            }
19352        }
19353
19354        synchronized (mPackages) {
19355            int updateFlags = UPDATE_PERMISSIONS_ALL;
19356            if (ver.sdkVersion != mSdkVersion) {
19357                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19358                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19359                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19360            }
19361            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19362
19363            // Yay, everything is now upgraded
19364            ver.forceCurrent();
19365
19366            mSettings.writeLPr();
19367        }
19368
19369        for (PackageFreezer freezer : freezers) {
19370            freezer.close();
19371        }
19372
19373        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19374        sendResourcesChangedBroadcast(true, false, loaded, null);
19375    }
19376
19377    private void unloadPrivatePackages(final VolumeInfo vol) {
19378        mHandler.post(new Runnable() {
19379            @Override
19380            public void run() {
19381                unloadPrivatePackagesInner(vol);
19382            }
19383        });
19384    }
19385
19386    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19387        final String volumeUuid = vol.fsUuid;
19388        if (TextUtils.isEmpty(volumeUuid)) {
19389            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19390            return;
19391        }
19392
19393        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19394        synchronized (mInstallLock) {
19395        synchronized (mPackages) {
19396            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19397            for (PackageSetting ps : packages) {
19398                if (ps.pkg == null) continue;
19399
19400                final ApplicationInfo info = ps.pkg.applicationInfo;
19401                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19402                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19403
19404                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19405                        "unloadPrivatePackagesInner")) {
19406                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19407                            false, null)) {
19408                        unloaded.add(info);
19409                    } else {
19410                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19411                    }
19412                }
19413
19414                // Try very hard to release any references to this package
19415                // so we don't risk the system server being killed due to
19416                // open FDs
19417                AttributeCache.instance().removePackage(ps.name);
19418            }
19419
19420            mSettings.writeLPr();
19421        }
19422        }
19423
19424        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19425        sendResourcesChangedBroadcast(false, false, unloaded, null);
19426
19427        // Try very hard to release any references to this path so we don't risk
19428        // the system server being killed due to open FDs
19429        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19430
19431        for (int i = 0; i < 3; i++) {
19432            System.gc();
19433            System.runFinalization();
19434        }
19435    }
19436
19437    /**
19438     * Prepare storage areas for given user on all mounted devices.
19439     */
19440    void prepareUserData(int userId, int userSerial, int flags) {
19441        synchronized (mInstallLock) {
19442            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19443            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19444                final String volumeUuid = vol.getFsUuid();
19445                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19446            }
19447        }
19448    }
19449
19450    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19451            boolean allowRecover) {
19452        // Prepare storage and verify that serial numbers are consistent; if
19453        // there's a mismatch we need to destroy to avoid leaking data
19454        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19455        try {
19456            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19457
19458            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19459                UserManagerService.enforceSerialNumber(
19460                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19461                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19462                    UserManagerService.enforceSerialNumber(
19463                            Environment.getDataSystemDeDirectory(userId), userSerial);
19464                }
19465            }
19466            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19467                UserManagerService.enforceSerialNumber(
19468                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19469                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19470                    UserManagerService.enforceSerialNumber(
19471                            Environment.getDataSystemCeDirectory(userId), userSerial);
19472                }
19473            }
19474
19475            synchronized (mInstallLock) {
19476                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19477            }
19478        } catch (Exception e) {
19479            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19480                    + " because we failed to prepare: " + e);
19481            destroyUserDataLI(volumeUuid, userId,
19482                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19483
19484            if (allowRecover) {
19485                // Try one last time; if we fail again we're really in trouble
19486                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19487            }
19488        }
19489    }
19490
19491    /**
19492     * Destroy storage areas for given user on all mounted devices.
19493     */
19494    void destroyUserData(int userId, int flags) {
19495        synchronized (mInstallLock) {
19496            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19497            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19498                final String volumeUuid = vol.getFsUuid();
19499                destroyUserDataLI(volumeUuid, userId, flags);
19500            }
19501        }
19502    }
19503
19504    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19505        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19506        try {
19507            // Clean up app data, profile data, and media data
19508            mInstaller.destroyUserData(volumeUuid, userId, flags);
19509
19510            // Clean up system data
19511            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19512                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19513                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19514                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19515                }
19516                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19517                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19518                }
19519            }
19520
19521            // Data with special labels is now gone, so finish the job
19522            storage.destroyUserStorage(volumeUuid, userId, flags);
19523
19524        } catch (Exception e) {
19525            logCriticalInfo(Log.WARN,
19526                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19527        }
19528    }
19529
19530    /**
19531     * Examine all users present on given mounted volume, and destroy data
19532     * belonging to users that are no longer valid, or whose user ID has been
19533     * recycled.
19534     */
19535    private void reconcileUsers(String volumeUuid) {
19536        final List<File> files = new ArrayList<>();
19537        Collections.addAll(files, FileUtils
19538                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19539        Collections.addAll(files, FileUtils
19540                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19541        Collections.addAll(files, FileUtils
19542                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19543        Collections.addAll(files, FileUtils
19544                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19545        for (File file : files) {
19546            if (!file.isDirectory()) continue;
19547
19548            final int userId;
19549            final UserInfo info;
19550            try {
19551                userId = Integer.parseInt(file.getName());
19552                info = sUserManager.getUserInfo(userId);
19553            } catch (NumberFormatException e) {
19554                Slog.w(TAG, "Invalid user directory " + file);
19555                continue;
19556            }
19557
19558            boolean destroyUser = false;
19559            if (info == null) {
19560                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19561                        + " because no matching user was found");
19562                destroyUser = true;
19563            } else if (!mOnlyCore) {
19564                try {
19565                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19566                } catch (IOException e) {
19567                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19568                            + " because we failed to enforce serial number: " + e);
19569                    destroyUser = true;
19570                }
19571            }
19572
19573            if (destroyUser) {
19574                synchronized (mInstallLock) {
19575                    destroyUserDataLI(volumeUuid, userId,
19576                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19577                }
19578            }
19579        }
19580    }
19581
19582    private void assertPackageKnown(String volumeUuid, String packageName)
19583            throws PackageManagerException {
19584        synchronized (mPackages) {
19585            final PackageSetting ps = mSettings.mPackages.get(packageName);
19586            if (ps == null) {
19587                throw new PackageManagerException("Package " + packageName + " is unknown");
19588            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19589                throw new PackageManagerException(
19590                        "Package " + packageName + " found on unknown volume " + volumeUuid
19591                                + "; expected volume " + ps.volumeUuid);
19592            }
19593        }
19594    }
19595
19596    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19597            throws PackageManagerException {
19598        synchronized (mPackages) {
19599            final PackageSetting ps = mSettings.mPackages.get(packageName);
19600            if (ps == null) {
19601                throw new PackageManagerException("Package " + packageName + " is unknown");
19602            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19603                throw new PackageManagerException(
19604                        "Package " + packageName + " found on unknown volume " + volumeUuid
19605                                + "; expected volume " + ps.volumeUuid);
19606            } else if (!ps.getInstalled(userId)) {
19607                throw new PackageManagerException(
19608                        "Package " + packageName + " not installed for user " + userId);
19609            }
19610        }
19611    }
19612
19613    /**
19614     * Examine all apps present on given mounted volume, and destroy apps that
19615     * aren't expected, either due to uninstallation or reinstallation on
19616     * another volume.
19617     */
19618    private void reconcileApps(String volumeUuid) {
19619        final File[] files = FileUtils
19620                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19621        for (File file : files) {
19622            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19623                    && !PackageInstallerService.isStageName(file.getName());
19624            if (!isPackage) {
19625                // Ignore entries which are not packages
19626                continue;
19627            }
19628
19629            try {
19630                final PackageLite pkg = PackageParser.parsePackageLite(file,
19631                        PackageParser.PARSE_MUST_BE_APK);
19632                assertPackageKnown(volumeUuid, pkg.packageName);
19633
19634            } catch (PackageParserException | PackageManagerException e) {
19635                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19636                synchronized (mInstallLock) {
19637                    removeCodePathLI(file);
19638                }
19639            }
19640        }
19641    }
19642
19643    /**
19644     * Reconcile all app data for the given user.
19645     * <p>
19646     * Verifies that directories exist and that ownership and labeling is
19647     * correct for all installed apps on all mounted volumes.
19648     */
19649    void reconcileAppsData(int userId, int flags) {
19650        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19651        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19652            final String volumeUuid = vol.getFsUuid();
19653            synchronized (mInstallLock) {
19654                reconcileAppsDataLI(volumeUuid, userId, flags);
19655            }
19656        }
19657    }
19658
19659    /**
19660     * Reconcile all app data on given mounted volume.
19661     * <p>
19662     * Destroys app data that isn't expected, either due to uninstallation or
19663     * reinstallation on another volume.
19664     * <p>
19665     * Verifies that directories exist and that ownership and labeling is
19666     * correct for all installed apps.
19667     */
19668    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19669        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19670                + Integer.toHexString(flags));
19671
19672        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19673        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19674
19675        boolean restoreconNeeded = false;
19676
19677        // First look for stale data that doesn't belong, and check if things
19678        // have changed since we did our last restorecon
19679        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19680            if (StorageManager.isFileEncryptedNativeOrEmulated()
19681                    && !StorageManager.isUserKeyUnlocked(userId)) {
19682                throw new RuntimeException(
19683                        "Yikes, someone asked us to reconcile CE storage while " + userId
19684                                + " was still locked; this would have caused massive data loss!");
19685            }
19686
19687            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19688
19689            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19690            for (File file : files) {
19691                final String packageName = file.getName();
19692                try {
19693                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19694                } catch (PackageManagerException e) {
19695                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19696                    try {
19697                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19698                                StorageManager.FLAG_STORAGE_CE, 0);
19699                    } catch (InstallerException e2) {
19700                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19701                    }
19702                }
19703            }
19704        }
19705        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19706            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19707
19708            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19709            for (File file : files) {
19710                final String packageName = file.getName();
19711                try {
19712                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19713                } catch (PackageManagerException e) {
19714                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19715                    try {
19716                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19717                                StorageManager.FLAG_STORAGE_DE, 0);
19718                    } catch (InstallerException e2) {
19719                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19720                    }
19721                }
19722            }
19723        }
19724
19725        // Ensure that data directories are ready to roll for all packages
19726        // installed for this volume and user
19727        final List<PackageSetting> packages;
19728        synchronized (mPackages) {
19729            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19730        }
19731        int preparedCount = 0;
19732        for (PackageSetting ps : packages) {
19733            final String packageName = ps.name;
19734            if (ps.pkg == null) {
19735                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19736                // TODO: might be due to legacy ASEC apps; we should circle back
19737                // and reconcile again once they're scanned
19738                continue;
19739            }
19740
19741            if (ps.getInstalled(userId)) {
19742                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19743
19744                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19745                    // We may have just shuffled around app data directories, so
19746                    // prepare them one more time
19747                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19748                }
19749
19750                preparedCount++;
19751            }
19752        }
19753
19754        if (restoreconNeeded) {
19755            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19756                SELinuxMMAC.setRestoreconDone(ceDir);
19757            }
19758            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19759                SELinuxMMAC.setRestoreconDone(deDir);
19760            }
19761        }
19762
19763        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19764                + " packages; restoreconNeeded was " + restoreconNeeded);
19765    }
19766
19767    /**
19768     * Prepare app data for the given app just after it was installed or
19769     * upgraded. This method carefully only touches users that it's installed
19770     * for, and it forces a restorecon to handle any seinfo changes.
19771     * <p>
19772     * Verifies that directories exist and that ownership and labeling is
19773     * correct for all installed apps. If there is an ownership mismatch, it
19774     * will try recovering system apps by wiping data; third-party app data is
19775     * left intact.
19776     * <p>
19777     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19778     */
19779    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19780        final PackageSetting ps;
19781        synchronized (mPackages) {
19782            ps = mSettings.mPackages.get(pkg.packageName);
19783            mSettings.writeKernelMappingLPr(ps);
19784        }
19785
19786        final UserManager um = mContext.getSystemService(UserManager.class);
19787        UserManagerInternal umInternal = getUserManagerInternal();
19788        for (UserInfo user : um.getUsers()) {
19789            final int flags;
19790            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19791                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19792            } else if (umInternal.isUserRunning(user.id)) {
19793                flags = StorageManager.FLAG_STORAGE_DE;
19794            } else {
19795                continue;
19796            }
19797
19798            if (ps.getInstalled(user.id)) {
19799                // Whenever an app changes, force a restorecon of its data
19800                // TODO: when user data is locked, mark that we're still dirty
19801                prepareAppDataLIF(pkg, user.id, flags, true);
19802            }
19803        }
19804    }
19805
19806    /**
19807     * Prepare app data for the given app.
19808     * <p>
19809     * Verifies that directories exist and that ownership and labeling is
19810     * correct for all installed apps. If there is an ownership mismatch, this
19811     * will try recovering system apps by wiping data; third-party app data is
19812     * left intact.
19813     */
19814    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19815            boolean restoreconNeeded) {
19816        if (pkg == null) {
19817            Slog.wtf(TAG, "Package was null!", new Throwable());
19818            return;
19819        }
19820        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19822        for (int i = 0; i < childCount; i++) {
19823            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19824        }
19825    }
19826
19827    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19828            boolean restoreconNeeded) {
19829        if (DEBUG_APP_DATA) {
19830            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19831                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19832        }
19833
19834        final String volumeUuid = pkg.volumeUuid;
19835        final String packageName = pkg.packageName;
19836        final ApplicationInfo app = pkg.applicationInfo;
19837        final int appId = UserHandle.getAppId(app.uid);
19838
19839        Preconditions.checkNotNull(app.seinfo);
19840
19841        try {
19842            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19843                    appId, app.seinfo, app.targetSdkVersion);
19844        } catch (InstallerException e) {
19845            if (app.isSystemApp()) {
19846                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19847                        + ", but trying to recover: " + e);
19848                destroyAppDataLeafLIF(pkg, userId, flags);
19849                try {
19850                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19851                            appId, app.seinfo, app.targetSdkVersion);
19852                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19853                } catch (InstallerException e2) {
19854                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19855                }
19856            } else {
19857                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19858            }
19859        }
19860
19861        if (restoreconNeeded) {
19862            try {
19863                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19864                        app.seinfo);
19865            } catch (InstallerException e) {
19866                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19867            }
19868        }
19869
19870        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19871            try {
19872                // CE storage is unlocked right now, so read out the inode and
19873                // remember for use later when it's locked
19874                // TODO: mark this structure as dirty so we persist it!
19875                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19876                        StorageManager.FLAG_STORAGE_CE);
19877                synchronized (mPackages) {
19878                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19879                    if (ps != null) {
19880                        ps.setCeDataInode(ceDataInode, userId);
19881                    }
19882                }
19883            } catch (InstallerException e) {
19884                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19885            }
19886        }
19887
19888        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19889    }
19890
19891    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19892        if (pkg == null) {
19893            Slog.wtf(TAG, "Package was null!", new Throwable());
19894            return;
19895        }
19896        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19897        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19898        for (int i = 0; i < childCount; i++) {
19899            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19900        }
19901    }
19902
19903    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19904        final String volumeUuid = pkg.volumeUuid;
19905        final String packageName = pkg.packageName;
19906        final ApplicationInfo app = pkg.applicationInfo;
19907
19908        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19909            // Create a native library symlink only if we have native libraries
19910            // and if the native libraries are 32 bit libraries. We do not provide
19911            // this symlink for 64 bit libraries.
19912            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19913                final String nativeLibPath = app.nativeLibraryDir;
19914                try {
19915                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19916                            nativeLibPath, userId);
19917                } catch (InstallerException e) {
19918                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19919                }
19920            }
19921        }
19922    }
19923
19924    /**
19925     * For system apps on non-FBE devices, this method migrates any existing
19926     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19927     * requested by the app.
19928     */
19929    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19930        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19931                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19932            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19933                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19934            try {
19935                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19936                        storageTarget);
19937            } catch (InstallerException e) {
19938                logCriticalInfo(Log.WARN,
19939                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19940            }
19941            return true;
19942        } else {
19943            return false;
19944        }
19945    }
19946
19947    public PackageFreezer freezePackage(String packageName, String killReason) {
19948        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19949    }
19950
19951    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19952        return new PackageFreezer(packageName, userId, killReason);
19953    }
19954
19955    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19956            String killReason) {
19957        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19958    }
19959
19960    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19961            String killReason) {
19962        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19963            return new PackageFreezer();
19964        } else {
19965            return freezePackage(packageName, userId, killReason);
19966        }
19967    }
19968
19969    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19970            String killReason) {
19971        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19972    }
19973
19974    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19975            String killReason) {
19976        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19977            return new PackageFreezer();
19978        } else {
19979            return freezePackage(packageName, userId, killReason);
19980        }
19981    }
19982
19983    /**
19984     * Class that freezes and kills the given package upon creation, and
19985     * unfreezes it upon closing. This is typically used when doing surgery on
19986     * app code/data to prevent the app from running while you're working.
19987     */
19988    private class PackageFreezer implements AutoCloseable {
19989        private final String mPackageName;
19990        private final PackageFreezer[] mChildren;
19991
19992        private final boolean mWeFroze;
19993
19994        private final AtomicBoolean mClosed = new AtomicBoolean();
19995        private final CloseGuard mCloseGuard = CloseGuard.get();
19996
19997        /**
19998         * Create and return a stub freezer that doesn't actually do anything,
19999         * typically used when someone requested
20000         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20001         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20002         */
20003        public PackageFreezer() {
20004            mPackageName = null;
20005            mChildren = null;
20006            mWeFroze = false;
20007            mCloseGuard.open("close");
20008        }
20009
20010        public PackageFreezer(String packageName, int userId, String killReason) {
20011            synchronized (mPackages) {
20012                mPackageName = packageName;
20013                mWeFroze = mFrozenPackages.add(mPackageName);
20014
20015                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20016                if (ps != null) {
20017                    killApplication(ps.name, ps.appId, userId, killReason);
20018                }
20019
20020                final PackageParser.Package p = mPackages.get(packageName);
20021                if (p != null && p.childPackages != null) {
20022                    final int N = p.childPackages.size();
20023                    mChildren = new PackageFreezer[N];
20024                    for (int i = 0; i < N; i++) {
20025                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20026                                userId, killReason);
20027                    }
20028                } else {
20029                    mChildren = null;
20030                }
20031            }
20032            mCloseGuard.open("close");
20033        }
20034
20035        @Override
20036        protected void finalize() throws Throwable {
20037            try {
20038                mCloseGuard.warnIfOpen();
20039                close();
20040            } finally {
20041                super.finalize();
20042            }
20043        }
20044
20045        @Override
20046        public void close() {
20047            mCloseGuard.close();
20048            if (mClosed.compareAndSet(false, true)) {
20049                synchronized (mPackages) {
20050                    if (mWeFroze) {
20051                        mFrozenPackages.remove(mPackageName);
20052                    }
20053
20054                    if (mChildren != null) {
20055                        for (PackageFreezer freezer : mChildren) {
20056                            freezer.close();
20057                        }
20058                    }
20059                }
20060            }
20061        }
20062    }
20063
20064    /**
20065     * Verify that given package is currently frozen.
20066     */
20067    private void checkPackageFrozen(String packageName) {
20068        synchronized (mPackages) {
20069            if (!mFrozenPackages.contains(packageName)) {
20070                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20071            }
20072        }
20073    }
20074
20075    @Override
20076    public int movePackage(final String packageName, final String volumeUuid) {
20077        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20078
20079        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20080        final int moveId = mNextMoveId.getAndIncrement();
20081        mHandler.post(new Runnable() {
20082            @Override
20083            public void run() {
20084                try {
20085                    movePackageInternal(packageName, volumeUuid, moveId, user);
20086                } catch (PackageManagerException e) {
20087                    Slog.w(TAG, "Failed to move " + packageName, e);
20088                    mMoveCallbacks.notifyStatusChanged(moveId,
20089                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20090                }
20091            }
20092        });
20093        return moveId;
20094    }
20095
20096    private void movePackageInternal(final String packageName, final String volumeUuid,
20097            final int moveId, UserHandle user) throws PackageManagerException {
20098        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20099        final PackageManager pm = mContext.getPackageManager();
20100
20101        final boolean currentAsec;
20102        final String currentVolumeUuid;
20103        final File codeFile;
20104        final String installerPackageName;
20105        final String packageAbiOverride;
20106        final int appId;
20107        final String seinfo;
20108        final String label;
20109        final int targetSdkVersion;
20110        final PackageFreezer freezer;
20111        final int[] installedUserIds;
20112
20113        // reader
20114        synchronized (mPackages) {
20115            final PackageParser.Package pkg = mPackages.get(packageName);
20116            final PackageSetting ps = mSettings.mPackages.get(packageName);
20117            if (pkg == null || ps == null) {
20118                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20119            }
20120
20121            if (pkg.applicationInfo.isSystemApp()) {
20122                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20123                        "Cannot move system application");
20124            }
20125
20126            if (pkg.applicationInfo.isExternalAsec()) {
20127                currentAsec = true;
20128                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20129            } else if (pkg.applicationInfo.isForwardLocked()) {
20130                currentAsec = true;
20131                currentVolumeUuid = "forward_locked";
20132            } else {
20133                currentAsec = false;
20134                currentVolumeUuid = ps.volumeUuid;
20135
20136                final File probe = new File(pkg.codePath);
20137                final File probeOat = new File(probe, "oat");
20138                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20139                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20140                            "Move only supported for modern cluster style installs");
20141                }
20142            }
20143
20144            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20145                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20146                        "Package already moved to " + volumeUuid);
20147            }
20148            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20149                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20150                        "Device admin cannot be moved");
20151            }
20152
20153            if (mFrozenPackages.contains(packageName)) {
20154                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20155                        "Failed to move already frozen package");
20156            }
20157
20158            codeFile = new File(pkg.codePath);
20159            installerPackageName = ps.installerPackageName;
20160            packageAbiOverride = ps.cpuAbiOverrideString;
20161            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20162            seinfo = pkg.applicationInfo.seinfo;
20163            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20164            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20165            freezer = freezePackage(packageName, "movePackageInternal");
20166            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20167        }
20168
20169        final Bundle extras = new Bundle();
20170        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20171        extras.putString(Intent.EXTRA_TITLE, label);
20172        mMoveCallbacks.notifyCreated(moveId, extras);
20173
20174        int installFlags;
20175        final boolean moveCompleteApp;
20176        final File measurePath;
20177
20178        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20179            installFlags = INSTALL_INTERNAL;
20180            moveCompleteApp = !currentAsec;
20181            measurePath = Environment.getDataAppDirectory(volumeUuid);
20182        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20183            installFlags = INSTALL_EXTERNAL;
20184            moveCompleteApp = false;
20185            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20186        } else {
20187            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20188            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20189                    || !volume.isMountedWritable()) {
20190                freezer.close();
20191                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20192                        "Move location not mounted private volume");
20193            }
20194
20195            Preconditions.checkState(!currentAsec);
20196
20197            installFlags = INSTALL_INTERNAL;
20198            moveCompleteApp = true;
20199            measurePath = Environment.getDataAppDirectory(volumeUuid);
20200        }
20201
20202        final PackageStats stats = new PackageStats(null, -1);
20203        synchronized (mInstaller) {
20204            for (int userId : installedUserIds) {
20205                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20206                    freezer.close();
20207                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20208                            "Failed to measure package size");
20209                }
20210            }
20211        }
20212
20213        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20214                + stats.dataSize);
20215
20216        final long startFreeBytes = measurePath.getFreeSpace();
20217        final long sizeBytes;
20218        if (moveCompleteApp) {
20219            sizeBytes = stats.codeSize + stats.dataSize;
20220        } else {
20221            sizeBytes = stats.codeSize;
20222        }
20223
20224        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20225            freezer.close();
20226            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20227                    "Not enough free space to move");
20228        }
20229
20230        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20231
20232        final CountDownLatch installedLatch = new CountDownLatch(1);
20233        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20234            @Override
20235            public void onUserActionRequired(Intent intent) throws RemoteException {
20236                throw new IllegalStateException();
20237            }
20238
20239            @Override
20240            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20241                    Bundle extras) throws RemoteException {
20242                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20243                        + PackageManager.installStatusToString(returnCode, msg));
20244
20245                installedLatch.countDown();
20246                freezer.close();
20247
20248                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20249                switch (status) {
20250                    case PackageInstaller.STATUS_SUCCESS:
20251                        mMoveCallbacks.notifyStatusChanged(moveId,
20252                                PackageManager.MOVE_SUCCEEDED);
20253                        break;
20254                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20255                        mMoveCallbacks.notifyStatusChanged(moveId,
20256                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20257                        break;
20258                    default:
20259                        mMoveCallbacks.notifyStatusChanged(moveId,
20260                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20261                        break;
20262                }
20263            }
20264        };
20265
20266        final MoveInfo move;
20267        if (moveCompleteApp) {
20268            // Kick off a thread to report progress estimates
20269            new Thread() {
20270                @Override
20271                public void run() {
20272                    while (true) {
20273                        try {
20274                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20275                                break;
20276                            }
20277                        } catch (InterruptedException ignored) {
20278                        }
20279
20280                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20281                        final int progress = 10 + (int) MathUtils.constrain(
20282                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20283                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20284                    }
20285                }
20286            }.start();
20287
20288            final String dataAppName = codeFile.getName();
20289            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20290                    dataAppName, appId, seinfo, targetSdkVersion);
20291        } else {
20292            move = null;
20293        }
20294
20295        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20296
20297        final Message msg = mHandler.obtainMessage(INIT_COPY);
20298        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20299        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20300                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20301                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20302        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20303        msg.obj = params;
20304
20305        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20306                System.identityHashCode(msg.obj));
20307        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20308                System.identityHashCode(msg.obj));
20309
20310        mHandler.sendMessage(msg);
20311    }
20312
20313    @Override
20314    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20315        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20316
20317        final int realMoveId = mNextMoveId.getAndIncrement();
20318        final Bundle extras = new Bundle();
20319        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20320        mMoveCallbacks.notifyCreated(realMoveId, extras);
20321
20322        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20323            @Override
20324            public void onCreated(int moveId, Bundle extras) {
20325                // Ignored
20326            }
20327
20328            @Override
20329            public void onStatusChanged(int moveId, int status, long estMillis) {
20330                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20331            }
20332        };
20333
20334        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20335        storage.setPrimaryStorageUuid(volumeUuid, callback);
20336        return realMoveId;
20337    }
20338
20339    @Override
20340    public int getMoveStatus(int moveId) {
20341        mContext.enforceCallingOrSelfPermission(
20342                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20343        return mMoveCallbacks.mLastStatus.get(moveId);
20344    }
20345
20346    @Override
20347    public void registerMoveCallback(IPackageMoveObserver callback) {
20348        mContext.enforceCallingOrSelfPermission(
20349                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20350        mMoveCallbacks.register(callback);
20351    }
20352
20353    @Override
20354    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20355        mContext.enforceCallingOrSelfPermission(
20356                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20357        mMoveCallbacks.unregister(callback);
20358    }
20359
20360    @Override
20361    public boolean setInstallLocation(int loc) {
20362        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20363                null);
20364        if (getInstallLocation() == loc) {
20365            return true;
20366        }
20367        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20368                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20369            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20370                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20371            return true;
20372        }
20373        return false;
20374   }
20375
20376    @Override
20377    public int getInstallLocation() {
20378        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20379                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20380                PackageHelper.APP_INSTALL_AUTO);
20381    }
20382
20383    /** Called by UserManagerService */
20384    void cleanUpUser(UserManagerService userManager, int userHandle) {
20385        synchronized (mPackages) {
20386            mDirtyUsers.remove(userHandle);
20387            mUserNeedsBadging.delete(userHandle);
20388            mSettings.removeUserLPw(userHandle);
20389            mPendingBroadcasts.remove(userHandle);
20390            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20391            removeUnusedPackagesLPw(userManager, userHandle);
20392        }
20393    }
20394
20395    /**
20396     * We're removing userHandle and would like to remove any downloaded packages
20397     * that are no longer in use by any other user.
20398     * @param userHandle the user being removed
20399     */
20400    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20401        final boolean DEBUG_CLEAN_APKS = false;
20402        int [] users = userManager.getUserIds();
20403        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20404        while (psit.hasNext()) {
20405            PackageSetting ps = psit.next();
20406            if (ps.pkg == null) {
20407                continue;
20408            }
20409            final String packageName = ps.pkg.packageName;
20410            // Skip over if system app
20411            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20412                continue;
20413            }
20414            if (DEBUG_CLEAN_APKS) {
20415                Slog.i(TAG, "Checking package " + packageName);
20416            }
20417            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20418            if (keep) {
20419                if (DEBUG_CLEAN_APKS) {
20420                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20421                }
20422            } else {
20423                for (int i = 0; i < users.length; i++) {
20424                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20425                        keep = true;
20426                        if (DEBUG_CLEAN_APKS) {
20427                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20428                                    + users[i]);
20429                        }
20430                        break;
20431                    }
20432                }
20433            }
20434            if (!keep) {
20435                if (DEBUG_CLEAN_APKS) {
20436                    Slog.i(TAG, "  Removing package " + packageName);
20437                }
20438                mHandler.post(new Runnable() {
20439                    public void run() {
20440                        deletePackageX(packageName, userHandle, 0);
20441                    } //end run
20442                });
20443            }
20444        }
20445    }
20446
20447    /** Called by UserManagerService */
20448    void createNewUser(int userId) {
20449        synchronized (mInstallLock) {
20450            mSettings.createNewUserLI(this, mInstaller, userId);
20451        }
20452        synchronized (mPackages) {
20453            scheduleWritePackageRestrictionsLocked(userId);
20454            scheduleWritePackageListLocked(userId);
20455            applyFactoryDefaultBrowserLPw(userId);
20456            primeDomainVerificationsLPw(userId);
20457        }
20458    }
20459
20460    void onBeforeUserStartUninitialized(final int userId) {
20461        synchronized (mPackages) {
20462            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20463                return;
20464            }
20465        }
20466        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20467        // If permission review for legacy apps is required, we represent
20468        // dagerous permissions for such apps as always granted runtime
20469        // permissions to keep per user flag state whether review is needed.
20470        // Hence, if a new user is added we have to propagate dangerous
20471        // permission grants for these legacy apps.
20472        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20473            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20474                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20475        }
20476    }
20477
20478    @Override
20479    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20480        mContext.enforceCallingOrSelfPermission(
20481                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20482                "Only package verification agents can read the verifier device identity");
20483
20484        synchronized (mPackages) {
20485            return mSettings.getVerifierDeviceIdentityLPw();
20486        }
20487    }
20488
20489    @Override
20490    public void setPermissionEnforced(String permission, boolean enforced) {
20491        // TODO: Now that we no longer change GID for storage, this should to away.
20492        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20493                "setPermissionEnforced");
20494        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20495            synchronized (mPackages) {
20496                if (mSettings.mReadExternalStorageEnforced == null
20497                        || mSettings.mReadExternalStorageEnforced != enforced) {
20498                    mSettings.mReadExternalStorageEnforced = enforced;
20499                    mSettings.writeLPr();
20500                }
20501            }
20502            // kill any non-foreground processes so we restart them and
20503            // grant/revoke the GID.
20504            final IActivityManager am = ActivityManagerNative.getDefault();
20505            if (am != null) {
20506                final long token = Binder.clearCallingIdentity();
20507                try {
20508                    am.killProcessesBelowForeground("setPermissionEnforcement");
20509                } catch (RemoteException e) {
20510                } finally {
20511                    Binder.restoreCallingIdentity(token);
20512                }
20513            }
20514        } else {
20515            throw new IllegalArgumentException("No selective enforcement for " + permission);
20516        }
20517    }
20518
20519    @Override
20520    @Deprecated
20521    public boolean isPermissionEnforced(String permission) {
20522        return true;
20523    }
20524
20525    @Override
20526    public boolean isStorageLow() {
20527        final long token = Binder.clearCallingIdentity();
20528        try {
20529            final DeviceStorageMonitorInternal
20530                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20531            if (dsm != null) {
20532                return dsm.isMemoryLow();
20533            } else {
20534                return false;
20535            }
20536        } finally {
20537            Binder.restoreCallingIdentity(token);
20538        }
20539    }
20540
20541    @Override
20542    public IPackageInstaller getPackageInstaller() {
20543        return mInstallerService;
20544    }
20545
20546    private boolean userNeedsBadging(int userId) {
20547        int index = mUserNeedsBadging.indexOfKey(userId);
20548        if (index < 0) {
20549            final UserInfo userInfo;
20550            final long token = Binder.clearCallingIdentity();
20551            try {
20552                userInfo = sUserManager.getUserInfo(userId);
20553            } finally {
20554                Binder.restoreCallingIdentity(token);
20555            }
20556            final boolean b;
20557            if (userInfo != null && userInfo.isManagedProfile()) {
20558                b = true;
20559            } else {
20560                b = false;
20561            }
20562            mUserNeedsBadging.put(userId, b);
20563            return b;
20564        }
20565        return mUserNeedsBadging.valueAt(index);
20566    }
20567
20568    @Override
20569    public KeySet getKeySetByAlias(String packageName, String alias) {
20570        if (packageName == null || alias == null) {
20571            return null;
20572        }
20573        synchronized(mPackages) {
20574            final PackageParser.Package pkg = mPackages.get(packageName);
20575            if (pkg == null) {
20576                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20577                throw new IllegalArgumentException("Unknown package: " + packageName);
20578            }
20579            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20580            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20581        }
20582    }
20583
20584    @Override
20585    public KeySet getSigningKeySet(String packageName) {
20586        if (packageName == null) {
20587            return null;
20588        }
20589        synchronized(mPackages) {
20590            final PackageParser.Package pkg = mPackages.get(packageName);
20591            if (pkg == null) {
20592                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20593                throw new IllegalArgumentException("Unknown package: " + packageName);
20594            }
20595            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20596                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20597                throw new SecurityException("May not access signing KeySet of other apps.");
20598            }
20599            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20600            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20601        }
20602    }
20603
20604    @Override
20605    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20606        if (packageName == null || ks == null) {
20607            return false;
20608        }
20609        synchronized(mPackages) {
20610            final PackageParser.Package pkg = mPackages.get(packageName);
20611            if (pkg == null) {
20612                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20613                throw new IllegalArgumentException("Unknown package: " + packageName);
20614            }
20615            IBinder ksh = ks.getToken();
20616            if (ksh instanceof KeySetHandle) {
20617                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20618                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20619            }
20620            return false;
20621        }
20622    }
20623
20624    @Override
20625    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20626        if (packageName == null || ks == null) {
20627            return false;
20628        }
20629        synchronized(mPackages) {
20630            final PackageParser.Package pkg = mPackages.get(packageName);
20631            if (pkg == null) {
20632                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20633                throw new IllegalArgumentException("Unknown package: " + packageName);
20634            }
20635            IBinder ksh = ks.getToken();
20636            if (ksh instanceof KeySetHandle) {
20637                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20638                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20639            }
20640            return false;
20641        }
20642    }
20643
20644    private void deletePackageIfUnusedLPr(final String packageName) {
20645        PackageSetting ps = mSettings.mPackages.get(packageName);
20646        if (ps == null) {
20647            return;
20648        }
20649        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20650            // TODO Implement atomic delete if package is unused
20651            // It is currently possible that the package will be deleted even if it is installed
20652            // after this method returns.
20653            mHandler.post(new Runnable() {
20654                public void run() {
20655                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20656                }
20657            });
20658        }
20659    }
20660
20661    /**
20662     * Check and throw if the given before/after packages would be considered a
20663     * downgrade.
20664     */
20665    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20666            throws PackageManagerException {
20667        if (after.versionCode < before.mVersionCode) {
20668            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20669                    "Update version code " + after.versionCode + " is older than current "
20670                    + before.mVersionCode);
20671        } else if (after.versionCode == before.mVersionCode) {
20672            if (after.baseRevisionCode < before.baseRevisionCode) {
20673                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20674                        "Update base revision code " + after.baseRevisionCode
20675                        + " is older than current " + before.baseRevisionCode);
20676            }
20677
20678            if (!ArrayUtils.isEmpty(after.splitNames)) {
20679                for (int i = 0; i < after.splitNames.length; i++) {
20680                    final String splitName = after.splitNames[i];
20681                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20682                    if (j != -1) {
20683                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20684                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20685                                    "Update split " + splitName + " revision code "
20686                                    + after.splitRevisionCodes[i] + " is older than current "
20687                                    + before.splitRevisionCodes[j]);
20688                        }
20689                    }
20690                }
20691            }
20692        }
20693    }
20694
20695    private static class MoveCallbacks extends Handler {
20696        private static final int MSG_CREATED = 1;
20697        private static final int MSG_STATUS_CHANGED = 2;
20698
20699        private final RemoteCallbackList<IPackageMoveObserver>
20700                mCallbacks = new RemoteCallbackList<>();
20701
20702        private final SparseIntArray mLastStatus = new SparseIntArray();
20703
20704        public MoveCallbacks(Looper looper) {
20705            super(looper);
20706        }
20707
20708        public void register(IPackageMoveObserver callback) {
20709            mCallbacks.register(callback);
20710        }
20711
20712        public void unregister(IPackageMoveObserver callback) {
20713            mCallbacks.unregister(callback);
20714        }
20715
20716        @Override
20717        public void handleMessage(Message msg) {
20718            final SomeArgs args = (SomeArgs) msg.obj;
20719            final int n = mCallbacks.beginBroadcast();
20720            for (int i = 0; i < n; i++) {
20721                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20722                try {
20723                    invokeCallback(callback, msg.what, args);
20724                } catch (RemoteException ignored) {
20725                }
20726            }
20727            mCallbacks.finishBroadcast();
20728            args.recycle();
20729        }
20730
20731        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20732                throws RemoteException {
20733            switch (what) {
20734                case MSG_CREATED: {
20735                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20736                    break;
20737                }
20738                case MSG_STATUS_CHANGED: {
20739                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20740                    break;
20741                }
20742            }
20743        }
20744
20745        private void notifyCreated(int moveId, Bundle extras) {
20746            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20747
20748            final SomeArgs args = SomeArgs.obtain();
20749            args.argi1 = moveId;
20750            args.arg2 = extras;
20751            obtainMessage(MSG_CREATED, args).sendToTarget();
20752        }
20753
20754        private void notifyStatusChanged(int moveId, int status) {
20755            notifyStatusChanged(moveId, status, -1);
20756        }
20757
20758        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20759            Slog.v(TAG, "Move " + moveId + " status " + status);
20760
20761            final SomeArgs args = SomeArgs.obtain();
20762            args.argi1 = moveId;
20763            args.argi2 = status;
20764            args.arg3 = estMillis;
20765            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20766
20767            synchronized (mLastStatus) {
20768                mLastStatus.put(moveId, status);
20769            }
20770        }
20771    }
20772
20773    private final static class OnPermissionChangeListeners extends Handler {
20774        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20775
20776        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20777                new RemoteCallbackList<>();
20778
20779        public OnPermissionChangeListeners(Looper looper) {
20780            super(looper);
20781        }
20782
20783        @Override
20784        public void handleMessage(Message msg) {
20785            switch (msg.what) {
20786                case MSG_ON_PERMISSIONS_CHANGED: {
20787                    final int uid = msg.arg1;
20788                    handleOnPermissionsChanged(uid);
20789                } break;
20790            }
20791        }
20792
20793        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20794            mPermissionListeners.register(listener);
20795
20796        }
20797
20798        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20799            mPermissionListeners.unregister(listener);
20800        }
20801
20802        public void onPermissionsChanged(int uid) {
20803            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20804                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20805            }
20806        }
20807
20808        private void handleOnPermissionsChanged(int uid) {
20809            final int count = mPermissionListeners.beginBroadcast();
20810            try {
20811                for (int i = 0; i < count; i++) {
20812                    IOnPermissionsChangeListener callback = mPermissionListeners
20813                            .getBroadcastItem(i);
20814                    try {
20815                        callback.onPermissionsChanged(uid);
20816                    } catch (RemoteException e) {
20817                        Log.e(TAG, "Permission listener is dead", e);
20818                    }
20819                }
20820            } finally {
20821                mPermissionListeners.finishBroadcast();
20822            }
20823        }
20824    }
20825
20826    private class PackageManagerInternalImpl extends PackageManagerInternal {
20827        @Override
20828        public void setLocationPackagesProvider(PackagesProvider provider) {
20829            synchronized (mPackages) {
20830                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20831            }
20832        }
20833
20834        @Override
20835        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20836            synchronized (mPackages) {
20837                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20838            }
20839        }
20840
20841        @Override
20842        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20843            synchronized (mPackages) {
20844                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20845            }
20846        }
20847
20848        @Override
20849        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20850            synchronized (mPackages) {
20851                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20852            }
20853        }
20854
20855        @Override
20856        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20857            synchronized (mPackages) {
20858                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20859            }
20860        }
20861
20862        @Override
20863        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20864            synchronized (mPackages) {
20865                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20866            }
20867        }
20868
20869        @Override
20870        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20871            synchronized (mPackages) {
20872                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20873                        packageName, userId);
20874            }
20875        }
20876
20877        @Override
20878        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20879            synchronized (mPackages) {
20880                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20881                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20882                        packageName, userId);
20883            }
20884        }
20885
20886        @Override
20887        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20888            synchronized (mPackages) {
20889                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20890                        packageName, userId);
20891            }
20892        }
20893
20894        @Override
20895        public void setKeepUninstalledPackages(final List<String> packageList) {
20896            Preconditions.checkNotNull(packageList);
20897            List<String> removedFromList = null;
20898            synchronized (mPackages) {
20899                if (mKeepUninstalledPackages != null) {
20900                    final int packagesCount = mKeepUninstalledPackages.size();
20901                    for (int i = 0; i < packagesCount; i++) {
20902                        String oldPackage = mKeepUninstalledPackages.get(i);
20903                        if (packageList != null && packageList.contains(oldPackage)) {
20904                            continue;
20905                        }
20906                        if (removedFromList == null) {
20907                            removedFromList = new ArrayList<>();
20908                        }
20909                        removedFromList.add(oldPackage);
20910                    }
20911                }
20912                mKeepUninstalledPackages = new ArrayList<>(packageList);
20913                if (removedFromList != null) {
20914                    final int removedCount = removedFromList.size();
20915                    for (int i = 0; i < removedCount; i++) {
20916                        deletePackageIfUnusedLPr(removedFromList.get(i));
20917                    }
20918                }
20919            }
20920        }
20921
20922        @Override
20923        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20924            synchronized (mPackages) {
20925                // If we do not support permission review, done.
20926                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20927                    return false;
20928                }
20929
20930                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20931                if (packageSetting == null) {
20932                    return false;
20933                }
20934
20935                // Permission review applies only to apps not supporting the new permission model.
20936                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20937                    return false;
20938                }
20939
20940                // Legacy apps have the permission and get user consent on launch.
20941                PermissionsState permissionsState = packageSetting.getPermissionsState();
20942                return permissionsState.isPermissionReviewRequired(userId);
20943            }
20944        }
20945
20946        @Override
20947        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20948            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20949        }
20950
20951        @Override
20952        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20953                int userId) {
20954            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20955        }
20956
20957        @Override
20958        public void setDeviceAndProfileOwnerPackages(
20959                int deviceOwnerUserId, String deviceOwnerPackage,
20960                SparseArray<String> profileOwnerPackages) {
20961            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20962                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20963        }
20964
20965        @Override
20966        public boolean isPackageDataProtected(int userId, String packageName) {
20967            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20968        }
20969    }
20970
20971    @Override
20972    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20973        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20974        synchronized (mPackages) {
20975            final long identity = Binder.clearCallingIdentity();
20976            try {
20977                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20978                        packageNames, userId);
20979            } finally {
20980                Binder.restoreCallingIdentity(identity);
20981            }
20982        }
20983    }
20984
20985    private static void enforceSystemOrPhoneCaller(String tag) {
20986        int callingUid = Binder.getCallingUid();
20987        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20988            throw new SecurityException(
20989                    "Cannot call " + tag + " from UID " + callingUid);
20990        }
20991    }
20992
20993    boolean isHistoricalPackageUsageAvailable() {
20994        return mPackageUsage.isHistoricalPackageUsageAvailable();
20995    }
20996
20997    /**
20998     * Return a <b>copy</b> of the collection of packages known to the package manager.
20999     * @return A copy of the values of mPackages.
21000     */
21001    Collection<PackageParser.Package> getPackages() {
21002        synchronized (mPackages) {
21003            return new ArrayList<>(mPackages.values());
21004        }
21005    }
21006
21007    /**
21008     * Logs process start information (including base APK hash) to the security log.
21009     * @hide
21010     */
21011    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21012            String apkFile, int pid) {
21013        if (!SecurityLog.isLoggingEnabled()) {
21014            return;
21015        }
21016        Bundle data = new Bundle();
21017        data.putLong("startTimestamp", System.currentTimeMillis());
21018        data.putString("processName", processName);
21019        data.putInt("uid", uid);
21020        data.putString("seinfo", seinfo);
21021        data.putString("apkFile", apkFile);
21022        data.putInt("pid", pid);
21023        Message msg = mProcessLoggingHandler.obtainMessage(
21024                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21025        msg.setData(data);
21026        mProcessLoggingHandler.sendMessage(msg);
21027    }
21028}
21029